From 21298fa9c4b68b2b31435fa12f732e2152b7af01 Mon Sep 17 00:00:00 2001 From: CrazyJasonwell Date: Thu, 17 Jul 2025 15:56:06 +0800 Subject: [PATCH] vault backup: 2025-07-17 15:56:06 --- .obsidian/community-plugins.json | 4 +- .obsidian/plugins/cubox-sync/main.js | 133 + .obsidian/plugins/cubox-sync/manifest.json | 9 + .obsidian/plugins/cubox-sync/styles.css | 213 + .obsidian/plugins/github-sync/main.js | 4870 ++++ .obsidian/plugins/github-sync/manifest.json | 10 + .obsidian/plugins/github-sync/styles.css | 42 + .obsidian/plugins/link-favicon/manifest.json | 10 - .obsidian/plugins/obsidian-livesync/main.js | 12 + .../plugins/obsidian-livesync/manifest.json | 10 + .../plugins/obsidian-livesync/styles.css | 454 + .obsidian/plugins/obsidian-omnivore/main.js | 18905 ---------------- .../plugins/obsidian-omnivore/manifest.json | 10 - .../plugins/obsidian-omnivore/styles.css | 77 - .obsidian/plugins/omnisearch/main.js | 170 - .obsidian/plugins/omnisearch/manifest.json | 14 - .obsidian/plugins/omnisearch/styles.css | 135 - .obsidian/plugins/sync-contacts-macos/main.js | 1014 + .../plugins/sync-contacts-macos/manifest.json | 11 + 19 files changed, 6781 insertions(+), 19322 deletions(-) create mode 100644 .obsidian/plugins/cubox-sync/main.js create mode 100644 .obsidian/plugins/cubox-sync/manifest.json create mode 100644 .obsidian/plugins/cubox-sync/styles.css create mode 100644 .obsidian/plugins/github-sync/main.js create mode 100644 .obsidian/plugins/github-sync/manifest.json create mode 100644 .obsidian/plugins/github-sync/styles.css delete mode 100644 .obsidian/plugins/link-favicon/manifest.json create mode 100644 .obsidian/plugins/obsidian-livesync/main.js create mode 100644 .obsidian/plugins/obsidian-livesync/manifest.json create mode 100644 .obsidian/plugins/obsidian-livesync/styles.css delete mode 100644 .obsidian/plugins/obsidian-omnivore/main.js delete mode 100644 .obsidian/plugins/obsidian-omnivore/manifest.json delete mode 100644 .obsidian/plugins/obsidian-omnivore/styles.css delete mode 100644 .obsidian/plugins/omnisearch/main.js delete mode 100644 .obsidian/plugins/omnisearch/manifest.json delete mode 100644 .obsidian/plugins/omnisearch/styles.css create mode 100644 .obsidian/plugins/sync-contacts-macos/main.js create mode 100644 .obsidian/plugins/sync-contacts-macos/manifest.json diff --git a/.obsidian/community-plugins.json b/.obsidian/community-plugins.json index cb860f7a..53704f4f 100644 --- a/.obsidian/community-plugins.json +++ b/.obsidian/community-plugins.json @@ -37,5 +37,7 @@ "obsidian-linter", "media-extended", "recent-files-obsidian", - "diary-ics" + "diary-ics", + "sync-contacts-macos", + "cubox-sync" ] \ No newline at end of file diff --git a/.obsidian/plugins/cubox-sync/main.js b/.obsidian/plugins/cubox-sync/main.js new file mode 100644 index 00000000..209ac1c3 --- /dev/null +++ b/.obsidian/plugins/cubox-sync/main.js @@ -0,0 +1,133 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var Kt=Object.defineProperty;var pn=Object.getOwnPropertyDescriptor;var yn=Object.getOwnPropertyNames;var Tn=Object.prototype.hasOwnProperty;var En=(s,e)=>{for(var t in e)Kt(s,t,{get:e[t],enumerable:!0})},wn=(s,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of yn(e))!Tn.call(s,n)&&n!==t&&Kt(s,n,{get:()=>e[n],enumerable:!(r=pn(e,n))||r.enumerable});return s};var Sn=s=>wn(Kt({},"__esModule",{value:!0}),s);var fa={};En(fa,{default:()=>jt});module.exports=Sn(fa);var H=require("obsidian");var Ps=require("obsidian");var ye=require("obsidian"),W="all_folders",vt=class extends ye.Modal{constructor(t,r,n,i){super(t);this.selectedFolders=new Set;this.folders=[];this.folders=r,n&&n.length>0&&n.forEach(a=>{a&&this.selectedFolders.add(a)}),this.onConfirm=i}async onOpen(){let{contentEl:t}=this;t.createEl("h2",{text:"Manage Cubox folders to be synced"}),t.addClass("cubox-modal"),this.listEl=t.createDiv({cls:"folder-list-container cubox-list-container"}),this.footerEl=t.createDiv({cls:"modal-footer"}),this.createFolderList(),this.footerEl.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close()}),this.footerEl.createEl("button",{text:"Done",cls:"mod-cta"}).addEventListener("click",()=>{if(this.selectedFolders.size===0){new ye.Notice("Please select at least one option.");return}let i=this.selectedFolders.has(W)?[W]:Array.from(this.selectedFolders);this.onConfirm(i),this.close()})}createFolderList(){this.listEl.empty();let t=new ye.Setting(this.listEl).setName("All items");this.selectedFolders.has(W)&&t.settingEl.addClass("is-selected"),t.settingEl.addEventListener("click",()=>{let r=this.selectedFolders.has(W);this.handleFolderToggle(W,!r),this.redraw()}),this.folders.forEach(r=>{let n=new ye.Setting(this.listEl).setName(r.nested_name);this.selectedFolders.has(W)?n.settingEl.addClass("is-disabled"):(this.selectedFolders.has(r.id)&&n.settingEl.addClass("is-selected"),n.settingEl.addEventListener("click",()=>{let i=this.selectedFolders.has(r.id);this.handleFolderToggle(r.id,!i),this.redraw()}))})}isFolderSelected(t){return this.selectedFolders.has(t)}handleFolderToggle(t,r){t===W?r?(this.selectedFolders.clear(),this.selectedFolders.add(W)):this.selectedFolders.delete(W):r?(this.selectedFolders.delete(W),this.selectedFolders.add(t)):this.selectedFolders.delete(t)}redraw(){this.createFolderList()}onClose(){let{contentEl:t}=this;t.empty()}};var le=require("obsidian"),A="all_items",Qt="",Ft=class extends le.Modal{constructor(t,r,n,i){super(t);this.selectedTags=new Set;this.tags=[];this.tags=r,n&&n.length>0&&n.forEach(a=>{this.selectedTags.add(a)}),this.onConfirm=i}async onOpen(){let{contentEl:t}=this;t.createEl("h2",{text:"Manage Cubox tags to be synced"}),t.addClass("cubox-modal"),this.listEl=t.createDiv({cls:"tag-list-container cubox-list-container"}),this.footerEl=t.createDiv({cls:"modal-footer"}),this.createTagList(),this.footerEl.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close()}),this.footerEl.createEl("button",{text:"Done",cls:"mod-cta"}).addEventListener("click",()=>{if(this.selectedTags.size===0){new le.Notice("Please select at least one option.");return}let i=this.selectedTags.has(A)?[A]:Array.from(this.selectedTags);this.onConfirm(i),this.close()})}createTagList(){this.listEl.empty();let t=new le.Setting(this.listEl).setName("All items");this.selectedTags.has(A)&&t.settingEl.addClass("is-selected"),t.settingEl.addEventListener("click",()=>{let n=this.selectedTags.has(A);this.handleTagToggle(A,!n),this.redraw()});let r=new le.Setting(this.listEl).setName("No tags");this.selectedTags.has(A)?r.settingEl.addClass("is-disabled"):(this.selectedTags.has(Qt)&&r.settingEl.addClass("is-selected"),r.settingEl.addEventListener("click",()=>{let n=this.selectedTags.has(Qt);this.handleTagToggle(Qt,!n),this.redraw()})),this.tags.forEach(n=>{let i=new le.Setting(this.listEl).setName(n.nested_name);this.selectedTags.has(A)?i.settingEl.addClass("is-disabled"):(this.selectedTags.has(n.id)&&i.settingEl.addClass("is-selected"),i.settingEl.addEventListener("click",()=>{let a=this.selectedTags.has(n.id);this.handleTagToggle(n.id,!a),this.redraw()}))})}isTagSelected(t){return this.selectedTags.has(t)}handleTagToggle(t,r){t===A?r?(this.selectedTags.clear(),this.selectedTags.add(A)):this.selectedTags.delete(A):r?(this.selectedTags.delete(A),this.selectedTags.add(t)):this.selectedTags.delete(t)}redraw(){this.createTagList()}onClose(){let{contentEl:t}=this;t.empty()}};var ve=require("obsidian"),ue="all",kt=class extends ve.Modal{constructor(t,r,n={},i){super(t);this.statuses=[{id:"all",name:"All items"},{id:"read",name:"Already read items only",value:!0},{id:"starred",name:"Starred items only",value:!0},{id:"annotated",name:"Annotated items only",value:!0}];this.selectedStatuses=new Set;this.statusValues=new Map;this.onSave=i,this.statuses.forEach(a=>{if(a.id!=="all"){let o=n[a.id]!==void 0?n[a.id]:a.value||!0;this.statusValues.set(a.id,o)}}),r&&r.length>0&&r.forEach(a=>{a&&this.selectedStatuses.add(a)})}async onOpen(){let{contentEl:t}=this;t.createEl("h2",{text:"Manage Cubox content status to be synced"}),t.addClass("cubox-modal"),this.listEl=t.createDiv({cls:"status-list-container cubox-list-container"}),this.footerEl=t.createDiv({cls:"modal-footer"}),this.createStatusList(),this.footerEl.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close()}),this.footerEl.createEl("button",{text:"Done",cls:"mod-cta"}).addEventListener("click",()=>{if(this.selectedStatuses.size===0){new ve.Notice("Please select at least one option.");return}let i=Array.from(this.selectedStatuses),a={};this.statusValues.forEach((o,l)=>{a[l]=o}),this.onSave(i,a),this.close()})}createStatusList(){this.listEl.empty(),this.statuses.forEach(t=>{let r=new ve.Setting(this.listEl).setName(t.name);t.id===ue?(this.selectedStatuses.has(t.id)&&r.settingEl.addClass("is-selected"),r.settingEl.addEventListener("click",()=>{let n=this.selectedStatuses.has(t.id);this.handleStatusToggle(t.id,!n),this.redraw()})):this.selectedStatuses.has(ue)?r.settingEl.addClass("is-disabled"):(this.selectedStatuses.has(t.id)&&r.settingEl.addClass("is-selected"),r.settingEl.addEventListener("click",()=>{let n=this.selectedStatuses.has(t.id);this.handleStatusToggle(t.id,!n),this.redraw()}))})}handleStatusToggle(t,r){t===ue?r?(this.selectedStatuses.clear(),this.selectedStatuses.add(ue),this.statuses.forEach(n=>{n.id!=="all"&&this.statusValues.set(n.id,!1)})):this.selectedStatuses.delete(ue):(r?(this.selectedStatuses.delete(ue),this.selectedStatuses.add(t)):this.selectedStatuses.delete(t),this.statusValues.set(t,r))}redraw(){this.createStatusList()}onClose(){let{contentEl:t}=this;t.empty()}};var bt=class{constructor(e,t){this.endpoint=`https://${e}`,this.apiKey=t}updateConfig(e,t){this.endpoint=`https://${e}`,this.apiKey=t}async request(e,t={}){let r=`${this.endpoint}${e}`,n={Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"};t.headers&&Object.entries(t.headers).forEach(([a,o])=>{typeof o=="string"&&(n[a]=o)});let i=await(0,Ps.requestUrl)({url:r,method:t.method||"GET",body:t.body,headers:n});if(i.status>=400)throw new Error(`API request failed: ${i.status}`);return JSON.parse(i.text)}async getArticles(e={lastCardId:null,lastCardUpdateTime:null}){var t;try{let r={limit:50},n=50;e.lastCardId!==null&&e.lastCardId.length>0&&e.lastCardUpdateTime!==null&&e.lastCardUpdateTime.length>0&&(r.last_card_id=e.lastCardId,r.last_card_update_time=e.lastCardUpdateTime),e.folderFilter&&e.folderFilter.length>0&&(e.folderFilter.includes(W)||(r.group_filters=e.folderFilter)),e.typeFilter&&e.typeFilter.length>0&&(r.type_filters=e.typeFilter),e.statusFilter&&e.statusFilter.length>0&&(e.statusFilter.includes(ue)||(e.isRead===!0&&(r.read=!0),e.isStarred===!0&&(r.starred=!0),e.isAnnotated===!0&&(r.annotated=!0))),e.tagsFilter&&e.tagsFilter.length>0&&(e.tagsFilter.includes(A)||(r.tag_filters=e.tagsFilter));let i="/c/api/third-party/card/filter",o=(t=(await this.request(i,{method:"POST",body:JSON.stringify(r)})).data)!=null?t:[],l=o&&o.length>=n;return{articles:o,hasMore:l}}catch(r){throw console.error("\u83B7\u53D6\u6587\u7AE0\u5217\u8868\u5931\u8D25:",r),r}}async getArticleDetail(e){try{let t=`/c/api/third-party/card/content?id=${e}`;return(await this.request(t)).data}catch(t){return console.error(`\u83B7\u53D6\u6587\u7AE0 ${e} \u8BE6\u60C5\u5931\u8D25:`,t),null}}async getFolders(){var e;try{let t="/c/api/third-party/group/list";return(e=(await this.request(t)).data)!=null?e:[]}catch(t){throw console.error("\u83B7\u53D6 Cubox \u6587\u4EF6\u5939\u5217\u8868\u5931\u8D25:",t),t}}async getTags(){var e;try{let t="/c/api/third-party/tag/list";return(e=(await this.request(t)).data)!=null?e:[]}catch(t){throw console.error("\u83B7\u53D6 Cubox \u6807\u7B7E\u5217\u8868\u5931\u8D25:",t),t}}};var ie=class extends Error{},It=class extends ie{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}},Ot=class extends ie{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}},Ct=class extends ie{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}},G=class extends ie{},Fe=class extends ie{constructor(e){super(`Invalid unit ${e}`)}},D=class extends ie{},J=class extends ie{constructor(){super("Zone is an abstract class")}};var d="numeric",j="short",U="long",ce={year:d,month:d,day:d},ze={year:d,month:j,day:d},Xt={year:d,month:j,day:d,weekday:j},Be={year:d,month:U,day:d},Ye={year:d,month:U,day:d,weekday:U},Ge={hour:d,minute:d},Je={hour:d,minute:d,second:d},je={hour:d,minute:d,second:d,timeZoneName:j},Ke={hour:d,minute:d,second:d,timeZoneName:U},Qe={hour:d,minute:d,hourCycle:"h23"},Xe={hour:d,minute:d,second:d,hourCycle:"h23"},et={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:j},tt={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:U},st={year:d,month:d,day:d,hour:d,minute:d},rt={year:d,month:d,day:d,hour:d,minute:d,second:d},nt={year:d,month:j,day:d,hour:d,minute:d},it={year:d,month:j,day:d,hour:d,minute:d,second:d},es={year:d,month:j,day:d,weekday:j,hour:d,minute:d},at={year:d,month:U,day:d,hour:d,minute:d,timeZoneName:j},ot={year:d,month:U,day:d,hour:d,minute:d,second:d,timeZoneName:j},lt={year:d,month:U,day:d,weekday:U,hour:d,minute:d,timeZoneName:U},ut={year:d,month:U,day:d,weekday:U,hour:d,minute:d,second:d,timeZoneName:U};var R=class{get type(){throw new J}get name(){throw new J}get ianaName(){return this.name}get isUniversal(){throw new J}offsetName(e,t){throw new J}formatOffset(e,t){throw new J}offset(e){throw new J}equals(e){throw new J}get isValid(){throw new J}};var ts=null,ee=class extends R{static get instance(){return ts===null&&(ts=new ee),ts}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:t,locale:r}){return Mt(e,t,r)}formatOffset(e,t){return de(this.offset(e),t)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}};var _t={};function xn(s){return _t[s]||(_t[s]=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"})),_t[s]}var vn={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Fn(s,e){let t=s.format(e).replace(/\u200E/g,""),r=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(t),[,n,i,a,o,l,u,c]=r;return[a,n,i,o,l,u,c]}function kn(s,e){let t=s.formatToParts(e),r=[];for(let n=0;n=0?k:1e3+k,(y-g)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}};var qs={};function bn(s,e={}){let t=JSON.stringify([s,e]),r=qs[t];return r||(r=new Intl.ListFormat(s,e),qs[t]=r),r}var ss={};function rs(s,e={}){let t=JSON.stringify([s,e]),r=ss[t];return r||(r=new Intl.DateTimeFormat(s,e),ss[t]=r),r}var ns={};function In(s,e={}){let t=JSON.stringify([s,e]),r=ns[t];return r||(r=new Intl.NumberFormat(s,e),ns[t]=r),r}var is={};function On(s,e={}){let{base:t,...r}=e,n=JSON.stringify([s,r]),i=is[n];return i||(i=new Intl.RelativeTimeFormat(s,e),is[n]=i),i}var ct=null;function Cn(){return ct||(ct=new Intl.DateTimeFormat().resolvedOptions().locale,ct)}var zs={};function Dn(s){let e=zs[s];if(!e){let t=new Intl.Locale(s);e="getWeekInfo"in t?t.getWeekInfo():t.weekInfo,zs[s]=e}return e}function Mn(s){let e=s.indexOf("-x-");e!==-1&&(s=s.substring(0,e));let t=s.indexOf("-u-");if(t===-1)return[s];{let r,n;try{r=rs(s).resolvedOptions(),n=s}catch(o){let l=s.substring(0,t);r=rs(l).resolvedOptions(),n=l}let{numberingSystem:i,calendar:a}=r;return[n,i,a]}}function Nn(s,e,t){return(t||e)&&(s.includes("-u-")||(s+="-u"),t&&(s+=`-ca-${t}`),e&&(s+=`-nu-${e}`)),s}function _n(s){let e=[];for(let t=1;t<=12;t++){let r=f.utc(2009,t,1);e.push(s(r))}return e}function An(s){let e=[];for(let t=1;t<=7;t++){let r=f.utc(2016,11,13+t);e.push(s(r))}return e}function At(s,e,t,r){let n=s.listingMode();return n==="error"?null:n==="en"?t(e):r(e)}function Ln(s){return s.numberingSystem&&s.numberingSystem!=="latn"?!1:s.numberingSystem==="latn"||!s.locale||s.locale.startsWith("en")||new Intl.DateTimeFormat(s.intl).resolvedOptions().numberingSystem==="latn"}var as=class{constructor(e,t,r){this.padTo=r.padTo||0,this.floor=r.floor||!1;let{padTo:n,floor:i,...a}=r;if(!t||Object.keys(a).length>0){let o={useGrouping:!1,...r};r.padTo>0&&(o.minimumIntegerDigits=r.padTo),this.inf=In(e,o)}}format(e){if(this.inf){let t=this.floor?Math.floor(e):e;return this.inf.format(t)}else{let t=this.floor?Math.floor(e):be(e,3);return I(t,this.padTo)}}},os=class{constructor(e,t,r){this.opts=r,this.originalZone=void 0;let n;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){let a=-1*(e.offset/60),o=a>=0?`Etc/GMT+${a}`:`Etc/GMT${a}`;e.offset!==0&&N.create(o).valid?(n=o,this.dt=e):(n="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,n=e.zone.name):(n="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);let i={...this.opts};i.timeZone=i.timeZone||n,this.dtf=rs(t,i)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){let e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(t=>{if(t.type==="timeZoneName"){let r=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...t,value:r}}else return t}):e}resolvedOptions(){return this.dtf.resolvedOptions()}},ls=class{constructor(e,t,r){this.opts={style:"long",...r},!t&&Lt()&&(this.rtf=On(e,r))}format(e,t){return this.rtf?this.rtf.format(e,t):Bs(t,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,t){return this.rtf?this.rtf.formatToParts(e,t):[]}},Vn={firstDay:1,minimalDays:4,weekend:[6,7]},T=class{static fromOpts(e){return T.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,t,r,n,i=!1){let a=e||E.defaultLocale,o=a||(i?"en-US":Cn()),l=t||E.defaultNumberingSystem,u=r||E.defaultOutputCalendar,c=dt(n)||E.defaultWeekSettings;return new T(o,l,u,c,a)}static resetCache(){ct=null,ss={},ns={},is={}}static fromObject({locale:e,numberingSystem:t,outputCalendar:r,weekSettings:n}={}){return T.create(e,t,r,n)}constructor(e,t,r,n,i){let[a,o,l]=Mn(e);this.locale=a,this.numberingSystem=t||o||null,this.outputCalendar=r||l||null,this.weekSettings=n,this.intl=Nn(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=i,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Ln(this)),this.fastNumbersCached}listingMode(){let e=this.isEnglish(),t=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&t?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:T.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,dt(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,t=!1){return At(this,e,us,()=>{let r=t?{month:e,day:"numeric"}:{month:e},n=t?"format":"standalone";return this.monthsCache[n][e]||(this.monthsCache[n][e]=_n(i=>this.extract(i,r,"month"))),this.monthsCache[n][e]})}weekdays(e,t=!1){return At(this,e,cs,()=>{let r=t?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},n=t?"format":"standalone";return this.weekdaysCache[n][e]||(this.weekdaysCache[n][e]=An(i=>this.extract(i,r,"weekday"))),this.weekdaysCache[n][e]})}meridiems(){return At(this,void 0,()=>ds,()=>{if(!this.meridiemCache){let e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[f.utc(2016,11,13,9),f.utc(2016,11,13,19)].map(t=>this.extract(t,e,"dayperiod"))}return this.meridiemCache})}eras(e){return At(this,e,hs,()=>{let t={era:e};return this.eraCache[e]||(this.eraCache[e]=[f.utc(-40,1,1),f.utc(2017,1,1)].map(r=>this.extract(r,t,"era"))),this.eraCache[e]})}extract(e,t,r){let n=this.dtFormatter(e,t),i=n.formatToParts(),a=i.find(o=>o.type.toLowerCase()===r);return a?a.value:null}numberFormatter(e={}){return new as(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,t={}){return new os(e,this.intl,t)}relFormatter(e={}){return new ls(this.intl,this.isEnglish(),e)}listFormatter(e={}){return bn(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Vt()?Dn(this.locale):Vn}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}};var ms=null,O=class extends R{static get utcInstance(){return ms===null&&(ms=new O(0)),ms}static instance(e){return e===0?O.utcInstance:new O(e)}static parseSpecifier(e){if(e){let t=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(t)return new O(Te(t[1],t[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${de(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${de(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,t){return de(this.fixed,t)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}};var Ie=class extends R{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}};function K(s,e){let t;if(m(s)||s===null)return e;if(s instanceof R)return s;if(Ys(s)){let r=s.toLowerCase();return r==="default"?e:r==="local"||r==="system"?ee.instance:r==="utc"||r==="gmt"?O.utcInstance:O.parseSpecifier(r)||N.create(s)}else return Q(s)?O.instance(s):typeof s=="object"&&"offset"in s&&typeof s.offset=="function"?s:new Ie(s)}var gs={arab:"[\u0660-\u0669]",arabext:"[\u06F0-\u06F9]",bali:"[\u1B50-\u1B59]",beng:"[\u09E6-\u09EF]",deva:"[\u0966-\u096F]",fullwide:"[\uFF10-\uFF19]",gujr:"[\u0AE6-\u0AEF]",hanidec:"[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]",khmr:"[\u17E0-\u17E9]",knda:"[\u0CE6-\u0CEF]",laoo:"[\u0ED0-\u0ED9]",limb:"[\u1946-\u194F]",mlym:"[\u0D66-\u0D6F]",mong:"[\u1810-\u1819]",mymr:"[\u1040-\u1049]",orya:"[\u0B66-\u0B6F]",tamldec:"[\u0BE6-\u0BEF]",telu:"[\u0C66-\u0C6F]",thai:"[\u0E50-\u0E59]",tibt:"[\u0F20-\u0F29]",latn:"\\d"},Gs={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Wn=gs.hanidec.replace(/[\[|\]]/g,"").split("");function Js(s){let e=parseInt(s,10);if(isNaN(e)){e="";for(let t=0;t=i&&r<=a&&(e+=r-i)}}return parseInt(e,10)}else return e}var Oe={};function js(){Oe={}}function P({numberingSystem:s},e=""){let t=s||"latn";return Oe[t]||(Oe[t]={}),Oe[t][e]||(Oe[t][e]=new RegExp(`${gs[t]}${e}`)),Oe[t][e]}var Ks=()=>Date.now(),Qs="system",Xs=null,er=null,tr=null,sr=60,rr,nr=null,E=class{static get now(){return Ks}static set now(e){Ks=e}static set defaultZone(e){Qs=e}static get defaultZone(){return K(Qs,ee.instance)}static get defaultLocale(){return Xs}static set defaultLocale(e){Xs=e}static get defaultNumberingSystem(){return er}static set defaultNumberingSystem(e){er=e}static get defaultOutputCalendar(){return tr}static set defaultOutputCalendar(e){tr=e}static get defaultWeekSettings(){return nr}static set defaultWeekSettings(e){nr=dt(e)}static get twoDigitCutoffYear(){return sr}static set twoDigitCutoffYear(e){sr=e%100}static get throwOnInvalid(){return rr}static set throwOnInvalid(e){rr=e}static resetCaches(){T.resetCache(),N.resetCache(),f.resetCache(),js()}};var _=class{constructor(e,t){this.reason=e,this.explanation=t}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}};var ir=[0,31,59,90,120,151,181,212,243,273,304,334],ar=[0,31,60,91,121,152,182,213,244,274,305,335];function q(s,e){return new _("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${s}, which is invalid`)}function Wt(s,e,t){let r=new Date(Date.UTC(s,e-1,t));s<100&&s>=0&&r.setUTCFullYear(r.getUTCFullYear()-1900);let n=r.getUTCDay();return n===0?7:n}function or(s,e,t){return t+(we(s)?ar:ir)[e-1]}function lr(s,e){let t=we(s)?ar:ir,r=t.findIndex(i=>iEe(r,e,t)?(u=r+1,l=1):u=r,{weekYear:u,weekNumber:l,weekday:o,...mt(s)}}function ps(s,e=4,t=1){let{weekYear:r,weekNumber:n,weekday:i}=s,a=Rt(Wt(r,1,e),t),o=he(r),l=n*7+i-a-7+e,u;l<1?(u=r-1,l+=he(u)):l>o?(u=r+1,l-=he(r)):u=r;let{month:c,day:h}=lr(u,l);return{year:u,month:c,day:h,...mt(s)}}function Ht(s){let{year:e,month:t,day:r}=s,n=or(e,t,r);return{year:e,ordinal:n,...mt(s)}}function ys(s){let{year:e,ordinal:t}=s,{month:r,day:n}=lr(e,t);return{year:e,month:r,day:n,...mt(s)}}function Ts(s,e){if(!m(s.localWeekday)||!m(s.localWeekNumber)||!m(s.localWeekYear)){if(!m(s.weekday)||!m(s.weekNumber)||!m(s.weekYear))throw new G("Cannot mix locale-based week fields with ISO-based week fields");return m(s.localWeekday)||(s.weekday=s.localWeekday),m(s.localWeekNumber)||(s.weekNumber=s.localWeekNumber),m(s.localWeekYear)||(s.weekYear=s.localWeekYear),delete s.localWeekday,delete s.localWeekNumber,delete s.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function ur(s,e=4,t=1){let r=ft(s.weekYear),n=$(s.weekNumber,1,Ee(s.weekYear,e,t)),i=$(s.weekday,1,7);return r?n?i?!1:q("weekday",s.weekday):q("week",s.weekNumber):q("weekYear",s.weekYear)}function cr(s){let e=ft(s.year),t=$(s.ordinal,1,he(s.year));return e?t?!1:q("ordinal",s.ordinal):q("year",s.year)}function Es(s){let e=ft(s.year),t=$(s.month,1,12),r=$(s.day,1,Ce(s.year,s.month));return e?t?r?!1:q("day",s.day):q("month",s.month):q("year",s.year)}function ws(s){let{hour:e,minute:t,second:r,millisecond:n}=s,i=$(e,0,23)||e===24&&t===0&&r===0&&n===0,a=$(t,0,59),o=$(r,0,59),l=$(n,0,999);return i?a?o?l?!1:q("millisecond",n):q("second",r):q("minute",t):q("hour",e)}function m(s){return typeof s=="undefined"}function Q(s){return typeof s=="number"}function ft(s){return typeof s=="number"&&s%1===0}function Ys(s){return typeof s=="string"}function hr(s){return Object.prototype.toString.call(s)==="[object Date]"}function Lt(){try{return typeof Intl!="undefined"&&!!Intl.RelativeTimeFormat}catch(s){return!1}}function Vt(){try{return typeof Intl!="undefined"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch(s){return!1}}function fr(s){return Array.isArray(s)?s:[s]}function Ss(s,e,t){if(s.length!==0)return s.reduce((r,n)=>{let i=[e(n),n];return r&&t(r[0],i[0])===r[0]?r:i},null)[1]}function mr(s,e){return e.reduce((t,r)=>(t[r]=s[r],t),{})}function fe(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function dt(s){if(s==null)return null;if(typeof s!="object")throw new D("Week settings must be an object");if(!$(s.firstDay,1,7)||!$(s.minimalDays,1,7)||!Array.isArray(s.weekend)||s.weekend.some(e=>!$(e,1,7)))throw new D("Invalid week settings");return{firstDay:s.firstDay,minimalDays:s.minimalDays,weekend:Array.from(s.weekend)}}function $(s,e,t){return ft(s)&&s>=e&&s<=t}function Rn(s,e){return s-e*Math.floor(s/e)}function I(s,e=2){let t=s<0,r;return t?r="-"+(""+-s).padStart(e,"0"):r=(""+s).padStart(e,"0"),r}function ae(s){if(!(m(s)||s===null||s===""))return parseInt(s,10)}function me(s){if(!(m(s)||s===null||s===""))return parseFloat(s)}function gt(s){if(!(m(s)||s===null||s==="")){let e=parseFloat("0."+s)*1e3;return Math.floor(e)}}function be(s,e,t=!1){let r=10**e;return(t?Math.trunc:Math.round)(s*r)/r}function we(s){return s%4===0&&(s%100!==0||s%400===0)}function he(s){return we(s)?366:365}function Ce(s,e){let t=Rn(e-1,12)+1,r=s+(e-t)/12;return t===2?we(r)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][t-1]}function ke(s){let e=Date.UTC(s.year,s.month-1,s.day,s.hour,s.minute,s.second,s.millisecond);return s.year<100&&s.year>=0&&(e=new Date(e),e.setUTCFullYear(s.year,s.month-1,s.day)),+e}function dr(s,e,t){return-Rt(Wt(s,1,e),t)+e-1}function Ee(s,e=4,t=1){let r=dr(s,e,t),n=dr(s+1,e,t);return(he(s)-r+n)/7}function pt(s){return s>99?s:s>E.twoDigitCutoffYear?1900+s:2e3+s}function Mt(s,e,t,r=null){let n=new Date(s),i={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};r&&(i.timeZone=r);let a={timeZoneName:e,...i},o=new Intl.DateTimeFormat(t,a).formatToParts(n).find(l=>l.type.toLowerCase()==="timezonename");return o?o.value:null}function Te(s,e){let t=parseInt(s,10);Number.isNaN(t)&&(t=0);let r=parseInt(e,10)||0,n=t<0||Object.is(t,-0)?-r:r;return t*60+n}function xs(s){let e=Number(s);if(typeof s=="boolean"||s===""||Number.isNaN(e))throw new D(`Invalid unit value ${s}`);return e}function De(s,e){let t={};for(let r in s)if(fe(s,r)){let n=s[r];if(n==null)continue;t[e(r)]=xs(n)}return t}function de(s,e){let t=Math.trunc(Math.abs(s/60)),r=Math.trunc(Math.abs(s%60)),n=s>=0?"+":"-";switch(e){case"short":return`${n}${I(t,2)}:${I(r,2)}`;case"narrow":return`${n}${t}${r>0?`:${r}`:""}`;case"techie":return`${n}${I(t,2)}${I(r,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function mt(s){return mr(s,["hour","minute","second","millisecond"])}var Hn=["January","February","March","April","May","June","July","August","September","October","November","December"],vs=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Un=["J","F","M","A","M","J","J","A","S","O","N","D"];function us(s){switch(s){case"narrow":return[...Un];case"short":return[...vs];case"long":return[...Hn];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var Fs=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],ks=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],$n=["M","T","W","T","F","S","S"];function cs(s){switch(s){case"narrow":return[...$n];case"short":return[...ks];case"long":return[...Fs];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var ds=["AM","PM"],Zn=["Before Christ","Anno Domini"],Pn=["BC","AD"],qn=["B","A"];function hs(s){switch(s){case"narrow":return[...qn];case"short":return[...Pn];case"long":return[...Zn];default:return null}}function gr(s){return ds[s.hour<12?0:1]}function pr(s,e){return cs(e)[s.weekday-1]}function yr(s,e){return us(e)[s.month-1]}function Tr(s,e){return hs(e)[s.year<0?0:1]}function Bs(s,e,t="always",r=!1){let n={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},i=["hours","minutes","seconds"].indexOf(s)===-1;if(t==="auto"&&i){let h=s==="days";switch(e){case 1:return h?"tomorrow":`next ${n[s][0]}`;case-1:return h?"yesterday":`last ${n[s][0]}`;case 0:return h?"today":`this ${n[s][0]}`;default:}}let a=Object.is(e,-0)||e<0,o=Math.abs(e),l=o===1,u=n[s],c=r?l?u[1]:u[2]||u[1]:l?n[s][0]:s;return a?`${o} ${c} ago`:`in ${o} ${c}`}function Er(s,e){let t="";for(let r of s)r.literal?t+=r.val:t+=e(r.val);return t}var zn={D:ce,DD:ze,DDD:Be,DDDD:Ye,t:Ge,tt:Je,ttt:je,tttt:Ke,T:Qe,TT:Xe,TTT:et,TTTT:tt,f:st,ff:nt,fff:at,ffff:lt,F:rt,FF:it,FFF:ot,FFFF:ut},C=class{static create(e,t={}){return new C(e,t)}static parseFormat(e){let t=null,r="",n=!1,i=[];for(let a=0;a0&&i.push({literal:n||/^\s+$/.test(r),val:r}),t=null,r="",n=!n):n||o===t?r+=o:(r.length>0&&i.push({literal:/^\s+$/.test(r),val:r}),r=o,t=o)}return r.length>0&&i.push({literal:n||/^\s+$/.test(r),val:r}),i}static macroTokenToFormatOpts(e){return zn[e]}constructor(e,t){this.opts=t,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,t){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...t}).format()}dtFormatter(e,t={}){return this.loc.dtFormatter(e,{...this.opts,...t})}formatDateTime(e,t){return this.dtFormatter(e,t).format()}formatDateTimeParts(e,t){return this.dtFormatter(e,t).formatToParts()}formatInterval(e,t){return this.dtFormatter(e.start,t).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,t){return this.dtFormatter(e,t).resolvedOptions()}num(e,t=0){if(this.opts.forceSimple)return I(e,t);let r={...this.opts};return t>0&&(r.padTo=t),this.loc.numberFormatter(r).format(e)}formatDateTimeFromString(e,t){let r=this.loc.listingMode()==="en",n=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",i=(g,k)=>this.loc.extract(e,g,k),a=g=>e.isOffsetFixed&&e.offset===0&&g.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,g.format):"",o=()=>r?gr(e):i({hour:"numeric",hourCycle:"h12"},"dayperiod"),l=(g,k)=>r?yr(e,g):i(k?{month:g}:{month:g,day:"numeric"},"month"),u=(g,k)=>r?pr(e,g):i(k?{weekday:g}:{weekday:g,month:"long",day:"numeric"},"weekday"),c=g=>{let k=C.macroTokenToFormatOpts(g);return k?this.formatWithSystemDefault(e,k):g},h=g=>r?Tr(e,g):i({era:g},"era"),y=g=>{switch(g){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return a({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return a({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return a({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return o();case"d":return n?i({day:"numeric"},"day"):this.num(e.day);case"dd":return n?i({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return u("short",!0);case"cccc":return u("long",!0);case"ccccc":return u("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return u("short",!1);case"EEEE":return u("long",!1);case"EEEEE":return u("narrow",!1);case"L":return n?i({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return n?i({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return l("short",!0);case"LLLL":return l("long",!0);case"LLLLL":return l("narrow",!0);case"M":return n?i({month:"numeric"},"month"):this.num(e.month);case"MM":return n?i({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return l("short",!1);case"MMMM":return l("long",!1);case"MMMMM":return l("narrow",!1);case"y":return n?i({year:"numeric"},"year"):this.num(e.year);case"yy":return n?i({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return n?i({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return n?i({year:"numeric"},"year"):this.num(e.year,6);case"G":return h("short");case"GG":return h("long");case"GGGGG":return h("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return c(g)}};return Er(C.parseFormat(t),y)}formatDurationFromString(e,t){let r=l=>{switch(l[0]){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":return"hour";case"d":return"day";case"w":return"week";case"M":return"month";case"y":return"year";default:return null}},n=l=>u=>{let c=r(u);return c?this.num(l.get(c),u.length):u},i=C.parseFormat(t),a=i.reduce((l,{literal:u,val:c})=>u?l:l.concat(c),[]),o=e.shiftTo(...a.map(r).filter(l=>l));return Er(i,n(o))}};var Sr=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Ne(...s){let e=s.reduce((t,r)=>t+r.source,"");return RegExp(`^${e}$`)}function _e(...s){return e=>s.reduce(([t,r,n],i)=>{let[a,o,l]=i(e,n);return[{...t,...a},o||r,l]},[{},null,1]).slice(0,2)}function Ae(s,...e){if(s==null)return[null,null];for(let[t,r]of e){let n=t.exec(s);if(n)return r(n)}return[null,null]}function xr(...s){return(e,t)=>{let r={},n;for(n=0;ng!==void 0&&(k||g&&c)?-g:g;return[{years:y(me(t)),months:y(me(r)),weeks:y(me(n)),days:y(me(i)),hours:y(me(a)),minutes:y(me(o)),seconds:y(me(l),l==="-0"),milliseconds:y(gt(u),h)}]}var ni={GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function Os(s,e,t,r,n,i,a){let o={year:e.length===2?pt(ae(e)):ae(e),month:vs.indexOf(t)+1,day:ae(r),hour:ae(n),minute:ae(i)};return a&&(o.second=ae(a)),s&&(o.weekday=s.length>3?Fs.indexOf(s)+1:ks.indexOf(s)+1),o}var ii=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function ai(s){let[,e,t,r,n,i,a,o,l,u,c,h]=s,y=Os(e,n,r,t,i,a,o),g;return l?g=ni[l]:u?g=0:g=Te(c,h),[y,new O(g)]}function oi(s){return s.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var li=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,ui=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,ci=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function wr(s){let[,e,t,r,n,i,a,o]=s;return[Os(e,n,r,t,i,a,o),O.utcInstance]}function di(s){let[,e,t,r,n,i,a,o]=s;return[Os(e,o,t,r,n,i,a),O.utcInstance]}var hi=Ne(Yn,Is),fi=Ne(Gn,Is),mi=Ne(Jn,Is),gi=Ne(Fr),br=_e(ei,Le,yt,Tt),pi=_e(jn,Le,yt,Tt),yi=_e(Kn,Le,yt,Tt),Ti=_e(Le,yt,Tt);function Ir(s){return Ae(s,[hi,br],[fi,pi],[mi,yi],[gi,Ti])}function Or(s){return Ae(oi(s),[ii,ai])}function Cr(s){return Ae(s,[li,wr],[ui,wr],[ci,di])}function Dr(s){return Ae(s,[si,ri])}var Ei=_e(Le);function Mr(s){return Ae(s,[ti,Ei])}var wi=Ne(Qn,Xn),Si=Ne(kr),xi=_e(Le,yt,Tt);function Nr(s){return Ae(s,[wi,br],[Si,xi])}var _r="Invalid Duration",Lr={weeks:{days:7,hours:7*24,minutes:7*24*60,seconds:7*24*60*60,milliseconds:7*24*60*60*1e3},days:{hours:24,minutes:24*60,seconds:24*60*60,milliseconds:24*60*60*1e3},hours:{minutes:60,seconds:60*60,milliseconds:60*60*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},vi={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:91*24,minutes:91*24*60,seconds:91*24*60*60,milliseconds:91*24*60*60*1e3},months:{weeks:4,days:30,hours:30*24,minutes:30*24*60,seconds:30*24*60*60,milliseconds:30*24*60*60*1e3},...Lr},z=146097/400,Ve=146097/4800,Fi={years:{quarters:4,months:12,weeks:z/7,days:z,hours:z*24,minutes:z*24*60,seconds:z*24*60*60,milliseconds:z*24*60*60*1e3},quarters:{months:3,weeks:z/28,days:z/4,hours:z*24/4,minutes:z*24*60/4,seconds:z*24*60*60/4,milliseconds:z*24*60*60*1e3/4},months:{weeks:Ve/7,days:Ve,hours:Ve*24,minutes:Ve*24*60,seconds:Ve*24*60*60,milliseconds:Ve*24*60*60*1e3},...Lr},Se=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],ki=Se.slice(0).reverse();function ge(s,e,t=!1){let r={values:t?e.values:{...s.values,...e.values||{}},loc:s.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||s.conversionAccuracy,matrix:e.matrix||s.matrix};return new p(r)}function Vr(s,e){var r;let t=(r=e.milliseconds)!=null?r:0;for(let n of ki.slice(1))e[n]&&(t+=e[n]*s[n].milliseconds);return t}function Ar(s,e){let t=Vr(s,e)<0?-1:1;Se.reduceRight((r,n)=>{if(m(e[n]))return r;if(r){let i=e[r]*t,a=s[n][r],o=Math.floor(i/a);e[n]+=o*t,e[r]-=o*a*t}return n},null),Se.reduce((r,n)=>{if(m(e[n]))return r;if(r){let i=e[r]%1;e[r]-=i,e[n]+=i*s[r][n]}return n},null)}function bi(s){let e={};for(let[t,r]of Object.entries(s))r!==0&&(e[t]=r);return e}var p=class{constructor(e){let t=e.conversionAccuracy==="longterm"||!1,r=t?Fi:vi;e.matrix&&(r=e.matrix),this.values=e.values,this.loc=e.loc||T.create(),this.conversionAccuracy=t?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=r,this.isLuxonDuration=!0}static fromMillis(e,t){return p.fromObject({milliseconds:e},t)}static fromObject(e,t={}){if(e==null||typeof e!="object")throw new D(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new p({values:De(e,p.normalizeUnit),loc:T.fromObject(t),conversionAccuracy:t.conversionAccuracy,matrix:t.matrix})}static fromDurationLike(e){if(Q(e))return p.fromMillis(e);if(p.isDuration(e))return e;if(typeof e=="object")return p.fromObject(e);throw new D(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,t){let[r]=Dr(e);return r?p.fromObject(r,t):p.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,t){let[r]=Mr(e);return r?p.fromObject(r,t):p.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,t=null){if(!e)throw new D("need to specify a reason the Duration is invalid");let r=e instanceof _?e:new _(e,t);if(E.throwOnInvalid)throw new Ct(r);return new p({invalid:r})}static normalizeUnit(e){let t={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!t)throw new Fe(e);return t}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,t={}){let r={...t,floor:t.round!==!1&&t.floor!==!1};return this.isValid?C.create(this.loc,r).formatDurationFromString(this,e):_r}toHuman(e={}){if(!this.isValid)return _r;let t=Se.map(r=>{let n=this.values[r];return m(n)?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:r.slice(0,-1)}).format(n)}).filter(r=>r);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(t)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=be(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;let t=this.toMillis();return t<0||t>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},f.fromMillis(t,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?Vr(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;let t=p.fromDurationLike(e),r={};for(let n of Se)(fe(t.values,n)||fe(this.values,n))&&(r[n]=t.get(n)+this.get(n));return ge(this,{values:r},!0)}minus(e){if(!this.isValid)return this;let t=p.fromDurationLike(e);return this.plus(t.negate())}mapUnits(e){if(!this.isValid)return this;let t={};for(let r of Object.keys(this.values))t[r]=xs(e(this.values[r],r));return ge(this,{values:t},!0)}get(e){return this[p.normalizeUnit(e)]}set(e){if(!this.isValid)return this;let t={...this.values,...De(e,p.normalizeUnit)};return ge(this,{values:t})}reconfigure({locale:e,numberingSystem:t,conversionAccuracy:r,matrix:n}={}){let a={loc:this.loc.clone({locale:e,numberingSystem:t}),matrix:n,conversionAccuracy:r};return ge(this,a)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;let e=this.toObject();return Ar(this.matrix,e),ge(this,{values:e},!0)}rescale(){if(!this.isValid)return this;let e=bi(this.normalize().shiftToAll().toObject());return ge(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(a=>p.normalizeUnit(a));let t={},r={},n=this.toObject(),i;for(let a of Se)if(e.indexOf(a)>=0){i=a;let o=0;for(let u in r)o+=this.matrix[u][a]*r[u],r[u]=0;Q(n[a])&&(o+=n[a]);let l=Math.trunc(o);t[a]=l,r[a]=(o*1e3-l*1e3)/1e3}else Q(n[a])&&(r[a]=n[a]);for(let a in r)r[a]!==0&&(t[i]+=a===i?r[a]:r[a]/this.matrix[i][a]);return Ar(this.matrix,t),ge(this,{values:t},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;let e={};for(let t of Object.keys(this.values))e[t]=this.values[t]===0?0:-this.values[t];return ge(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function t(r,n){return r===void 0||r===0?n===void 0||n===0:r===n}for(let r of Se)if(!t(this.values[r],e.values[r]))return!1;return!0}};var We="Invalid Interval";function Ii(s,e){return!s||!s.isValid?v.invalid("missing or invalid start"):!e||!e.isValid?v.invalid("missing or invalid end"):ee:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:t}={}){return this.isValid?v.fromDateTimes(e||this.s,t||this.e):this}splitAt(...e){if(!this.isValid)return[];let t=e.map(Re).filter(a=>this.contains(a)).sort((a,o)=>a.toMillis()-o.toMillis()),r=[],{s:n}=this,i=0;for(;n+this.e?this.e:a;r.push(v.fromDateTimes(n,o)),n=o,i+=1}return r}splitBy(e){let t=p.fromDurationLike(e);if(!this.isValid||!t.isValid||t.as("milliseconds")===0)return[];let{s:r}=this,n=1,i,a=[];for(;rl*n));i=+o>+this.e?this.e:o,a.push(v.fromDateTimes(r,i)),r=i,n+=1}return a}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;let t=this.s>e.s?this.s:e.s,r=this.e=r?null:v.fromDateTimes(t,r)}union(e){if(!this.isValid)return this;let t=this.se.e?this.e:e.e;return v.fromDateTimes(t,r)}static merge(e){let[t,r]=e.sort((n,i)=>n.s-i.s).reduce(([n,i],a)=>i?i.overlaps(a)||i.abutsStart(a)?[n,i.union(a)]:[n.concat([i]),a]:[n,a],[[],null]);return r&&t.push(r),t}static xor(e){let t=null,r=0,n=[],i=e.map(l=>[{time:l.s,type:"s"},{time:l.e,type:"e"}]),a=Array.prototype.concat(...i),o=a.sort((l,u)=>l.time-u.time);for(let l of o)r+=l.type==="s"?1:-1,r===1?t=l.time:(t&&+t!=+l.time&&n.push(v.fromDateTimes(t,l.time)),t=null);return v.merge(n)}difference(...e){return v.xor([this].concat(e)).map(t=>this.intersection(t)).filter(t=>t&&!t.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} \u2013 ${this.e.toISO()})`:We}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=ce,t={}){return this.isValid?C.create(this.s.loc.clone(t),e).formatInterval(this):We}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:We}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:We}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:We}toFormat(e,{separator:t=" \u2013 "}={}){return this.isValid?`${this.s.toFormat(e)}${t}${this.e.toFormat(e)}`:We}toDuration(e,t){return this.isValid?this.e.diff(this.s,e,t):p.invalid(this.invalidReason)}mapEndpoints(e){return v.fromDateTimes(e(this.s),e(this.e))}};var oe=class{static hasDST(e=E.defaultZone){let t=f.now().setZone(e).set({month:12});return!e.isUniversal&&t.offset!==t.set({month:6}).offset}static isValidIANAZone(e){return N.isValidZone(e)}static normalizeZone(e){return K(e,E.defaultZone)}static getStartOfWeek({locale:e=null,locObj:t=null}={}){return(t||T.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:t=null}={}){return(t||T.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:t=null}={}){return(t||T.create(e)).getWeekendDays().slice()}static months(e="long",{locale:t=null,numberingSystem:r=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||T.create(t,r,i)).months(e)}static monthsFormat(e="long",{locale:t=null,numberingSystem:r=null,locObj:n=null,outputCalendar:i="gregory"}={}){return(n||T.create(t,r,i)).months(e,!0)}static weekdays(e="long",{locale:t=null,numberingSystem:r=null,locObj:n=null}={}){return(n||T.create(t,r,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:t=null,numberingSystem:r=null,locObj:n=null}={}){return(n||T.create(t,r,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return T.create(e).meridiems()}static eras(e="short",{locale:t=null}={}){return T.create(t,null,"gregory").eras(e)}static features(){return{relative:Lt(),localeWeek:Vt()}}};function Wr(s,e){let t=n=>n.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),r=t(e)-t(s);return Math.floor(p.fromMillis(r).as("days"))}function Oi(s,e,t){let r=[["years",(l,u)=>u.year-l.year],["quarters",(l,u)=>u.quarter-l.quarter+(u.year-l.year)*4],["months",(l,u)=>u.month-l.month+(u.year-l.year)*12],["weeks",(l,u)=>{let c=Wr(l,u);return(c-c%7)/7}],["days",Wr]],n={},i=s,a,o;for(let[l,u]of r)t.indexOf(l)>=0&&(a=l,n[l]=u(s,e),o=i.plus(n),o>e?(n[l]--,s=i.plus(n),s>e&&(o=s,n[l]--,s=i.plus(n))):s=o);return[s,n,o,a]}function Rr(s,e,t,r){let[n,i,a,o]=Oi(s,e,t),l=e-n,u=t.filter(h=>["hours","minutes","seconds","milliseconds"].indexOf(h)>=0);u.length===0&&(a0?p.fromMillis(l,r).shiftTo(...u).plus(c):c}var Ci="missing Intl.DateTimeFormat.formatToParts support";function w(s,e=t=>t){return{regex:s,deser:([t])=>e(Js(t))}}var Di=String.fromCharCode(160),$r=`[ ${Di}]`,Zr=new RegExp($r,"g");function Mi(s){return s.replace(/\./g,"\\.?").replace(Zr,$r)}function Hr(s){return s.replace(/\./g,"").replace(Zr," ").toLowerCase()}function X(s,e){return s===null?null:{regex:RegExp(s.map(Mi).join("|")),deser:([t])=>s.findIndex(r=>Hr(t)===Hr(r))+e}}function Ur(s,e){return{regex:s,deser:([,t,r])=>Te(t,r),groups:e}}function Ut(s){return{regex:s,deser:([e])=>e}}function Ni(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function _i(s,e){let t=P(e),r=P(e,"{2}"),n=P(e,"{3}"),i=P(e,"{4}"),a=P(e,"{6}"),o=P(e,"{1,2}"),l=P(e,"{1,3}"),u=P(e,"{1,6}"),c=P(e,"{1,9}"),h=P(e,"{2,4}"),y=P(e,"{4,6}"),g=F=>({regex:RegExp(Ni(F.val)),deser:([b])=>b,literal:!0}),S=(F=>{if(s.literal)return g(F);switch(F.val){case"G":return X(e.eras("short"),0);case"GG":return X(e.eras("long"),0);case"y":return w(u);case"yy":return w(h,pt);case"yyyy":return w(i);case"yyyyy":return w(y);case"yyyyyy":return w(a);case"M":return w(o);case"MM":return w(r);case"MMM":return X(e.months("short",!0),1);case"MMMM":return X(e.months("long",!0),1);case"L":return w(o);case"LL":return w(r);case"LLL":return X(e.months("short",!1),1);case"LLLL":return X(e.months("long",!1),1);case"d":return w(o);case"dd":return w(r);case"o":return w(l);case"ooo":return w(n);case"HH":return w(r);case"H":return w(o);case"hh":return w(r);case"h":return w(o);case"mm":return w(r);case"m":return w(o);case"q":return w(o);case"qq":return w(r);case"s":return w(o);case"ss":return w(r);case"S":return w(l);case"SSS":return w(n);case"u":return Ut(c);case"uu":return Ut(o);case"uuu":return w(t);case"a":return X(e.meridiems(),0);case"kkkk":return w(i);case"kk":return w(h,pt);case"W":return w(o);case"WW":return w(r);case"E":case"c":return w(t);case"EEE":return X(e.weekdays("short",!1),1);case"EEEE":return X(e.weekdays("long",!1),1);case"ccc":return X(e.weekdays("short",!0),1);case"cccc":return X(e.weekdays("long",!0),1);case"Z":case"ZZ":return Ur(new RegExp(`([+-]${o.source})(?::(${r.source}))?`),2);case"ZZZ":return Ur(new RegExp(`([+-]${o.source})(${r.source})?`),2);case"z":return Ut(/[a-z_+-/]{1,256}?/i);case" ":return Ut(/[^\S\n\r]/);default:return g(F)}})(s)||{invalidReason:Ci};return S.token=s,S}var Ai={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function Li(s,e,t){let{type:r,value:n}=s;if(r==="literal"){let l=/^\s+$/.test(n);return{literal:!l,val:l?" ":n}}let i=e[r],a=r;r==="hour"&&(e.hour12!=null?a=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?a="hour12":a="hour24":a=t.hour12?"hour12":"hour24");let o=Ai[a];if(typeof o=="object"&&(o=o[i]),o)return{literal:!1,val:o}}function Vi(s){return[`^${s.map(t=>t.regex).reduce((t,r)=>`${t}(${r.source})`,"")}$`,s]}function Wi(s,e,t){let r=s.match(e);if(r){let n={},i=1;for(let a in t)if(fe(t,a)){let o=t[a],l=o.groups?o.groups+1:1;!o.literal&&o.token&&(n[o.token.val[0]]=o.deser(r.slice(i,i+l))),i+=l}return[r,n]}else return[r,{}]}function Ri(s){let e=i=>{switch(i){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},t=null,r;return m(s.z)||(t=N.create(s.z)),m(s.Z)||(t||(t=new O(s.Z)),r=s.Z),m(s.q)||(s.M=(s.q-1)*3+1),m(s.h)||(s.h<12&&s.a===1?s.h+=12:s.h===12&&s.a===0&&(s.h=0)),s.G===0&&s.y&&(s.y=-s.y),m(s.u)||(s.S=gt(s.u)),[Object.keys(s).reduce((i,a)=>{let o=e(a);return o&&(i[o]=s[a]),i},{}),t,r]}var Cs=null;function Hi(){return Cs||(Cs=f.fromMillis(1555555555555)),Cs}function Ui(s,e){if(s.literal)return s;let t=C.macroTokenToFormatOpts(s.val),r=Ns(t,e);return r==null||r.includes(void 0)?s:r}function Ds(s,e){return Array.prototype.concat(...s.map(t=>Ui(t,e)))}var Et=class{constructor(e,t){if(this.locale=e,this.format=t,this.tokens=Ds(C.parseFormat(t),e),this.units=this.tokens.map(r=>_i(r,e)),this.disqualifyingUnit=this.units.find(r=>r.invalidReason),!this.disqualifyingUnit){let[r,n]=Vi(this.units);this.regex=RegExp(r,"i"),this.handlers=n}}explainFromTokens(e){if(this.isValid){let[t,r]=Wi(e,this.regex,this.handlers),[n,i,a]=r?Ri(r):[null,null,void 0];if(fe(r,"a")&&fe(r,"H"))throw new G("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:t,matches:r,result:n,zone:i,specificOffset:a}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}};function Ms(s,e,t){return new Et(s,t).explainFromTokens(e)}function Pr(s,e,t){let{result:r,zone:n,specificOffset:i,invalidReason:a}=Ms(s,e,t);return[r,n,i,a]}function Ns(s,e){if(!s)return null;let r=C.create(e,s).dtFormatter(Hi()),n=r.formatToParts(),i=r.resolvedOptions();return n.map(a=>Li(a,s,i))}var _s="Invalid DateTime",qr=864e13;function wt(s){return new _("unsupported zone",`the zone "${s.name}" is not supported`)}function As(s){return s.weekData===null&&(s.weekData=ht(s.c)),s.weekData}function Ls(s){return s.localWeekData===null&&(s.localWeekData=ht(s.c,s.loc.getMinDaysInFirstWeek(),s.loc.getStartOfWeek())),s.localWeekData}function xe(s,e){let t={ts:s.ts,zone:s.zone,c:s.c,o:s.o,loc:s.loc,invalid:s.invalid};return new f({...t,...e,old:t})}function Kr(s,e,t){let r=s-e*60*1e3,n=t.offset(r);if(e===n)return[r,e];r-=(n-e)*60*1e3;let i=t.offset(r);return n===i?[r,n]:[s-Math.min(n,i)*60*1e3,Math.max(n,i)]}function $t(s,e){s+=e*60*1e3;let t=new Date(s);return{year:t.getUTCFullYear(),month:t.getUTCMonth()+1,day:t.getUTCDate(),hour:t.getUTCHours(),minute:t.getUTCMinutes(),second:t.getUTCSeconds(),millisecond:t.getUTCMilliseconds()}}function Pt(s,e,t){return Kr(ke(s),e,t)}function zr(s,e){let t=s.o,r=s.c.year+Math.trunc(e.years),n=s.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,i={...s.c,year:r,month:n,day:Math.min(s.c.day,Ce(r,n))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},a=p.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),o=ke(i),[l,u]=Kr(o,t,s.zone);return a!==0&&(l+=a,u=s.zone.offset(l)),{ts:l,o:u}}function He(s,e,t,r,n,i){let{setZone:a,zone:o}=t;if(s&&Object.keys(s).length!==0||e){let l=e||o,u=f.fromObject(s,{...t,zone:l,specificOffset:i});return a?u:u.setZone(o)}else return f.invalid(new _("unparsable",`the input "${n}" can't be parsed as ${r}`))}function Zt(s,e,t=!0){return s.isValid?C.create(T.create("en-US"),{allowZ:t,forceSimple:!0}).formatDateTimeFromString(s,e):null}function Vs(s,e){let t=s.c.year>9999||s.c.year<0,r="";return t&&s.c.year>=0&&(r+="+"),r+=I(s.c.year,t?6:4),e?(r+="-",r+=I(s.c.month),r+="-",r+=I(s.c.day)):(r+=I(s.c.month),r+=I(s.c.day)),r}function Br(s,e,t,r,n,i){let a=I(s.c.hour);return e?(a+=":",a+=I(s.c.minute),(s.c.millisecond!==0||s.c.second!==0||!t)&&(a+=":")):a+=I(s.c.minute),(s.c.millisecond!==0||s.c.second!==0||!t)&&(a+=I(s.c.second),(s.c.millisecond!==0||!r)&&(a+=".",a+=I(s.c.millisecond,3))),n&&(s.isOffsetFixed&&s.offset===0&&!i?a+="Z":s.o<0?(a+="-",a+=I(Math.trunc(-s.o/60)),a+=":",a+=I(Math.trunc(-s.o%60))):(a+="+",a+=I(Math.trunc(s.o/60)),a+=":",a+=I(Math.trunc(s.o%60)))),i&&(a+="["+s.zone.ianaName+"]"),a}var Qr={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},$i={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Zi={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Xr=["year","month","day","hour","minute","second","millisecond"],Pi=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],qi=["year","ordinal","hour","minute","second","millisecond"];function zi(s){let e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[s.toLowerCase()];if(!e)throw new Fe(s);return e}function Yr(s){switch(s.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return zi(s)}}function Bi(s){return zt[s]||(qt===void 0&&(qt=E.now()),zt[s]=s.offset(qt)),zt[s]}function Gr(s,e){let t=K(e.zone,E.defaultZone);if(!t.isValid)return f.invalid(wt(t));let r=T.fromObject(e),n,i;if(m(s.year))n=E.now();else{for(let l of Xr)m(s[l])&&(s[l]=Qr[l]);let a=Es(s)||ws(s);if(a)return f.invalid(a);let o=Bi(t);[n,i]=Pt(s,o,t)}return new f({ts:n,zone:t,loc:r,o:i})}function Jr(s,e,t){let r=m(t.round)?!0:t.round,n=(a,o)=>(a=be(a,r||t.calendary?0:2,!0),e.loc.clone(t).relFormatter(t).format(a,o)),i=a=>t.calendary?e.hasSame(s,a)?0:e.startOf(a).diff(s.startOf(a),a).get(a):e.diff(s,a).get(a);if(t.unit)return n(i(t.unit),t.unit);for(let a of t.units){let o=i(a);if(Math.abs(o)>=1)return n(o,a)}return n(s>e?-0:0,t.units[t.units.length-1])}function jr(s){let e={},t;return s.length>0&&typeof s[s.length-1]=="object"?(e=s[s.length-1],t=Array.from(s).slice(0,s.length-1)):t=Array.from(s),[e,t]}var qt,zt={},f=class{constructor(e){let t=e.zone||E.defaultZone,r=e.invalid||(Number.isNaN(e.ts)?new _("invalid input"):null)||(t.isValid?null:wt(t));this.ts=m(e.ts)?E.now():e.ts;let n=null,i=null;if(!r)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(t))[n,i]=[e.old.c,e.old.o];else{let o=Q(e.o)&&!e.old?e.o:t.offset(this.ts);n=$t(this.ts,o),r=Number.isNaN(n.year)?new _("invalid input"):null,n=r?null:n,i=r?null:o}this._zone=t,this.loc=e.loc||T.create(),this.invalid=r,this.weekData=null,this.localWeekData=null,this.c=n,this.o=i,this.isLuxonDateTime=!0}static now(){return new f({})}static local(){let[e,t]=jr(arguments),[r,n,i,a,o,l,u]=t;return Gr({year:r,month:n,day:i,hour:a,minute:o,second:l,millisecond:u},e)}static utc(){let[e,t]=jr(arguments),[r,n,i,a,o,l,u]=t;return e.zone=O.utcInstance,Gr({year:r,month:n,day:i,hour:a,minute:o,second:l,millisecond:u},e)}static fromJSDate(e,t={}){let r=hr(e)?e.valueOf():NaN;if(Number.isNaN(r))return f.invalid("invalid input");let n=K(t.zone,E.defaultZone);return n.isValid?new f({ts:r,zone:n,loc:T.fromObject(t)}):f.invalid(wt(n))}static fromMillis(e,t={}){if(Q(e))return e<-qr||e>qr?f.invalid("Timestamp out of range"):new f({ts:e,zone:K(t.zone,E.defaultZone),loc:T.fromObject(t)});throw new D(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,t={}){if(Q(e))return new f({ts:e*1e3,zone:K(t.zone,E.defaultZone),loc:T.fromObject(t)});throw new D("fromSeconds requires a numerical input")}static fromObject(e,t={}){e=e||{};let r=K(t.zone,E.defaultZone);if(!r.isValid)return f.invalid(wt(r));let n=T.fromObject(t),i=De(e,Yr),{minDaysInFirstWeek:a,startOfWeek:o}=Ts(i,n),l=E.now(),u=m(t.specificOffset)?r.offset(l):t.specificOffset,c=!m(i.ordinal),h=!m(i.year),y=!m(i.month)||!m(i.day),g=h||y,k=i.weekYear||i.weekNumber;if((g||c)&&k)throw new G("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(y&&c)throw new G("Can't mix ordinal dates with month/day");let S=k||i.weekday&&!g,F,b,M=$t(l,u);S?(F=Pi,b=$i,M=ht(M,a,o)):c?(F=qi,b=Zi,M=Ht(M)):(F=Xr,b=Qr);let Y=!1;for(let qe of F){let gn=i[qe];m(gn)?Y?i[qe]=b[qe]:i[qe]=M[qe]:Y=!0}let se=S?ur(i,a,o):c?cr(i):Es(i),Z=se||ws(i);if(Z)return f.invalid(Z);let re=S?ps(i,a,o):c?ys(i):i,[ne,V]=Pt(re,u,r),Pe=new f({ts:ne,zone:r,o:V,loc:n});return i.weekday&&g&&e.weekday!==Pe.weekday?f.invalid("mismatched weekday",`you can't specify both a weekday of ${i.weekday} and a date of ${Pe.toISO()}`):Pe.isValid?Pe:f.invalid(Pe.invalid)}static fromISO(e,t={}){let[r,n]=Ir(e);return He(r,n,t,"ISO 8601",e)}static fromRFC2822(e,t={}){let[r,n]=Or(e);return He(r,n,t,"RFC 2822",e)}static fromHTTP(e,t={}){let[r,n]=Cr(e);return He(r,n,t,"HTTP",t)}static fromFormat(e,t,r={}){if(m(e)||m(t))throw new D("fromFormat requires an input string and a format");let{locale:n=null,numberingSystem:i=null}=r,a=T.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0}),[o,l,u,c]=Pr(a,e,t);return c?f.invalid(c):He(o,l,r,`format ${t}`,e,u)}static fromString(e,t,r={}){return f.fromFormat(e,t,r)}static fromSQL(e,t={}){let[r,n]=Nr(e);return He(r,n,t,"SQL",e)}static invalid(e,t=null){if(!e)throw new D("need to specify a reason the DateTime is invalid");let r=e instanceof _?e:new _(e,t);if(E.throwOnInvalid)throw new It(r);return new f({invalid:r})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,t={}){let r=Ns(e,T.fromObject(t));return r?r.map(n=>n?n.val:null).join(""):null}static expandFormat(e,t={}){return Ds(C.parseFormat(e),T.fromObject(t)).map(n=>n.val).join("")}static resetCache(){qt=void 0,zt={}}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?As(this).weekYear:NaN}get weekNumber(){return this.isValid?As(this).weekNumber:NaN}get weekday(){return this.isValid?As(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Ls(this).weekday:NaN}get localWeekNumber(){return this.isValid?Ls(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Ls(this).weekYear:NaN}get ordinal(){return this.isValid?Ht(this.c).ordinal:NaN}get monthShort(){return this.isValid?oe.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?oe.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?oe.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?oe.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let e=864e5,t=6e4,r=ke(this.c),n=this.zone.offset(r-e),i=this.zone.offset(r+e),a=this.zone.offset(r-n*t),o=this.zone.offset(r-i*t);if(a===o)return[this];let l=r-a*t,u=r-o*t,c=$t(l,a),h=$t(u,o);return c.hour===h.hour&&c.minute===h.minute&&c.second===h.second&&c.millisecond===h.millisecond?[xe(this,{ts:l}),xe(this,{ts:u})]:[this]}get isInLeapYear(){return we(this.year)}get daysInMonth(){return Ce(this.year,this.month)}get daysInYear(){return this.isValid?he(this.year):NaN}get weeksInWeekYear(){return this.isValid?Ee(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Ee(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){let{locale:t,numberingSystem:r,calendar:n}=C.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:t,numberingSystem:r,outputCalendar:n}}toUTC(e=0,t={}){return this.setZone(O.instance(e),t)}toLocal(){return this.setZone(E.defaultZone)}setZone(e,{keepLocalTime:t=!1,keepCalendarTime:r=!1}={}){if(e=K(e,E.defaultZone),e.equals(this.zone))return this;if(e.isValid){let n=this.ts;if(t||r){let i=e.offset(this.ts),a=this.toObject();[n]=Pt(a,i,e)}return xe(this,{ts:n,zone:e})}else return f.invalid(wt(e))}reconfigure({locale:e,numberingSystem:t,outputCalendar:r}={}){let n=this.loc.clone({locale:e,numberingSystem:t,outputCalendar:r});return xe(this,{loc:n})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;let t=De(e,Yr),{minDaysInFirstWeek:r,startOfWeek:n}=Ts(t,this.loc),i=!m(t.weekYear)||!m(t.weekNumber)||!m(t.weekday),a=!m(t.ordinal),o=!m(t.year),l=!m(t.month)||!m(t.day),u=o||l,c=t.weekYear||t.weekNumber;if((u||a)&&c)throw new G("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(l&&a)throw new G("Can't mix ordinal dates with month/day");let h;i?h=ps({...ht(this.c,r,n),...t},r,n):m(t.ordinal)?(h={...this.toObject(),...t},m(t.day)&&(h.day=Math.min(Ce(h.year,h.month),h.day))):h=ys({...Ht(this.c),...t});let[y,g]=Pt(h,this.o,this.zone);return xe(this,{ts:y,o:g})}plus(e){if(!this.isValid)return this;let t=p.fromDurationLike(e);return xe(this,zr(this,t))}minus(e){if(!this.isValid)return this;let t=p.fromDurationLike(e).negate();return xe(this,zr(this,t))}startOf(e,{useLocaleWeeks:t=!1}={}){if(!this.isValid)return this;let r={},n=p.normalizeUnit(e);switch(n){case"years":r.month=1;case"quarters":case"months":r.day=1;case"weeks":case"days":r.hour=0;case"hours":r.minute=0;case"minutes":r.second=0;case"seconds":r.millisecond=0;break;case"milliseconds":break}if(n==="weeks")if(t){let i=this.loc.getStartOfWeek(),{weekday:a}=this;athis.valueOf(),o=a?this:e,l=a?e:this,u=Rr(o,l,i,n);return a?u.negate():u}diffNow(e="milliseconds",t={}){return this.diff(f.now(),e,t)}until(e){return this.isValid?v.fromDateTimes(this,e):this}hasSame(e,t,r){if(!this.isValid)return!1;let n=e.valueOf(),i=this.setZone(e.zone,{keepLocalTime:!0});return i.startOf(t,r)<=n&&n<=i.endOf(t,r)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;let t=e.base||f.fromObject({},{zone:this.zone}),r=e.padding?thist.valueOf(),Math.min)}static max(...e){if(!e.every(f.isDateTime))throw new D("max requires all arguments be DateTimes");return Ss(e,t=>t.valueOf(),Math.max)}static fromFormatExplain(e,t,r={}){let{locale:n=null,numberingSystem:i=null}=r,a=T.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});return Ms(a,e,t)}static fromStringExplain(e,t,r={}){return f.fromFormatExplain(e,t,r)}static buildFormatParser(e,t={}){let{locale:r=null,numberingSystem:n=null}=t,i=T.fromOpts({locale:r,numberingSystem:n,defaultToEN:!0});return new Et(i,e)}static fromFormatParser(e,t,r={}){if(m(e)||m(t))throw new D("fromFormatParser requires an input string and a format parser");let{locale:n=null,numberingSystem:i=null}=r,a=T.fromOpts({locale:n,numberingSystem:i,defaultToEN:!0});if(!a.equals(t.locale))throw new D(`fromFormatParser called with a locale of ${a}, but the format parser was created for ${t.locale}`);let{result:o,zone:l,specificOffset:u,invalidReason:c}=t.explainFromTokens(e);return c?f.invalid(c):He(o,l,r,`format ${t.format}`,e,u)}static get DATE_SHORT(){return ce}static get DATE_MED(){return ze}static get DATE_MED_WITH_WEEKDAY(){return Xt}static get DATE_FULL(){return Be}static get DATE_HUGE(){return Ye}static get TIME_SIMPLE(){return Ge}static get TIME_WITH_SECONDS(){return Je}static get TIME_WITH_SHORT_OFFSET(){return je}static get TIME_WITH_LONG_OFFSET(){return Ke}static get TIME_24_SIMPLE(){return Qe}static get TIME_24_WITH_SECONDS(){return Xe}static get TIME_24_WITH_SHORT_OFFSET(){return et}static get TIME_24_WITH_LONG_OFFSET(){return tt}static get DATETIME_SHORT(){return st}static get DATETIME_SHORT_WITH_SECONDS(){return rt}static get DATETIME_MED(){return nt}static get DATETIME_MED_WITH_SECONDS(){return it}static get DATETIME_MED_WITH_WEEKDAY(){return es}static get DATETIME_FULL(){return at}static get DATETIME_FULL_WITH_SECONDS(){return ot}static get DATETIME_HUGE(){return lt}static get DATETIME_HUGE_WITH_SECONDS(){return ut}};function Re(s){if(f.isDateTime(s))return s;if(s&&s.valueOf&&Q(s.valueOf()))return f.fromJSDate(s);if(s&&typeof s=="object")return f.fromObject(s);throw new D(`Unknown datetime argument: ${s}, of type ${typeof s}`)}var en=require("obsidian"),Yi=/[<>:"/\\|?*\u0000-\u001F]/g;var Gi="-",Ji=s=>s.replace(Yi,Gi);var tn=s=>{let e=Ji(s).trim();return(0,en.normalizePath)(e)},te=(s,e="yyyy-MM-dd HH:mm:ss")=>{if(!s)return"";try{let t=f.fromISO(s);return t.isValid?t.toFormat(e):s}catch(t){return console.error("Error formatting date:",t),s}};var ji=Object.prototype.toString,$e=Array.isArray||function(e){return ji.call(e)==="[object Array]"};function Rs(s){return typeof s=="function"}function Ki(s){return $e(s)?"array":typeof s}function Ws(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function sn(s,e){return s!=null&&typeof s=="object"&&e in s}function Qi(s,e){return s!=null&&typeof s!="object"&&s.hasOwnProperty&&s.hasOwnProperty(e)}var Xi=RegExp.prototype.test;function ea(s,e){return Xi.call(s,e)}var ta=/\S/;function sa(s){return!ea(ta,s)}var ra={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/","`":"`","=":"="};function na(s){return String(s).replace(/[&<>"'`=\/]/g,function(t){return ra[t]})}var ia=/\s*/,aa=/\s+/,rn=/\s*=/,oa=/\s*\}/,la=/#|\^|\/|>|\{|&|=|!/;function ua(s,e){if(!s)return[];var t=!1,r=[],n=[],i=[],a=!1,o=!1,l="",u=0;function c(){if(a&&!o)for(;i.length;)delete n[i.pop()];else i=[];a=!1,o=!1}var h,y,g;function k(V){if(typeof V=="string"&&(V=V.split(aa,2)),!$e(V)||V.length!==2)throw new Error("Invalid tags: "+V);h=new RegExp(Ws(V[0])+"\\s*"),y=new RegExp("\\s*"+Ws(V[1])),g=new RegExp("\\s*"+Ws("}"+V[1]))}k(e||B.tags);for(var S=new xt(s),F,b,M,Y,se,Z;!S.eos();){if(F=S.pos,M=S.scanUntil(h),M)for(var re=0,ne=M.length;re"?se=[b,M,F,S.pos,l,u,t]:se=[b,M,F,S.pos],u++,n.push(se),b==="#"||b==="^")r.push(se);else if(b==="/"){if(Z=r.pop(),!Z)throw new Error('Unopened section "'+M+'" at '+F);if(Z[1]!==M)throw new Error('Unclosed section "'+Z[1]+'" at '+F)}else b==="name"||b==="{"||b==="&"?o=!0:b==="="&&k(M)}if(c(),Z=r.pop(),Z)throw new Error('Unclosed section "'+Z[1]+'" at '+S.pos);return da(ca(n))}function ca(s){for(var e=[],t,r,n=0,i=s.length;n0?r[r.length-1][4]:e;break;default:t.push(n)}return e}function xt(s){this.string=s,this.tail=s,this.pos=0}xt.prototype.eos=function(){return this.tail===""};xt.prototype.scan=function(e){var t=this.tail.match(e);if(!t||t.index!==0)return"";var r=t[0];return this.tail=this.tail.substring(r.length),this.pos+=r.length,r};xt.prototype.scanUntil=function(e){var t=this.tail.search(e),r;switch(t){case-1:r=this.tail,this.tail="";break;case 0:r="";break;default:r=this.tail.substring(0,t),this.tail=this.tail.substring(t)}return this.pos+=r.length,r};function Ue(s,e){this.view=s,this.cache={".":this.view},this.parent=e}Ue.prototype.push=function(e){return new Ue(e,this)};Ue.prototype.lookup=function(e){var t=this.cache,r;if(t.hasOwnProperty(e))r=t[e];else{for(var n=this,i,a,o,l=!1;n;){if(e.indexOf(".")>0)for(i=n.view,a=e.split("."),o=0;i!=null&&o"?u=this.renderPartial(o,t,r,i):l==="&"?u=this.unescapedValue(o,t):l==="name"?u=this.escapedValue(o,t,i):l==="text"&&(u=this.rawValue(o)),u!==void 0&&(a+=u);return a};L.prototype.renderSection=function(e,t,r,n,i){var a=this,o="",l=t.lookup(e[1]);function u(y){return a.render(y,t,r,i)}if(l){if($e(l))for(var c=0,h=l.length;c0||!r)&&(i[a]=n+i[a]);return i.join(` +`)};L.prototype.renderPartial=function(e,t,r,n){if(r){var i=this.getConfigTags(n),a=Rs(r)?r(e[1]):r[e[1]];if(a!=null){var o=e[6],l=e[5],u=e[4],c=a;l==0&&u&&(c=this.indentPartial(a,u,o));var h=this.parse(c,i);return this.renderTokens(h,t,r,c,n)}}};L.prototype.unescapedValue=function(e,t){var r=t.lookup(e[1]);if(r!=null)return r};L.prototype.escapedValue=function(e,t,r){var n=this.getConfigEscape(r)||B.escape,i=t.lookup(e[1]);if(i!=null)return typeof i=="number"&&n===B.escape?String(i):n(i)};L.prototype.rawValue=function(e){return e[1]};L.prototype.getConfigTags=function(e){return $e(e)?e:e&&typeof e=="object"?e.tags:void 0};L.prototype.getConfigEscape=function(e){if(e&&typeof e=="object"&&!$e(e))return e.escape};var B={name:"mustache.js",version:"4.2.0",tags:["{{","}}"],clearCache:void 0,escape:void 0,parse:void 0,render:void 0,Scanner:void 0,Context:void 0,Writer:void 0,set templateCache(s){St.templateCache=s},get templateCache(){return St.templateCache}},St=new L;B.clearCache=function(){return St.clearCache()};B.parse=function(e,t){return St.parse(e,t)};B.render=function(e,t,r,n){if(typeof e!="string")throw new TypeError('Invalid template! Template should be a "string" but "'+Ki(e)+'" was given as the first argument for mustache#render(template, view, partials)');return St.render(e,t,r,n)};B.escape=na;B.Scanner=xt;B.Context=Ue;B.Writer=L;var Hs=B;var Us=require("obsidian"),nn=["title","article_title","tags","create_time","update_time","domain","url","cubox_url","description","description","words_count","type","words_count","id"],Bt=class{constructor(){this.dateFormat="yyyy-MM-dd"}setDateFormat(e){this.dateFormat=e}processFilenameTemplate(e,t){if(!e)return t.title||"Untitled";let r={title:t.title||"",article_title:t.article_title||"",create_time:t.create_time?te(t.create_time,this.dateFormat):"",update_time:t.update_time?te(t.update_time,this.dateFormat):"",domain:t.domain||"",type:t.type||"",id:t.id||""},n="";try{n=Hs.render(e,r)}catch(a){console.error("\u6A21\u677F\u6E32\u67D3\u5931\u8D25:",a),n=t.title||"Untitled"}let i=100;return n.length>i&&(n=n.substring(0,i)),tn(n)}processFrontMatter(e,t){let r={id:t.id};if(e.length===0)return(0,Us.stringifyYaml)(r);for(let n of e){let i=n.split("::"),a=i[0],o=i.length>1?i[1]:a;if(a==="tags"&&t.tags&&t.tags.length>0){r[o]=t.tags;continue}if(a==="create_time"&&t.create_time){r[o]=te(t.create_time,this.dateFormat);continue}if(a==="update_time"&&t.update_time){r[o]=te(t.update_time,this.dateFormat);continue}let l=this.getArticleProperty(t,a);l&&(r[o]=l)}return(0,Us.stringifyYaml)(r)}processContentTemplate(e,t){if(!e){let n="";return t.content&&(n+=t.content+` + +`),t.highlights&&t.highlights.length>0&&(n+=`## Highlights + +`,t.highlights.forEach(i=>{n+=`- ${i.text} +`})),n}let r=this.createArticleView(t);return e.includes("content_highlighted")&&t.content&&t.highlights&&t.highlights.length>0&&(r.content_highlighted=this.generateHighlightedContent(t.content,t.highlights)),Hs.render(e,r)}createArticleView(e){var r;let t={...e,highlights:[],tags:e.tags||[],highlights_length:((r=e.highlights)==null?void 0:r.length)||0,create_time:e.create_time?te(e.create_time,this.dateFormat):"",update_time:e.update_time?te(e.update_time,this.dateFormat):""};return e.highlights&&e.highlights.length>0&&(t.highlights=e.highlights.map(n=>this.createHighlightView(n))),t.highlights.length===0?t.highlights_length=0:t.highlights_length=t.highlights.length,t}createHighlightView(e){let t=e.text||"";!t&&e.image_url?t=`![](${e.image_url})`:t.includes(` +`)&&(t=t.split(` +`).map((o,l)=>l===0?o:o.trim()?"> "+o:">").join(` +`));let r=e.note&&e.note.trim()?e.note.trim()+` +`:"",n={...e,text:t,note:r,create_time:e.create_time?te(e.create_time,this.dateFormat):""};return n.cubox_url||(n.cubox_url=""),n}generateHighlightedContent(e,t){if(!e||!t||t.length===0)return e||"";let r=e.length,n=new Array(r).fill(!1);for(let o of t){let l=o.text;if(!l)continue;let u=0,c;for(;(c=e.indexOf(l,u))!==-1;){for(let h=0;h{if(s==="cubox.pro")switch(e){case"filename":return"https://help.cubox.pro/share/obplugin/#%E6%96%87%E4%BB%B6%E5%90%8D%E6%A8%A1%E6%9D%BF";case"metadata":return"https://help.cubox.pro/share/obplugin/#%E5%85%83%E5%B1%9E%E6%80%A7";case"content":return"https://help.cubox.pro/share/obplugin/#%E5%86%85%E5%AE%B9%E6%A8%A1%E6%9D%BF";case"date":return"https://help.cubox.pro/share/obplugin/#%E6%97%A5%E6%9C%9F%E6%A0%BC%E5%BC%8F";default:return"#"}else if(s==="cubox.cc")switch(e){case"filename":return"https://help.cubox.cc/share/obplugin/#filename-template";case"metadata":return"https://help.cubox.cc/share/obplugin/#metadata";case"content":return"https://help.cubox.cc/share/obplugin/#content-template";case"date":return"https://help.cubox.cc/share/obplugin/#date-format";default:return"#"}return"#"},Yt=(s,e)=>s?`
For more, refer to reference.
`:'
For more, refer to reference.
',an=s=>Yt(s,"filename"),on=s=>Yt(s,"metadata"),ln=s=>Yt(s,"content"),un=s=>Yt(s,"date"),cn=` +Enter template for creating synced article file name. + +
+
Available variables
+
    +
  • {{{title}}}
  • +
  • {{{article_title}}}
  • +
  • {{{create_time}}}
  • +
  • {{{update_time}}}
  • +
  • {{{domain}}}
  • +
  • {{{type}}}
  • +
+
+
+`,dn=` +Enter the metadata separated by comma. you can also use custom aliases in the format of metadata::alias. For syncing purposes, the id will always be included. + +
+
Available variables
+
    +
  • title
  • +
  • article_title
  • +
  • tags
  • +
  • create_time
  • +
  • update_time
  • +
  • domain
  • +
  • url
  • +
  • cubox_url
  • +
  • description
  • +
  • words_count
  • +
  • type
  • +
+ +
+`,hn=` +Enter template for creating synced article content. + +
+
Available variables
+
    +
  • {{{id}}}
  • +
  • {{{title}}}
  • +
  • {{{description}}}
  • +
  • {{{article_title}}}
  • +
  • {{{content}}}
  • +
  • {{{content_highlighted}}}
  • +
  • {{{highlights}}}
  • +
  • +
      +
    • {{{text}}}
    • +
    • {{{image_url}}}
    • +
    • {{{cubox_url}}}
    • +
    • {{{note}}}
    • +
    • {{{color}}}
    • +
    • {{{create_time}}}
    • +
    +
  • +
  • {{{tags}}}
  • +
  • {{{create_time}}}
  • +
  • {{{update_time}}}
  • +
  • {{{domain}}}
  • +
  • {{{url}}}
  • +
  • {{{cubox_url}}}
  • +
  • {{{words_count}}}
  • +
+
+
+`,fn=` +If date is used on above templates, enter the format date. + +
+
Example
+
    +
  • yyyy-MM-dd
  • +
  • MM/dd/yyyy
  • +
  • dd.MM.yyyy
  • +
  • yyyy-MM-dd HH:mm:ss
  • +
+
+
+`;var Ze=require("obsidian"),Zs=["Article","Snippet","Memo","Image","Audio","Video","File"],Gt=class extends Ze.Modal{constructor(t,r=[],n){super(t);this.selectedTypes=new Set;this.onSave=n,r&&r.length>0&&r.forEach(i=>{i&&this.selectedTypes.add(i)})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h2",{text:"Manage Cubox content types to be synced"}),t.addClass("cubox-modal"),this.listEl=t.createDiv({cls:"type-list-container cubox-list-container"}),this.footerEl=t.createDiv({cls:"modal-footer"}),this.createTypeList(),this.footerEl.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close()}),this.footerEl.createEl("button",{text:"Done",cls:"mod-cta"}).addEventListener("click",()=>{if(this.selectedTypes.size===0){new Ze.Notice("Please select at least one option.");return}let i=Array.from(this.selectedTypes);this.onSave(i),this.close()})}createTypeList(){this.listEl.empty(),Zs.forEach(t=>{let r=new Ze.Setting(this.listEl).setName(t);this.selectedTypes.has(t)&&r.settingEl.addClass("is-selected"),r.settingEl.addEventListener("click",()=>{let n=this.selectedTypes.has(t);this.handleTypeToggle(t,!n),this.redraw()})})}handleTypeToggle(t,r){r?this.selectedTypes.add(t):this.selectedTypes.delete(t)}redraw(){this.createTypeList()}onClose(){let{contentEl:t}=this;t.empty()}};var mn=require("obsidian"),ha=`# {{{title}}} + +{{{description}}} + +[Read in Cubox]({{{cubox_url}}}) +[Read Original]({{{url}}}) + +--- + +{{#highlights.length}} +## Annotations + +{{#highlights}} +> {{{text}}} + +{{#note}} +{{{note}}} +{{/note}} +[Link\uFE0F]({{{cubox_url}}}) + +{{/highlights}} +{{/highlights.length}}`,pe={domain:"",apiKey:"",folderFilter:[],typeFilter:[],statusFilter:[],isRead:!0,isStarred:!0,isAnnotated:!0,tagsFilter:[],syncFrequency:30,targetFolder:"Cubox",filenameTemplate:"{{{title}}}-{{{create_time}}}",frontMatterVariables:["id","cubox_url","url","tags"],contentTemplate:ha,highlightInContent:!0,dateFormat:"yyyy-MM-dd",lastSyncTime:0,lastSyncCardId:null,lastCardUpdateTime:null,syncing:!1},Jt=class extends x.PluginSettingTab{constructor(t,r){super(t,r);this.plugin=r}display(){let{containerEl:t}=this;t.empty(),new x.Setting(t).setName("Cubox server domain").setDesc("Select the correct domain name of the Cubox you are using.").addDropdown(o=>o.addOption("","Choose region").addOption("cubox.cc","cubox.cc (international)").addOption("cubox.pro","cubox.pro").setValue(this.plugin.settings.domain).onChange(async l=>{this.plugin.settings.domain=l,await this.plugin.saveSettings(),this.updateApiKeySetting(),this.plugin.updateCuboxApiConfig(l,this.plugin.settings.apiKey),this.updateHelpLinks(l)})),this.apiKeySetting=new x.Setting(t).setName("Your Cubox API key").setDesc("Please select a region first").addText(o=>(o.setPlaceholder("Enter your API key").setValue(this.plugin.settings.apiKey).onChange(async l=>{let u=l.trim();if(u.includes("://"))try{let c=u.includes("://")?new URL(u):null;if(c){let h=c.pathname.split("/").filter(y=>y.length>0);h.length>0&&(u=h[h.length-1])}o.setValue(u)}catch(c){new x.Notice("Invalid API key")}this.plugin.settings.apiKey=u,await this.plugin.saveSettings(),this.plugin.updateCuboxApiConfig(this.plugin.settings.domain,u)}),this.plugin.settings.domain||(o.inputEl.disabled=!0),o)),this.updateApiKeySetting(),new x.Setting(t).setName("Filter").setHeading(),new x.Setting(t).setName("Folder filter").setDesc("Manage Cubox folders to be synced").addButton(o=>o.setButtonText(this.getFolderFilterButtonText()).setCta().onClick(async()=>{if(!this.plugin.settings.apiKey){new x.Notice("Please enter the API key first");return}o.setButtonText("Loading folders...");try{let l=await this.plugin.cuboxApi.getFolders();new vt(this.app,l,this.plugin.settings.folderFilter,async c=>{this.plugin.settings.folderFilter=c,await this.plugin.saveSettings(),o.setButtonText(this.getFolderFilterButtonText())}).open()}catch(l){console.error("\u83B7\u53D6\u6587\u4EF6\u5939\u5217\u8868\u5931\u8D25:",l),new x.Notice("Failed to get Cubox folders"),o.setButtonText(this.getFolderFilterButtonText())}o.setButtonText(this.getFolderFilterButtonText())})),new x.Setting(t).setName("Tag filter").setDesc("Manage Cubox tags to be synced").addButton(o=>o.setButtonText(this.getTagFilterButtonText()).setCta().onClick(async()=>{if(!this.plugin.settings.apiKey){new x.Notice("Please enter the API key first");return}o.setButtonText("Loading tags...");try{let l=await this.plugin.cuboxApi.getTags();new Ft(this.app,l,this.plugin.settings.tagsFilter,async c=>{this.plugin.settings.tagsFilter=c,await this.plugin.saveSettings(),o.setButtonText(this.getTagFilterButtonText())}).open()}catch(l){console.error("\u83B7\u53D6\u6807\u7B7E\u5217\u8868\u5931\u8D25:",l),new x.Notice("Failed to get Cubox tags"),o.setButtonText(this.getTagFilterButtonText())}o.setButtonText(this.getTagFilterButtonText())})),new x.Setting(t).setName("Type filter").setDesc("Manage Cubox content types to be synced").addButton(o=>o.setButtonText(this.getTypeFilterButtonText()).setCta().onClick(async()=>{if(!this.plugin.settings.apiKey){new x.Notice("Please enter the API key first");return}new Gt(this.app,this.plugin.settings.typeFilter,async u=>{this.plugin.settings.typeFilter=u,await this.plugin.saveSettings(),o.setButtonText(this.getTypeFilterButtonText())}).open()})),new x.Setting(t).setName("Status filter").setDesc("Manage Cubox content status to be synced").addButton(o=>o.setButtonText(this.getStatusFilterButtonText()).setCta().onClick(async()=>{if(!this.plugin.settings.apiKey){new x.Notice("Please enter the API key first");return}let l={read:this.plugin.settings.isRead,starred:this.plugin.settings.isStarred,annotated:this.plugin.settings.isAnnotated};new kt(this.app,this.plugin.settings.statusFilter,l,async(c,h)=>{this.plugin.settings.statusFilter=c,this.plugin.settings.isRead=h.read,this.plugin.settings.isStarred=h.starred,this.plugin.settings.isAnnotated=h.annotated,await this.plugin.saveSettings(),o.setButtonText(this.getStatusFilterButtonText())}).open()})),new x.Setting(t).setName("Sync").setHeading(),new x.Setting(t).setName("Sync interval").setDesc("Auto sync interval (in minutes). 0 means manual sync. Each item syncs only once. Subsequent updates won't be synced, and modifications in Obsidian won't affect Cubox. We recommend avoiding frequent updates.").addText(o=>o.setPlaceholder("Enter the interval").setValue(String(this.plugin.settings.syncFrequency)).onChange(async u=>{let c=parseInt(u);if(isNaN(c)){new x.Notice("Frequency must be a positive integer");return}c=Math.min(c,9999),this.plugin.settings.syncFrequency=c,await this.plugin.saveSettings(),this.plugin.setupAutoSync(),o.setValue(String(c))})),new x.Setting(t).setName("Folder").setDesc("Select the folder you'd like to sync to").addText(o=>o.setPlaceholder("Enter target folder path").setValue(this.plugin.settings.targetFolder).onChange(async l=>{this.plugin.settings.lastSyncCardId=null,this.plugin.settings.targetFolder=(0,mn.normalizePath)(l),await this.plugin.saveSettings()}));let r=document.createRange().createContextualFragment(cn);new x.Setting(t).setName("File name template").setDesc(r).addText(o=>o.setPlaceholder("Enter file name template").setValue(this.plugin.settings.filenameTemplate).onChange(async l=>{this.plugin.settings.filenameTemplate=l,await this.plugin.saveSettings()})).addExtraButton(o=>o.setIcon("reset").setTooltip("Reset to default").onClick(async()=>{var u,c;this.plugin.settings.filenameTemplate=pe.filenameTemplate,await this.plugin.saveSettings();let l=(c=(u=o.extraSettingsEl.parentElement)==null?void 0:u.parentElement)==null?void 0:c.querySelector("input");l&&(l.value=pe.filenameTemplate)}));let n=document.createRange().createContextualFragment(dn);new x.Setting(t).setName("Metadata variables").setDesc(n).addTextArea(o=>o.setPlaceholder("Enter front matter variables").setValue(this.plugin.settings.frontMatterVariables.join(",")).onChange(async l=>{this.plugin.settings.frontMatterVariables=l.split(",").map(u=>u.trim()).filter((u,c,h)=>nn.includes(u.split("::")[0])&&h.indexOf(u)===c),await this.plugin.saveSettings()}).then(l=>{l.inputEl.rows=20,l.inputEl.cols=30})).addExtraButton(o=>{o.setIcon("reset").setTooltip("Reset to default").onClick(async()=>{var u,c;this.plugin.settings.frontMatterVariables=pe.frontMatterVariables,await this.plugin.saveSettings();let l=(c=(u=o.extraSettingsEl.parentElement)==null?void 0:u.parentElement)==null?void 0:c.querySelector("textarea");l&&(l.value=pe.frontMatterVariables.join(","))})});let i=document.createRange().createContextualFragment(hn);new x.Setting(t).setName("Content template").setDesc(i).addTextArea(o=>o.setPlaceholder("Enter content template").setValue(this.plugin.settings.contentTemplate).onChange(async l=>{this.plugin.settings.contentTemplate=l,await this.plugin.saveSettings()}).then(l=>{l.inputEl.rows=24,l.inputEl.cols=30})).addExtraButton(o=>{o.setIcon("reset").setTooltip("Reset to default").onClick(async()=>{var u,c;this.plugin.settings.contentTemplate=pe.contentTemplate,await this.plugin.saveSettings();let l=(c=(u=o.extraSettingsEl.parentElement)==null?void 0:u.parentElement)==null?void 0:c.querySelector("textarea");l&&(l.value=pe.contentTemplate)})});let a=document.createRange().createContextualFragment(fn);new x.Setting(t).setName("Date format").setDesc(a).addText(o=>o.setPlaceholder("Enter date format").setValue(this.plugin.settings.dateFormat).onChange(async l=>{this.plugin.settings.dateFormat=l,await this.plugin.saveSettings(),this.plugin.updateTemplateProcessorDateFormat(l)})),new x.Setting(t).setName("Status").setHeading(),new x.Setting(t).setDesc(`Last sync: ${this.plugin.formatLastSyncTime()}`),setTimeout(()=>{this.updateHelpLinks(this.plugin.settings.domain)},100)}updateApiKeySetting(){let t=this.plugin.settings.domain,r=this.apiKeySetting.components[0];if(!t)this.apiKeySetting.setDesc("Please select a region first"),r.inputEl.disabled=!0;else{let n=`https://${t}/my/settings/extensions`,i=this.apiKeySetting.descEl;i.empty(),i.appendChild(createSpan({text:"You can create a key in the "})),i.appendChild(createEl("a",{text:"Extension settings",href:n,attr:{target:"_blank",rel:"noopener"}})),i.appendChild(createSpan({text:" of Cubox web app."})),r.inputEl.disabled=!1}}updateHelpLinks(t){let r=(n,i)=>{let a=document.querySelector(n);if(a){a.empty();let o=a.createSpan({text:"For more, refer to "}),l=t?$s(t,n.includes("filename")?"filename":n.includes("metadata")?"metadata":n.includes("content")?"content":"date"):"#",u=o.createEl("a",{text:"reference",cls:"reference-link",href:l});t&&u.setAttribute("target","_blank"),o.createSpan({text:"."})}};r(".domain-reference-filename",an),r(".domain-reference-metadata",on),r(".domain-reference-content",ln),r(".domain-reference-date",un)}getFolderFilterButtonText(){let t=this.plugin.settings.folderFilter;return!t||t.length===0?"Select...":t.includes(W)?"All folders":`${t.length} selected`}getTypeFilterButtonText(){let t=this.plugin.settings.typeFilter;return!t||t.length===0?"Select...":t.length===Zs.length?"All types":`${t.length} selected`}getStatusFilterButtonText(){let t=this.plugin.settings.statusFilter;return!t||t.length===0?"Select...":t.includes("all")?"All items":`${t.length} selected`}getTagFilterButtonText(){let t=this.plugin.settings.tagsFilter;return!t||t.length===0?"Select...":t.includes(A)?"All items":t.includes("")?"No tags":`${t.length} selected`}};var jt=class extends H.Plugin{async onload(){await this.loadSettings(),this.cuboxApi=new bt(this.settings.domain,this.settings.apiKey),this.templateProcessor=new Bt,this.templateProcessor.setDateFormat(this.settings.dateFormat);let t="Cubox";(0,H.addIcon)(t,' '),this.addRibbonIcon(t,t,async n=>{new H.Notice("Syncing your Cubox\u2026"),await this.syncCubox()}).addClass("cubox-sync-ribbon-class"),this.addCommand({id:"sync-cubox-data",name:"Sync now",callback:async()=>{await this.syncCubox()}}),this.addSettingTab(new Jt(this.app,this)),this.setupAutoSync()}onunload(){this.syncIntervalId&&window.clearInterval(this.syncIntervalId)}async loadSettings(){this.settings=Object.assign({},pe,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}async setupAutoSync(){this.syncIntervalId&&window.clearInterval(this.syncIntervalId),this.settings.syncFrequency>0&&(this.syncIntervalId=window.setInterval(async()=>await this.syncCubox(),this.settings.syncFrequency*60*1e3),this.registerInterval(this.syncIntervalId))}async syncCubox(){var t,r;if(this.settings.syncing){new H.Notice("Sync is in progress, please wait.");return}if(this.settings.folderFilter.length===0||this.settings.typeFilter.length===0||this.settings.statusFilter.length===0||this.settings.tagsFilter.length===0){new H.Notice("Please select the filter first");return}try{this.settings.syncing=!0,await this.saveSettings(),await this.ensureTargetFolder();let n=this.settings.lastSyncCardId,i=this.settings.lastCardUpdateTime,a=!0,o=0,l=0,u=0;for(;a;){let h=await this.cuboxApi.getArticles({lastCardId:n,lastCardUpdateTime:i,folderFilter:this.settings.folderFilter,typeFilter:this.settings.typeFilter,statusFilter:this.settings.statusFilter,tagsFilter:this.settings.tagsFilter,isRead:this.settings.isRead,isStarred:this.settings.isStarred,isAnnotated:this.settings.isAnnotated}),{articles:y,hasMore:g}=h,k=this.templateProcessor.needsArticleContent(this.settings.contentTemplate);if(y.length===0)break;for(let S of y)try{let F={...S};if(k){let ne=await this.cuboxApi.getArticleDetail(S.id);if(ne===null)continue;F.content=ne}let b=this.templateProcessor.processFilenameTemplate(this.settings.filenameTemplate,F),M=`${this.settings.targetFolder}/${b}.md`,Y=this.app.vault.getAbstractFileByPath(M);if(Y instanceof H.TFile){let ne=!1,V=(r=(t=this.app.metadataCache.getFileCache(Y))==null?void 0:t.frontmatter)==null?void 0:r.id;if(V&&V===S.id&&(ne=!0),ne){u++;continue}}let se=this.templateProcessor.processFrontMatter(this.settings.frontMatterVariables,F),Z=this.templateProcessor.processContentTemplate(this.settings.contentTemplate,F),re="";se.length>0&&(re=`--- +${se} +--- +`),re+=Z,await this.app.vault.create(M,re),o++}catch(F){l++,console.error("\u540C\u6B65 Cubox \u6570\u636E\u5931\u8D25:",F)}a=g,y.length>0&&(n=y[y.length-1].id,i=y[y.length-1].update_time,this.settings.lastSyncCardId=n,this.settings.lastCardUpdateTime=i,await this.saveSettings())}this.settings.lastSyncTime=Date.now(),this.settings.syncing=!1,await this.saveSettings();let c=`Cubox sync completed: ${o} new items${u>0?`, ${u} skipped`:""}${l>0?`, ${l} errors`:""}`;new H.Notice(c)}catch(n){console.error("\u540C\u6B65 Cubox \u6570\u636E\u5931\u8D25:",n),new H.Notice("Cubox sync failed. Please check settings or network.")}finally{this.settings.syncing=!1,await this.saveSettings()}}async ensureTargetFolder(){let t=this.settings.targetFolder;this.app.vault.getAbstractFileByPath(t)instanceof H.TFolder||await this.app.vault.createFolder(t)}formatLastSyncTime(){return this.settings.lastSyncTime?te(new Date(this.settings.lastSyncTime).toISOString(),"yyyy-MM-dd HH:mm"):"never"}updateCuboxApiConfig(t,r){this.cuboxApi.updateConfig(t,r)}updateTemplateProcessorDateFormat(t){this.templateProcessor.setDateFormat(t)}}; +/*! Bundled license information: + +mustache/mustache.mjs: + (*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + *) +*/ + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/cubox-sync/manifest.json b/.obsidian/plugins/cubox-sync/manifest.json new file mode 100644 index 00000000..443836c2 --- /dev/null +++ b/.obsidian/plugins/cubox-sync/manifest.json @@ -0,0 +1,9 @@ +{ + "id": "cubox-sync", + "name": "Cubox", + "version": "1.0.6", + "minAppVersion": "0.15.0", + "description": "Sync your Cubox articles & annotations", + "author": "delphi-2015", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/.obsidian/plugins/cubox-sync/styles.css b/.obsidian/plugins/cubox-sync/styles.css new file mode 100644 index 00000000..f727d1c5 --- /dev/null +++ b/.obsidian/plugins/cubox-sync/styles.css @@ -0,0 +1,213 @@ +/* + +This CSS file will be included with your plugin, and +available in the app when your plugin is enabled. + +If your plugin does not need CSS, delete this file. + +*/ + +.modal-footer { + display: flex; + justify-content: flex-end; + padding: 16px; + border-top: 1px solid var(--background-modifier-border); +} + +.modal-footer button { + margin-left: 8px; +} + +.modal-footer button.mod-cta { + background-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +/* 变量列表样式优化 */ +.cubox-variables-container { + margin: 20px 0; + color: var(--text-muted); +} + +.cubox-variables-title { + font-weight: 500; + margin-bottom: 8px; + color: var(--text-normal); +} + +.cubox-variables-list { + margin: 0; + padding-left: 15px; + list-style-type: disc; +} + +.cubox-variables-list li { + margin-bottom: 4px; + line-height: 1.2; +} + +.highlight-sublist { + margin-top: 4px; + padding-left: 15px; + list-style-type: disc; +} + +.cubox-reference { + margin-top: 10px; + font-size: 1.0em; +} + +.reference-link { + color: var(--text-accent); + text-decoration: none; +} + +.reference-link:hover { + text-decoration: underline; +} + +/* Modal Dialog Styles */ +.cubox-modal { + display: flex; + flex-direction: column; + height: 100%; +} + +.cubox-list-container { + flex-grow: 1; + overflow-y: auto; + padding-top: 20px; + padding-right: 10px; + overflow-anchor: none; + scroll-behavior: auto; + height: 100%; + max-height: 65vh; +} + +/* Setting item styles for modal dialogs */ +.cubox-list-container .setting-item { + position: relative; + padding-left: 36px; + border-radius: 4px; + transition: background-color 0.1s ease; + display: flex; + align-items: center; + min-height: 40px; + box-sizing: border-box; +} + +.cubox-list-container .setting-item:hover { + background-color: var(--background-modifier-hover); +} + +/* Setting item name styles */ +.cubox-list-container .setting-item-name { + display: flex; + align-items: center; + padding: 0; + margin: 0; +} + +/* Custom checkbox styles */ +.cubox-list-container .setting-item::before { + content: ""; + position: absolute; + width: 16px; + height: 16px; + border: 1px solid var(--checkbox-border-color, var(--background-modifier-border)); + border-radius: 3px; + background-color: var(--checkbox-color, var(--background-primary)); + box-sizing: border-box; +} + +/* First child checkbox positioning */ +.cubox-list-container .setting-item:first-child::before { + left: 10px; + top: 12px; +} + +/* Other items checkbox positioning */ +.cubox-list-container .setting-item:not(:first-child)::before { + left: 10px; + top: 50%; + transform: translateY(-50%); +} + +/* Selected checkbox state */ +.cubox-list-container .setting-item.is-selected::before { + background-color: var(--checkbox-color-checked, var(--interactive-accent)); + border-color: var(--checkbox-border-color-checked, var(--interactive-accent)); +} + +/* Checkmark for selected items */ +.cubox-list-container .setting-item.is-selected::after { + content: ""; + position: absolute; + width: 5px; + height: 9px; + border-right: 2px solid var(--text-on-accent); + border-bottom: 2px solid var(--text-on-accent); +} + +/* First child checkmark positioning */ +.cubox-list-container .setting-item:first-child.is-selected::after { + left: 14px; + top: 13px; + transform: rotate(45deg); +} + +/* Other items checkmark positioning */ +.cubox-list-container .setting-item:not(:first-child).is-selected::after { + left: 14px; + top: 50%; + transform: translateY(-60%) rotate(45deg); +} + +/* First item special styling */ +.cubox-list-container .setting-item:first-child { + margin-top: 0; + padding-top: 0; +} + +.cubox-list-container .setting-item:first-child .setting-item-name { + margin-top: 0; + padding-top: 0; + position: relative; + top: 6px; + font-weight: bold; +} + +/* Disabled state styling */ +.cubox-list-container .setting-item.is-disabled { + opacity: 0.3; + pointer-events: none; +} + +.cubox-list-container .setting-item.is-disabled::before { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); +} + +.cubox-list-container .setting-item.is-disabled::after { + content: ""; + position: absolute; + width: 8px; + height: 2px; + background-color: var(--text-muted); + left: 14px; + top: 50%; + transform: translateY(-50%); + border: none; +} + +/* Consistent line height for all items */ +.cubox-list-container .setting-item-heading, +.cubox-list-container .setting-item-name { + line-height: normal; + margin: auto 0; +} + +/* Override first row bold font for type modal */ +.type-list-container .setting-item:first-child .setting-item-name { + font-weight: normal; +} \ No newline at end of file diff --git a/.obsidian/plugins/github-sync/main.js b/.obsidian/plugins/github-sync/main.js new file mode 100644 index 00000000..852c104e --- /dev/null +++ b/.obsidian/plugins/github-sync/main.js @@ -0,0 +1,4870 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; +var __privateMethod = (obj, member, method) => { + __accessCheck(obj, member, "access private method"); + return method; +}; + +// node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/ms/index.js"(exports, module2) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module2.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === "string" && val.length > 0) { + return parse(val); + } else if (type === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || "ms").toLowerCase(); + switch (type) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/debug/src/common.js"(exports, module2) { + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env).forEach((key) => { + createDebug[key] = env[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash = 0; + for (let i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; + } + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug2(...args) { + if (!debug2.enabled) { + return; + } + const self = debug2; + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + if (typeof args[0] !== "string") { + args.unshift("%O"); + } + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + if (match === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === "function") { + const val = args[index]; + match = formatter.call(self, val); + args.splice(index, 1); + index--; + } + return match; + }); + createDebug.formatArgs.call(self, args); + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + debug2.namespace = namespace; + debug2.useColors = createDebug.useColors(); + debug2.color = createDebug.selectColor(namespace); + debug2.extend = extend; + debug2.destroy = createDebug.destroy; + Object.defineProperty(debug2, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug2); + } + return debug2; + } + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + let i; + const split = (typeof namespaces === "string" ? namespaces : "").split(/[\s,]+/); + const len = split.length; + for (i = 0; i < len; i++) { + if (!split[i]) { + continue; + } + namespaces = split[i].replace(/\*/g, ".*?"); + if (namespaces[0] === "-") { + createDebug.skips.push(new RegExp("^" + namespaces.slice(1) + "$")); + } else { + createDebug.names.push(new RegExp("^" + namespaces + "$")); + } + } + } + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + if (name[name.length - 1] === "*") { + return true; + } + let i; + let len; + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + return false; + } + function toNamespace(regexp) { + return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, "*"); + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module2.exports = setup; + } +}); + +// node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/debug/src/browser.js"(exports, module2) { + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.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 useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs(args) { + args[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args[0] + (this.useColors ? "%c " : " ") + "+" + module2.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, (match) => { + if (match === "%%") { + return; + } + index++; + if (match === "%c") { + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + exports.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error) { + } + } + function load() { + let r; + try { + r = exports.storage.getItem("debug"); + } catch (error) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error) { + } + } + module2.exports = require_common()(exports); + var { formatters } = module2.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error) { + return "[UnexpectedJSONParseError]: " + error.message; + } + }; + } +}); + +// node_modules/@kwsites/file-exists/dist/src/index.js +var require_src = __commonJS({ + "node_modules/@kwsites/file-exists/dist/src/index.js"(exports) { + "use strict"; + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { "default": mod }; + }; + Object.defineProperty(exports, "__esModule", { value: true }); + var fs_1 = require("fs"); + var debug_1 = __importDefault(require_browser()); + var log = debug_1.default("@kwsites/file-exists"); + function check(path, isFile, isDirectory) { + log(`checking %s`, path); + try { + const stat = fs_1.statSync(path); + if (stat.isFile() && isFile) { + log(`[OK] path represents a file`); + return true; + } + if (stat.isDirectory() && isDirectory) { + log(`[OK] path represents a directory`); + return true; + } + log(`[FAIL] path represents something other than a file or directory`); + return false; + } catch (e) { + if (e.code === "ENOENT") { + log(`[FAIL] path is not accessible: %o`, e); + return false; + } + log(`[FATAL] %o`, e); + throw e; + } + } + function exists2(path, type = exports.READABLE) { + return check(path, (type & exports.FILE) > 0, (type & exports.FOLDER) > 0); + } + exports.exists = exists2; + exports.FILE = 1; + exports.FOLDER = 2; + exports.READABLE = exports.FILE + exports.FOLDER; + } +}); + +// node_modules/@kwsites/file-exists/dist/index.js +var require_dist = __commonJS({ + "node_modules/@kwsites/file-exists/dist/index.js"(exports) { + "use strict"; + function __export3(m) { + for (var p in m) + if (!exports.hasOwnProperty(p)) + exports[p] = m[p]; + } + Object.defineProperty(exports, "__esModule", { value: true }); + __export3(require_src()); + } +}); + +// node_modules/@kwsites/promise-deferred/dist/index.js +var require_dist2 = __commonJS({ + "node_modules/@kwsites/promise-deferred/dist/index.js"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createDeferred = exports.deferred = void 0; + function deferred2() { + let done; + let fail; + let status = "pending"; + const promise = new Promise((_done, _fail) => { + done = _done; + fail = _fail; + }); + return { + promise, + done(result) { + if (status === "pending") { + status = "resolved"; + done(result); + } + }, + fail(error) { + if (status === "pending") { + status = "rejected"; + fail(error); + } + }, + get fulfilled() { + return status !== "pending"; + }, + get status() { + return status; + } + }; + } + exports.deferred = deferred2; + exports.createDeferred = deferred2; + exports.default = deferred2; + } +}); + +// node_modules/set-interval-async/dist/set-interval-async-timer.cjs +var require_set_interval_async_timer = __commonJS({ + "node_modules/set-interval-async/dist/set-interval-async-timer.cjs"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SetIntervalAsyncTimer = void 0; + var MIN_INTERVAL_MS = 10; + var MAX_INTERVAL_MS = 2147483647; + var _timeout, _promise, _stopped, _scheduleTimeout, scheduleTimeout_fn, _runHandlerAndScheduleTimeout, runHandlerAndScheduleTimeout_fn; + var _SetIntervalAsyncTimer = class { + constructor() { + __privateAdd(this, _scheduleTimeout); + __privateAdd(this, _runHandlerAndScheduleTimeout); + __privateAdd(this, _timeout, void 0); + __privateAdd(this, _promise, void 0); + __privateAdd(this, _stopped, false); + } + static startTimer(strategy, handler, intervalMs, ...handlerArgs) { + var _a2; + intervalMs = Math.min(Math.max(Math.trunc(intervalMs), MIN_INTERVAL_MS), MAX_INTERVAL_MS); + const timer = new _SetIntervalAsyncTimer(); + __privateMethod(_a2 = timer, _scheduleTimeout, scheduleTimeout_fn).call(_a2, strategy, handler, intervalMs, intervalMs, ...handlerArgs); + return timer; + } + static async stopTimer(timer) { + __privateSet(timer, _stopped, true); + if (__privateGet(timer, _timeout)) { + clearTimeout(__privateGet(timer, _timeout)); + } + if (__privateGet(timer, _promise)) { + await __privateGet(timer, _promise); + } + } + }; + var SetIntervalAsyncTimer = _SetIntervalAsyncTimer; + _timeout = new WeakMap(); + _promise = new WeakMap(); + _stopped = new WeakMap(); + _scheduleTimeout = new WeakSet(); + scheduleTimeout_fn = function(strategy, handler, intervalMs, delayMs, ...handlerArgs) { + __privateSet(this, _timeout, setTimeout(async () => { + __privateSet(this, _timeout, void 0); + __privateSet(this, _promise, __privateMethod(this, _runHandlerAndScheduleTimeout, runHandlerAndScheduleTimeout_fn).call(this, strategy, handler, intervalMs, ...handlerArgs)); + await __privateGet(this, _promise); + __privateSet(this, _promise, void 0); + }, delayMs)); + }; + _runHandlerAndScheduleTimeout = new WeakSet(); + runHandlerAndScheduleTimeout_fn = async function(strategy, handler, intervalMs, ...handlerArgs) { + const startTimeMs = new Date().getTime(); + try { + await handler(...handlerArgs); + } finally { + if (!__privateGet(this, _stopped)) { + const executionTimeMs = new Date().getTime() - startTimeMs; + const delayMs = strategy === "dynamic" ? intervalMs > executionTimeMs ? intervalMs - executionTimeMs : 0 : intervalMs; + __privateMethod(this, _scheduleTimeout, scheduleTimeout_fn).call(this, strategy, handler, intervalMs, delayMs, ...handlerArgs); + } + } + }; + exports.SetIntervalAsyncTimer = SetIntervalAsyncTimer; + } +}); + +// node_modules/set-interval-async/dist/clear-interval-async.cjs +var require_clear_interval_async = __commonJS({ + "node_modules/set-interval-async/dist/clear-interval-async.cjs"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.clearIntervalAsync = void 0; + var set_interval_async_timer_cjs_1 = require_set_interval_async_timer(); + async function clearIntervalAsync3(timer) { + if (!(timer instanceof set_interval_async_timer_cjs_1.SetIntervalAsyncTimer)) { + throw new TypeError("First argument is not an instance of SetIntervalAsyncTimer"); + } + await set_interval_async_timer_cjs_1.SetIntervalAsyncTimer.stopTimer(timer); + } + exports.clearIntervalAsync = clearIntervalAsync3; + } +}); + +// node_modules/set-interval-async/dist/dynamic/set-interval-async.cjs +var require_set_interval_async = __commonJS({ + "node_modules/set-interval-async/dist/dynamic/set-interval-async.cjs"(exports) { + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.setIntervalAsync = exports.clearIntervalAsync = void 0; + var clear_interval_async_cjs_1 = require_clear_interval_async(); + Object.defineProperty(exports, "clearIntervalAsync", { enumerable: true, get: function() { + return clear_interval_async_cjs_1.clearIntervalAsync; + } }); + var set_interval_async_timer_cjs_1 = require_set_interval_async_timer(); + function setIntervalAsync2(handler, intervalMs, ...handlerArgs) { + if (!(typeof handler === "function")) { + throw new TypeError("First argument is not a function"); + } + if (!(typeof intervalMs === "number")) { + throw new TypeError("Second argument is not a number"); + } + return set_interval_async_timer_cjs_1.SetIntervalAsyncTimer.startTimer("dynamic", handler, intervalMs, ...handlerArgs); + } + exports.setIntervalAsync = setIntervalAsync2; + } +}); + +// main.ts +var main_exports = {}; +__export(main_exports, { + default: () => GHSyncPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian = require("obsidian"); + +// node_modules/simple-git/dist/esm/index.js +var import_file_exists = __toESM(require_dist(), 1); +var import_debug = __toESM(require_browser(), 1); +var import_child_process = require("child_process"); +var import_promise_deferred = __toESM(require_dist2(), 1); +var import_promise_deferred2 = __toESM(require_dist2(), 1); +var __defProp2 = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames2 = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __hasOwnProp2 = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp2.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __markAsModule = (target) => __defProp2(target, "__esModule", { value: true }); +var __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames2(fn)[0]])(fn = 0)), res; +}; +var __commonJS2 = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export2 = (target, all) => { + for (var name in all) + __defProp2(target, name, { get: all[name], enumerable: true }); +}; +var __reExport = (target, module2, copyDefault, desc) => { + if (module2 && typeof module2 === "object" || typeof module2 === "function") { + for (let key of __getOwnPropNames2(module2)) + if (!__hasOwnProp2.call(target, key) && (copyDefault || key !== "default")) + __defProp2(target, key, { get: () => module2[key], enumerable: !(desc = __getOwnPropDesc2(module2, key)) || desc.enumerable }); + } + return target; +}; +var __toCommonJS2 = /* @__PURE__ */ ((cache2) => { + return (module2, temp) => { + return cache2 && cache2.get(module2) || (temp = __reExport(__markAsModule({}), module2, 1), cache2 && cache2.set(module2, temp), temp); + }; +})(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; +function pathspec(...paths) { + const key = new String(paths); + cache.set(key, paths); + return key; +} +function isPathSpec(path) { + return path instanceof String && cache.has(path); +} +function toPaths(pathSpec) { + return cache.get(pathSpec) || []; +} +var cache; +var init_pathspec = __esm({ + "src/lib/args/pathspec.ts"() { + cache = /* @__PURE__ */ new WeakMap(); + } +}); +var GitError; +var init_git_error = __esm({ + "src/lib/errors/git-error.ts"() { + GitError = class extends Error { + constructor(task, message) { + super(message); + this.task = task; + Object.setPrototypeOf(this, new.target.prototype); + } + }; + } +}); +var GitResponseError; +var init_git_response_error = __esm({ + "src/lib/errors/git-response-error.ts"() { + init_git_error(); + GitResponseError = class extends GitError { + constructor(git2, message) { + super(void 0, message || String(git2)); + this.git = git2; + } + }; + } +}); +var TaskConfigurationError; +var init_task_configuration_error = __esm({ + "src/lib/errors/task-configuration-error.ts"() { + init_git_error(); + TaskConfigurationError = class extends GitError { + constructor(message) { + super(void 0, message); + } + }; + } +}); +function asFunction(source) { + return typeof source === "function" ? source : NOOP; +} +function isUserFunction(source) { + return typeof source === "function" && source !== NOOP; +} +function splitOn(input, char) { + const index = input.indexOf(char); + if (index <= 0) { + return [input, ""]; + } + return [input.substr(0, index), input.substr(index + 1)]; +} +function first(input, offset = 0) { + return isArrayLike(input) && input.length > offset ? input[offset] : void 0; +} +function last(input, offset = 0) { + if (isArrayLike(input) && input.length > offset) { + return input[input.length - 1 - offset]; + } +} +function isArrayLike(input) { + return !!(input && typeof input.length === "number"); +} +function toLinesWithContent(input = "", trimmed2 = true, separator = "\n") { + return input.split(separator).reduce((output, line) => { + const lineContent = trimmed2 ? line.trim() : line; + if (lineContent) { + output.push(lineContent); + } + return output; + }, []); +} +function forEachLineWithContent(input, callback) { + return toLinesWithContent(input, true).map((line) => callback(line)); +} +function folderExists(path) { + return (0, import_file_exists.exists)(path, import_file_exists.FOLDER); +} +function append(target, item) { + if (Array.isArray(target)) { + if (!target.includes(item)) { + target.push(item); + } + } else { + target.add(item); + } + return item; +} +function including(target, item) { + if (Array.isArray(target) && !target.includes(item)) { + target.push(item); + } + return target; +} +function remove(target, item) { + if (Array.isArray(target)) { + const index = target.indexOf(item); + if (index >= 0) { + target.splice(index, 1); + } + } else { + target.delete(item); + } + return item; +} +function asArray(source) { + return Array.isArray(source) ? source : [source]; +} +function asStringArray(source) { + return asArray(source).map(String); +} +function asNumber(source, onNaN = 0) { + if (source == null) { + return onNaN; + } + const num = parseInt(source, 10); + return isNaN(num) ? onNaN : num; +} +function prefixedArray(input, prefix) { + const output = []; + for (let i = 0, max = input.length; i < max; i++) { + output.push(prefix, input[i]); + } + return output; +} +function bufferToString(input) { + return (Array.isArray(input) ? Buffer.concat(input) : input).toString("utf-8"); +} +function pick(source, properties) { + return Object.assign({}, ...properties.map((property) => property in source ? { [property]: source[property] } : {})); +} +function delay(duration = 0) { + return new Promise((done) => setTimeout(done, duration)); +} +function orVoid(input) { + if (input === false) { + return void 0; + } + return input; +} +var NULL; +var NOOP; +var objectToString; +var init_util = __esm({ + "src/lib/utils/util.ts"() { + NULL = "\0"; + NOOP = () => { + }; + objectToString = Object.prototype.toString.call.bind(Object.prototype.toString); + } +}); +function filterType(input, filter, def) { + if (filter(input)) { + return input; + } + return arguments.length > 2 ? def : void 0; +} +function filterPrimitives(input, omit) { + const type = isPathSpec(input) ? "string" : typeof input; + return /number|string|boolean/.test(type) && (!omit || !omit.includes(type)); +} +function filterPlainObject(input) { + return !!input && objectToString(input) === "[object Object]"; +} +function filterFunction(input) { + return typeof input === "function"; +} +var filterArray; +var filterString; +var filterStringArray; +var filterStringOrStringArray; +var filterHasLength; +var init_argument_filters = __esm({ + "src/lib/utils/argument-filters.ts"() { + init_util(); + init_pathspec(); + filterArray = (input) => { + return Array.isArray(input); + }; + filterString = (input) => { + return typeof input === "string"; + }; + filterStringArray = (input) => { + return Array.isArray(input) && input.every(filterString); + }; + filterStringOrStringArray = (input) => { + return filterString(input) || Array.isArray(input) && input.every(filterString); + }; + filterHasLength = (input) => { + if (input == null || "number|boolean|function".includes(typeof input)) { + return false; + } + return Array.isArray(input) || typeof input === "string" || typeof input.length === "number"; + }; + } +}); +var ExitCodes; +var init_exit_codes = __esm({ + "src/lib/utils/exit-codes.ts"() { + ExitCodes = /* @__PURE__ */ ((ExitCodes2) => { + ExitCodes2[ExitCodes2["SUCCESS"] = 0] = "SUCCESS"; + ExitCodes2[ExitCodes2["ERROR"] = 1] = "ERROR"; + ExitCodes2[ExitCodes2["NOT_FOUND"] = -2] = "NOT_FOUND"; + ExitCodes2[ExitCodes2["UNCLEAN"] = 128] = "UNCLEAN"; + return ExitCodes2; + })(ExitCodes || {}); + } +}); +var GitOutputStreams; +var init_git_output_streams = __esm({ + "src/lib/utils/git-output-streams.ts"() { + GitOutputStreams = class { + constructor(stdOut, stdErr) { + this.stdOut = stdOut; + this.stdErr = stdErr; + } + asStrings() { + return new GitOutputStreams(this.stdOut.toString("utf8"), this.stdErr.toString("utf8")); + } + }; + } +}); +var LineParser; +var RemoteLineParser; +var init_line_parser = __esm({ + "src/lib/utils/line-parser.ts"() { + LineParser = class { + constructor(regExp, useMatches) { + this.matches = []; + this.parse = (line, target) => { + this.resetMatches(); + if (!this._regExp.every((reg, index) => this.addMatch(reg, index, line(index)))) { + return false; + } + return this.useMatches(target, this.prepareMatches()) !== false; + }; + this._regExp = Array.isArray(regExp) ? regExp : [regExp]; + if (useMatches) { + this.useMatches = useMatches; + } + } + useMatches(target, match) { + throw new Error(`LineParser:useMatches not implemented`); + } + resetMatches() { + this.matches.length = 0; + } + prepareMatches() { + return this.matches; + } + addMatch(reg, index, line) { + const matched = line && reg.exec(line); + if (matched) { + this.pushMatch(index, matched); + } + return !!matched; + } + pushMatch(_index, matched) { + this.matches.push(...matched.slice(1)); + } + }; + RemoteLineParser = class extends LineParser { + addMatch(reg, index, line) { + return /^remote:\s/.test(String(line)) && super.addMatch(reg, index, line); + } + pushMatch(index, matched) { + if (index > 0 || matched.length > 1) { + super.pushMatch(index, matched); + } + } + }; + } +}); +function createInstanceConfig(...options) { + const baseDir = process.cwd(); + const config = Object.assign(__spreadValues({ baseDir }, defaultOptions), ...options.filter((o) => typeof o === "object" && o)); + config.baseDir = config.baseDir || baseDir; + config.trimmed = config.trimmed === true; + return config; +} +var defaultOptions; +var init_simple_git_options = __esm({ + "src/lib/utils/simple-git-options.ts"() { + defaultOptions = { + binary: "git", + maxConcurrentProcesses: 5, + config: [], + trimmed: false + }; + } +}); +function appendTaskOptions(options, commands = []) { + if (!filterPlainObject(options)) { + return commands; + } + return Object.keys(options).reduce((commands2, key) => { + const value = options[key]; + if (isPathSpec(value)) { + commands2.push(value); + } else if (filterPrimitives(value, ["boolean"])) { + commands2.push(key + "=" + value); + } else { + commands2.push(key); + } + return commands2; + }, commands); +} +function getTrailingOptions(args, initialPrimitive = 0, objectOnly = false) { + const command = []; + for (let i = 0, max = initialPrimitive < 0 ? args.length : initialPrimitive; i < max; i++) { + if ("string|number".includes(typeof args[i])) { + command.push(String(args[i])); + } + } + appendTaskOptions(trailingOptionsArgument(args), command); + if (!objectOnly) { + command.push(...trailingArrayArgument(args)); + } + return command; +} +function trailingArrayArgument(args) { + const hasTrailingCallback = typeof last(args) === "function"; + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterArray, []); +} +function trailingOptionsArgument(args) { + const hasTrailingCallback = filterFunction(last(args)); + return filterType(last(args, hasTrailingCallback ? 1 : 0), filterPlainObject); +} +function trailingFunctionArgument(args, includeNoop = true) { + const callback = asFunction(last(args)); + return includeNoop || isUserFunction(callback) ? callback : void 0; +} +var init_task_options = __esm({ + "src/lib/utils/task-options.ts"() { + init_argument_filters(); + init_util(); + init_pathspec(); + } +}); +function callTaskParser(parser3, streams) { + return parser3(streams.stdOut, streams.stdErr); +} +function parseStringResponse(result, parsers12, texts, trim = true) { + asArray(texts).forEach((text) => { + for (let lines = toLinesWithContent(text, trim), i = 0, max = lines.length; i < max; i++) { + const line = (offset = 0) => { + if (i + offset >= max) { + return; + } + return lines[i + offset]; + }; + parsers12.some(({ parse }) => parse(line, result)); + } + }); + return result; +} +var init_task_parser = __esm({ + "src/lib/utils/task-parser.ts"() { + init_util(); + } +}); +var utils_exports = {}; +__export2(utils_exports, { + ExitCodes: () => ExitCodes, + GitOutputStreams: () => GitOutputStreams, + LineParser: () => LineParser, + NOOP: () => NOOP, + NULL: () => NULL, + RemoteLineParser: () => RemoteLineParser, + append: () => append, + appendTaskOptions: () => appendTaskOptions, + asArray: () => asArray, + asFunction: () => asFunction, + asNumber: () => asNumber, + asStringArray: () => asStringArray, + bufferToString: () => bufferToString, + callTaskParser: () => callTaskParser, + createInstanceConfig: () => createInstanceConfig, + delay: () => delay, + filterArray: () => filterArray, + filterFunction: () => filterFunction, + filterHasLength: () => filterHasLength, + filterPlainObject: () => filterPlainObject, + filterPrimitives: () => filterPrimitives, + filterString: () => filterString, + filterStringArray: () => filterStringArray, + filterStringOrStringArray: () => filterStringOrStringArray, + filterType: () => filterType, + first: () => first, + folderExists: () => folderExists, + forEachLineWithContent: () => forEachLineWithContent, + getTrailingOptions: () => getTrailingOptions, + including: () => including, + isUserFunction: () => isUserFunction, + last: () => last, + objectToString: () => objectToString, + orVoid: () => orVoid, + parseStringResponse: () => parseStringResponse, + pick: () => pick, + prefixedArray: () => prefixedArray, + remove: () => remove, + splitOn: () => splitOn, + toLinesWithContent: () => toLinesWithContent, + trailingFunctionArgument: () => trailingFunctionArgument, + trailingOptionsArgument: () => trailingOptionsArgument +}); +var init_utils = __esm({ + "src/lib/utils/index.ts"() { + init_argument_filters(); + init_exit_codes(); + init_git_output_streams(); + init_line_parser(); + init_simple_git_options(); + init_task_options(); + init_task_parser(); + init_util(); + } +}); +var check_is_repo_exports = {}; +__export2(check_is_repo_exports, { + CheckRepoActions: () => CheckRepoActions, + checkIsBareRepoTask: () => checkIsBareRepoTask, + checkIsRepoRootTask: () => checkIsRepoRootTask, + checkIsRepoTask: () => checkIsRepoTask +}); +function checkIsRepoTask(action) { + switch (action) { + case "bare": + return checkIsBareRepoTask(); + case "root": + return checkIsRepoRootTask(); + } + const commands = ["rev-parse", "--is-inside-work-tree"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function checkIsRepoRootTask() { + const commands = ["rev-parse", "--git-dir"]; + return { + commands, + format: "utf-8", + onError, + parser(path) { + return /^\.(git)?$/.test(path.trim()); + } + }; +} +function checkIsBareRepoTask() { + const commands = ["rev-parse", "--is-bare-repository"]; + return { + commands, + format: "utf-8", + onError, + parser + }; +} +function isNotRepoMessage(error) { + return /(Not a git repository|Kein Git-Repository)/i.test(String(error)); +} +var CheckRepoActions; +var onError; +var parser; +var init_check_is_repo = __esm({ + "src/lib/tasks/check-is-repo.ts"() { + init_utils(); + CheckRepoActions = /* @__PURE__ */ ((CheckRepoActions2) => { + CheckRepoActions2["BARE"] = "bare"; + CheckRepoActions2["IN_TREE"] = "tree"; + CheckRepoActions2["IS_REPO_ROOT"] = "root"; + return CheckRepoActions2; + })(CheckRepoActions || {}); + onError = ({ exitCode }, error, done, fail) => { + if (exitCode === 128 && isNotRepoMessage(error)) { + return done(Buffer.from("false")); + } + fail(error); + }; + parser = (text) => { + return text.trim() === "true"; + }; + } +}); +function cleanSummaryParser(dryRun, text) { + const summary = new CleanResponse(dryRun); + const regexp = dryRun ? dryRunRemovalRegexp : removalRegexp; + toLinesWithContent(text).forEach((line) => { + const removed = line.replace(regexp, ""); + summary.paths.push(removed); + (isFolderRegexp.test(removed) ? summary.folders : summary.files).push(removed); + }); + return summary; +} +var CleanResponse; +var removalRegexp; +var dryRunRemovalRegexp; +var isFolderRegexp; +var init_CleanSummary = __esm({ + "src/lib/responses/CleanSummary.ts"() { + init_utils(); + CleanResponse = class { + constructor(dryRun) { + this.dryRun = dryRun; + this.paths = []; + this.files = []; + this.folders = []; + } + }; + removalRegexp = /^[a-z]+\s*/i; + dryRunRemovalRegexp = /^[a-z]+\s+[a-z]+\s*/i; + isFolderRegexp = /\/$/; + } +}); +var task_exports = {}; +__export2(task_exports, { + EMPTY_COMMANDS: () => EMPTY_COMMANDS, + adhocExecTask: () => adhocExecTask, + configurationErrorTask: () => configurationErrorTask, + isBufferTask: () => isBufferTask, + isEmptyTask: () => isEmptyTask, + straightThroughBufferTask: () => straightThroughBufferTask, + straightThroughStringTask: () => straightThroughStringTask +}); +function adhocExecTask(parser3) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser: parser3 + }; +} +function configurationErrorTask(error) { + return { + commands: EMPTY_COMMANDS, + format: "empty", + parser() { + throw typeof error === "string" ? new TaskConfigurationError(error) : error; + } + }; +} +function straightThroughStringTask(commands, trimmed2 = false) { + return { + commands, + format: "utf-8", + parser(text) { + return trimmed2 ? String(text).trim() : text; + } + }; +} +function straightThroughBufferTask(commands) { + return { + commands, + format: "buffer", + parser(buffer) { + return buffer; + } + }; +} +function isBufferTask(task) { + return task.format === "buffer"; +} +function isEmptyTask(task) { + return task.format === "empty" || !task.commands.length; +} +var EMPTY_COMMANDS; +var init_task = __esm({ + "src/lib/tasks/task.ts"() { + init_task_configuration_error(); + EMPTY_COMMANDS = []; + } +}); +var clean_exports = {}; +__export2(clean_exports, { + CONFIG_ERROR_INTERACTIVE_MODE: () => CONFIG_ERROR_INTERACTIVE_MODE, + CONFIG_ERROR_MODE_REQUIRED: () => CONFIG_ERROR_MODE_REQUIRED, + CONFIG_ERROR_UNKNOWN_OPTION: () => CONFIG_ERROR_UNKNOWN_OPTION, + CleanOptions: () => CleanOptions, + cleanTask: () => cleanTask, + cleanWithOptionsTask: () => cleanWithOptionsTask, + isCleanOptionsArray: () => isCleanOptionsArray +}); +function cleanWithOptionsTask(mode, customArgs) { + const { cleanMode, options, valid } = getCleanOptions(mode); + if (!cleanMode) { + return configurationErrorTask(CONFIG_ERROR_MODE_REQUIRED); + } + if (!valid.options) { + return configurationErrorTask(CONFIG_ERROR_UNKNOWN_OPTION + JSON.stringify(mode)); + } + options.push(...customArgs); + if (options.some(isInteractiveMode)) { + return configurationErrorTask(CONFIG_ERROR_INTERACTIVE_MODE); + } + return cleanTask(cleanMode, options); +} +function cleanTask(mode, customArgs) { + const commands = ["clean", `-${mode}`, ...customArgs]; + return { + commands, + format: "utf-8", + parser(text) { + return cleanSummaryParser(mode === "n", text); + } + }; +} +function isCleanOptionsArray(input) { + return Array.isArray(input) && input.every((test) => CleanOptionValues.has(test)); +} +function getCleanOptions(input) { + let cleanMode; + let options = []; + let valid = { cleanMode: false, options: true }; + input.replace(/[^a-z]i/g, "").split("").forEach((char) => { + if (isCleanMode(char)) { + cleanMode = char; + valid.cleanMode = true; + } else { + valid.options = valid.options && isKnownOption(options[options.length] = `-${char}`); + } + }); + return { + cleanMode, + options, + valid + }; +} +function isCleanMode(cleanMode) { + return cleanMode === "f" || cleanMode === "n"; +} +function isKnownOption(option) { + return /^-[a-z]$/i.test(option) && CleanOptionValues.has(option.charAt(1)); +} +function isInteractiveMode(option) { + if (/^-[^\-]/.test(option)) { + return option.indexOf("i") > 0; + } + return option === "--interactive"; +} +var CONFIG_ERROR_INTERACTIVE_MODE; +var CONFIG_ERROR_MODE_REQUIRED; +var CONFIG_ERROR_UNKNOWN_OPTION; +var CleanOptions; +var CleanOptionValues; +var init_clean = __esm({ + "src/lib/tasks/clean.ts"() { + init_CleanSummary(); + init_utils(); + init_task(); + CONFIG_ERROR_INTERACTIVE_MODE = "Git clean interactive mode is not supported"; + CONFIG_ERROR_MODE_REQUIRED = 'Git clean mode parameter ("n" or "f") is required'; + CONFIG_ERROR_UNKNOWN_OPTION = "Git clean unknown option found in: "; + CleanOptions = /* @__PURE__ */ ((CleanOptions22) => { + CleanOptions22["DRY_RUN"] = "n"; + CleanOptions22["FORCE"] = "f"; + CleanOptions22["IGNORED_INCLUDED"] = "x"; + CleanOptions22["IGNORED_ONLY"] = "X"; + CleanOptions22["EXCLUDING"] = "e"; + CleanOptions22["QUIET"] = "q"; + CleanOptions22["RECURSIVE"] = "d"; + return CleanOptions22; + })(CleanOptions || {}); + CleanOptionValues = /* @__PURE__ */ new Set([ + "i", + ...asStringArray(Object.values(CleanOptions)) + ]); + } +}); +function configListParser(text) { + const config = new ConfigList(); + for (const item of configParser(text)) { + config.addValue(item.file, String(item.key), item.value); + } + return config; +} +function configGetParser(text, key) { + let value = null; + const values = []; + const scopes = /* @__PURE__ */ new Map(); + for (const item of configParser(text, key)) { + if (item.key !== key) { + continue; + } + values.push(value = item.value); + if (!scopes.has(item.file)) { + scopes.set(item.file, []); + } + scopes.get(item.file).push(value); + } + return { + key, + paths: Array.from(scopes.keys()), + scopes, + value, + values + }; +} +function configFilePath(filePath) { + return filePath.replace(/^(file):/, ""); +} +function* configParser(text, requestedKey = null) { + const lines = text.split("\0"); + for (let i = 0, max = lines.length - 1; i < max; ) { + const file = configFilePath(lines[i++]); + let value = lines[i++]; + let key = requestedKey; + if (value.includes("\n")) { + const line = splitOn(value, "\n"); + key = line[0]; + value = line[1]; + } + yield { file, key, value }; + } +} +var ConfigList; +var init_ConfigList = __esm({ + "src/lib/responses/ConfigList.ts"() { + init_utils(); + ConfigList = class { + constructor() { + this.files = []; + this.values = /* @__PURE__ */ Object.create(null); + } + get all() { + if (!this._all) { + this._all = this.files.reduce((all, file) => { + return Object.assign(all, this.values[file]); + }, {}); + } + return this._all; + } + addFile(file) { + if (!(file in this.values)) { + const latest = last(this.files); + this.values[file] = latest ? Object.create(this.values[latest]) : {}; + this.files.push(file); + } + return this.values[file]; + } + addValue(file, key, value) { + const values = this.addFile(file); + if (!values.hasOwnProperty(key)) { + values[key] = value; + } else if (Array.isArray(values[key])) { + values[key].push(value); + } else { + values[key] = [values[key], value]; + } + this._all = void 0; + } + }; + } +}); +function asConfigScope(scope, fallback) { + if (typeof scope === "string" && GitConfigScope.hasOwnProperty(scope)) { + return scope; + } + return fallback; +} +function addConfigTask(key, value, append2, scope) { + const commands = ["config", `--${scope}`]; + if (append2) { + commands.push("--add"); + } + commands.push(key, value); + return { + commands, + format: "utf-8", + parser(text) { + return text; + } + }; +} +function getConfigTask(key, scope) { + const commands = ["config", "--null", "--show-origin", "--get-all", key]; + if (scope) { + commands.splice(1, 0, `--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configGetParser(text, key); + } + }; +} +function listConfigTask(scope) { + const commands = ["config", "--list", "--show-origin", "--null"]; + if (scope) { + commands.push(`--${scope}`); + } + return { + commands, + format: "utf-8", + parser(text) { + return configListParser(text); + } + }; +} +function config_default() { + return { + addConfig(key, value, ...rest) { + return this._runTask(addConfigTask(key, value, rest[0] === true, asConfigScope( + rest[1], + "local" + /* local */ + )), trailingFunctionArgument(arguments)); + }, + getConfig(key, scope) { + return this._runTask(getConfigTask(key, asConfigScope(scope, void 0)), trailingFunctionArgument(arguments)); + }, + listConfig(...rest) { + return this._runTask(listConfigTask(asConfigScope(rest[0], void 0)), trailingFunctionArgument(arguments)); + } + }; +} +var GitConfigScope; +var init_config = __esm({ + "src/lib/tasks/config.ts"() { + init_ConfigList(); + init_utils(); + GitConfigScope = /* @__PURE__ */ ((GitConfigScope2) => { + GitConfigScope2["system"] = "system"; + GitConfigScope2["global"] = "global"; + GitConfigScope2["local"] = "local"; + GitConfigScope2["worktree"] = "worktree"; + return GitConfigScope2; + })(GitConfigScope || {}); + } +}); +function isDiffNameStatus(input) { + return diffNameStatus.has(input); +} +var DiffNameStatus; +var diffNameStatus; +var init_diff_name_status = __esm({ + "src/lib/tasks/diff-name-status.ts"() { + DiffNameStatus = /* @__PURE__ */ ((DiffNameStatus2) => { + DiffNameStatus2["ADDED"] = "A"; + DiffNameStatus2["COPIED"] = "C"; + DiffNameStatus2["DELETED"] = "D"; + DiffNameStatus2["MODIFIED"] = "M"; + DiffNameStatus2["RENAMED"] = "R"; + DiffNameStatus2["CHANGED"] = "T"; + DiffNameStatus2["UNMERGED"] = "U"; + DiffNameStatus2["UNKNOWN"] = "X"; + DiffNameStatus2["BROKEN"] = "B"; + return DiffNameStatus2; + })(DiffNameStatus || {}); + diffNameStatus = new Set(Object.values(DiffNameStatus)); + } +}); +function grepQueryBuilder(...params) { + return new GrepQuery().param(...params); +} +function parseGrep(grep) { + const paths = /* @__PURE__ */ new Set(); + const results = {}; + forEachLineWithContent(grep, (input) => { + const [path, line, preview] = input.split(NULL); + paths.add(path); + (results[path] = results[path] || []).push({ + line: asNumber(line), + path, + preview + }); + }); + return { + paths, + results + }; +} +function grep_default() { + return { + grep(searchTerm) { + const then = trailingFunctionArgument(arguments); + const options = getTrailingOptions(arguments); + for (const option of disallowedOptions) { + if (options.includes(option)) { + return this._runTask(configurationErrorTask(`git.grep: use of "${option}" is not supported.`), then); + } + } + if (typeof searchTerm === "string") { + searchTerm = grepQueryBuilder().param(searchTerm); + } + const commands = ["grep", "--null", "-n", "--full-name", ...options, ...searchTerm]; + return this._runTask({ + commands, + format: "utf-8", + parser(stdOut) { + return parseGrep(stdOut); + } + }, then); + } + }; +} +var disallowedOptions; +var Query; +var _a; +var GrepQuery; +var init_grep = __esm({ + "src/lib/tasks/grep.ts"() { + init_utils(); + init_task(); + disallowedOptions = ["-h"]; + Query = Symbol("grepQuery"); + GrepQuery = class { + constructor() { + this[_a] = []; + } + *[(_a = Query, Symbol.iterator)]() { + for (const query of this[Query]) { + yield query; + } + } + and(...and) { + and.length && this[Query].push("--and", "(", ...prefixedArray(and, "-e"), ")"); + return this; + } + param(...param) { + this[Query].push(...prefixedArray(param, "-e")); + return this; + } + }; + } +}); +var reset_exports = {}; +__export2(reset_exports, { + ResetMode: () => ResetMode, + getResetMode: () => getResetMode, + resetTask: () => resetTask +}); +function resetTask(mode, customArgs) { + const commands = ["reset"]; + if (isValidResetMode(mode)) { + commands.push(`--${mode}`); + } + commands.push(...customArgs); + return straightThroughStringTask(commands); +} +function getResetMode(mode) { + if (isValidResetMode(mode)) { + return mode; + } + switch (typeof mode) { + case "string": + case "undefined": + return "soft"; + } + return; +} +function isValidResetMode(mode) { + return ResetModes.includes(mode); +} +var ResetMode; +var ResetModes; +var init_reset = __esm({ + "src/lib/tasks/reset.ts"() { + init_task(); + ResetMode = /* @__PURE__ */ ((ResetMode2) => { + ResetMode2["MIXED"] = "mixed"; + ResetMode2["SOFT"] = "soft"; + ResetMode2["HARD"] = "hard"; + ResetMode2["MERGE"] = "merge"; + ResetMode2["KEEP"] = "keep"; + return ResetMode2; + })(ResetMode || {}); + ResetModes = Array.from(Object.values(ResetMode)); + } +}); +function createLog() { + return (0, import_debug.default)("simple-git"); +} +function prefixedLogger(to, prefix, forward) { + if (!prefix || !String(prefix).replace(/\s*/, "")) { + return !forward ? to : (message, ...args) => { + to(message, ...args); + forward(message, ...args); + }; + } + return (message, ...args) => { + to(`%s ${message}`, prefix, ...args); + if (forward) { + forward(message, ...args); + } + }; +} +function childLoggerName(name, childDebugger, { namespace: parentNamespace }) { + if (typeof name === "string") { + return name; + } + const childNamespace = childDebugger && childDebugger.namespace || ""; + if (childNamespace.startsWith(parentNamespace)) { + return childNamespace.substr(parentNamespace.length + 1); + } + return childNamespace || parentNamespace; +} +function createLogger(label, verbose, initialStep, infoDebugger = createLog()) { + const labelPrefix = label && `[${label}]` || ""; + const spawned = []; + const debugDebugger = typeof verbose === "string" ? infoDebugger.extend(verbose) : verbose; + const key = childLoggerName(filterType(verbose, filterString), debugDebugger, infoDebugger); + return step(initialStep); + function sibling(name, initial) { + return append(spawned, createLogger(label, key.replace(/^[^:]+/, name), initial, infoDebugger)); + } + function step(phase) { + const stepPrefix = phase && `[${phase}]` || ""; + const debug2 = debugDebugger && prefixedLogger(debugDebugger, stepPrefix) || NOOP; + const info = prefixedLogger(infoDebugger, `${labelPrefix} ${stepPrefix}`, debug2); + return Object.assign(debugDebugger ? debug2 : info, { + label, + sibling, + info, + step + }); + } +} +var init_git_logger = __esm({ + "src/lib/git-logger.ts"() { + init_utils(); + import_debug.default.formatters.L = (value) => String(filterHasLength(value) ? value.length : "-"); + import_debug.default.formatters.B = (value) => { + if (Buffer.isBuffer(value)) { + return value.toString("utf8"); + } + return objectToString(value); + }; + } +}); +var _TasksPendingQueue; +var TasksPendingQueue; +var init_tasks_pending_queue = __esm({ + "src/lib/runners/tasks-pending-queue.ts"() { + init_git_error(); + init_git_logger(); + _TasksPendingQueue = class { + constructor(logLabel = "GitExecutor") { + this.logLabel = logLabel; + this._queue = /* @__PURE__ */ new Map(); + } + withProgress(task) { + return this._queue.get(task); + } + createProgress(task) { + const name = _TasksPendingQueue.getName(task.commands[0]); + const logger = createLogger(this.logLabel, name); + return { + task, + logger, + name + }; + } + push(task) { + const progress = this.createProgress(task); + progress.logger("Adding task to the queue, commands = %o", task.commands); + this._queue.set(task, progress); + return progress; + } + fatal(err) { + for (const [task, { logger }] of Array.from(this._queue.entries())) { + if (task === err.task) { + logger.info(`Failed %o`, err); + logger(`Fatal exception, any as-yet un-started tasks run through this executor will not be attempted`); + } else { + logger.info(`A fatal exception occurred in a previous task, the queue has been purged: %o`, err.message); + } + this.complete(task); + } + if (this._queue.size !== 0) { + throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`); + } + } + complete(task) { + const progress = this.withProgress(task); + if (progress) { + this._queue.delete(task); + } + } + attempt(task) { + const progress = this.withProgress(task); + if (!progress) { + throw new GitError(void 0, "TasksPendingQueue: attempt called for an unknown task"); + } + progress.logger("Starting task"); + return progress; + } + static getName(name = "empty") { + return `task:${name}:${++_TasksPendingQueue.counter}`; + } + }; + TasksPendingQueue = _TasksPendingQueue; + TasksPendingQueue.counter = 0; + } +}); +function pluginContext(task, commands) { + return { + method: first(task.commands) || "", + commands + }; +} +function onErrorReceived(target, logger) { + return (err) => { + logger(`[ERROR] child process exception %o`, err); + target.push(Buffer.from(String(err.stack), "ascii")); + }; +} +function onDataReceived(target, name, logger, output) { + return (buffer) => { + logger(`%s received %L bytes`, name, buffer); + output(`%B`, buffer); + target.push(buffer); + }; +} +var GitExecutorChain; +var init_git_executor_chain = __esm({ + "src/lib/runners/git-executor-chain.ts"() { + init_git_error(); + init_task(); + init_utils(); + init_tasks_pending_queue(); + GitExecutorChain = class { + constructor(_executor, _scheduler, _plugins) { + this._executor = _executor; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = Promise.resolve(); + this._queue = new TasksPendingQueue(); + } + get binary() { + return this._executor.binary; + } + get cwd() { + return this._cwd || this._executor.cwd; + } + set cwd(cwd) { + this._cwd = cwd; + } + get env() { + return this._executor.env; + } + get outputHandler() { + return this._executor.outputHandler; + } + chain() { + return this; + } + push(task) { + this._queue.push(task); + return this._chain = this._chain.then(() => this.attemptTask(task)); + } + attemptTask(task) { + return __async(this, null, function* () { + const onScheduleComplete = yield this._scheduler.next(); + const onQueueComplete = () => this._queue.complete(task); + try { + const { logger } = this._queue.attempt(task); + return yield isEmptyTask(task) ? this.attemptEmptyTask(task, logger) : this.attemptRemoteTask(task, logger); + } catch (e) { + throw this.onFatalException(task, e); + } finally { + onQueueComplete(); + onScheduleComplete(); + } + }); + } + onFatalException(task, e) { + const gitError = e instanceof GitError ? Object.assign(e, { task }) : new GitError(task, e && String(e)); + this._chain = Promise.resolve(); + this._queue.fatal(gitError); + return gitError; + } + attemptRemoteTask(task, logger) { + return __async(this, null, function* () { + const args = this._plugins.exec("spawn.args", [...task.commands], pluginContext(task, task.commands)); + const raw = yield this.gitResponse(task, this.binary, args, this.outputHandler, logger.step("SPAWN")); + const outputStreams = yield this.handleTaskData(task, args, raw, logger.step("HANDLE")); + logger(`passing response to task's parser as a %s`, task.format); + if (isBufferTask(task)) { + return callTaskParser(task.parser, outputStreams); + } + return callTaskParser(task.parser, outputStreams.asStrings()); + }); + } + attemptEmptyTask(task, logger) { + return __async(this, null, function* () { + logger(`empty task bypassing child process to call to task's parser`); + return task.parser(this); + }); + } + handleTaskData(task, args, result, logger) { + const { exitCode, rejection, stdOut, stdErr } = result; + return new Promise((done, fail) => { + logger(`Preparing to handle process response exitCode=%d stdOut=`, exitCode); + const { error } = this._plugins.exec("task.error", { error: rejection }, __spreadValues(__spreadValues({}, pluginContext(task, args)), result)); + if (error && task.onError) { + logger.info(`exitCode=%s handling with custom error handler`); + return task.onError(result, error, (newStdOut) => { + logger.info(`custom error handler treated as success`); + logger(`custom error returned a %s`, objectToString(newStdOut)); + done(new GitOutputStreams(Array.isArray(newStdOut) ? Buffer.concat(newStdOut) : newStdOut, Buffer.concat(stdErr))); + }, fail); + } + if (error) { + logger.info(`handling as error: exitCode=%s stdErr=%s rejection=%o`, exitCode, stdErr.length, rejection); + return fail(error); + } + logger.info(`retrieving task output complete`); + done(new GitOutputStreams(Buffer.concat(stdOut), Buffer.concat(stdErr))); + }); + } + gitResponse(task, command, args, outputHandler, logger) { + return __async(this, null, function* () { + const outputLogger = logger.sibling("output"); + const spawnOptions = this._plugins.exec("spawn.options", { + cwd: this.cwd, + env: this.env, + windowsHide: true + }, pluginContext(task, task.commands)); + return new Promise((done) => { + const stdOut = []; + const stdErr = []; + logger.info(`%s %o`, command, args); + logger("%O", spawnOptions); + let rejection = this._beforeSpawn(task, args); + if (rejection) { + return done({ + stdOut, + stdErr, + exitCode: 9901, + rejection + }); + } + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + const spawned = (0, import_child_process.spawn)(command, args, spawnOptions); + spawned.stdout.on("data", onDataReceived(stdOut, "stdOut", logger, outputLogger.step("stdOut"))); + spawned.stderr.on("data", onDataReceived(stdErr, "stdErr", logger, outputLogger.step("stdErr"))); + spawned.on("error", onErrorReceived(stdErr, logger)); + if (outputHandler) { + logger(`Passing child process stdOut/stdErr to custom outputHandler`); + outputHandler(command, spawned.stdout, spawned.stderr, [...args]); + } + this._plugins.exec("spawn.after", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + spawned, + close(exitCode, reason) { + done({ + stdOut, + stdErr, + exitCode, + rejection: rejection || reason + }); + }, + kill(reason) { + if (spawned.killed) { + return; + } + rejection = reason; + spawned.kill("SIGINT"); + } + })); + }); + }); + } + _beforeSpawn(task, args) { + let rejection; + this._plugins.exec("spawn.before", void 0, __spreadProps(__spreadValues({}, pluginContext(task, args)), { + kill(reason) { + rejection = reason || rejection; + } + })); + return rejection; + } + }; + } +}); +var git_executor_exports = {}; +__export2(git_executor_exports, { + GitExecutor: () => GitExecutor +}); +var GitExecutor; +var init_git_executor = __esm({ + "src/lib/runners/git-executor.ts"() { + init_git_executor_chain(); + GitExecutor = class { + constructor(binary = "git", cwd, _scheduler, _plugins) { + this.binary = binary; + this.cwd = cwd; + this._scheduler = _scheduler; + this._plugins = _plugins; + this._chain = new GitExecutorChain(this, this._scheduler, this._plugins); + } + chain() { + return new GitExecutorChain(this, this._scheduler, this._plugins); + } + push(task) { + return this._chain.push(task); + } + }; + } +}); +function taskCallback(task, response, callback = NOOP) { + const onSuccess = (data) => { + callback(null, data); + }; + const onError2 = (err) => { + if ((err == null ? void 0 : err.task) === task) { + callback(err instanceof GitResponseError ? addDeprecationNoticeToError(err) : err, void 0); + } + }; + response.then(onSuccess, onError2); +} +function addDeprecationNoticeToError(err) { + let log = (name) => { + console.warn(`simple-git deprecation notice: accessing GitResponseError.${name} should be GitResponseError.git.${name}, this will no longer be available in version 3`); + log = NOOP; + }; + return Object.create(err, Object.getOwnPropertyNames(err.git).reduce(descriptorReducer, {})); + function descriptorReducer(all, name) { + if (name in err) { + return all; + } + all[name] = { + enumerable: false, + configurable: false, + get() { + log(name); + return err.git[name]; + } + }; + return all; + } +} +var init_task_callback = __esm({ + "src/lib/task-callback.ts"() { + init_git_response_error(); + init_utils(); + } +}); +function changeWorkingDirectoryTask(directory, root) { + return adhocExecTask((instance) => { + if (!folderExists(directory)) { + throw new Error(`Git.cwd: cannot change to non-directory "${directory}"`); + } + return (root || instance).cwd = directory; + }); +} +var init_change_working_directory = __esm({ + "src/lib/tasks/change-working-directory.ts"() { + init_utils(); + init_task(); + } +}); +function checkoutTask(args) { + const commands = ["checkout", ...args]; + if (commands[1] === "-b" && commands.includes("-B")) { + commands[1] = remove(commands, "-B"); + } + return straightThroughStringTask(commands); +} +function checkout_default() { + return { + checkout() { + return this._runTask(checkoutTask(getTrailingOptions(arguments, 1)), trailingFunctionArgument(arguments)); + }, + checkoutBranch(branchName, startPoint) { + return this._runTask(checkoutTask(["-b", branchName, startPoint, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + }, + checkoutLocalBranch(branchName) { + return this._runTask(checkoutTask(["-b", branchName, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + }; +} +var init_checkout = __esm({ + "src/lib/tasks/checkout.ts"() { + init_utils(); + init_task(); + } +}); +function parseCommitResult(stdOut) { + const result = { + author: null, + branch: "", + commit: "", + root: false, + summary: { + changes: 0, + insertions: 0, + deletions: 0 + } + }; + return parseStringResponse(result, parsers, stdOut); +} +var parsers; +var init_parse_commit = __esm({ + "src/lib/parsers/parse-commit.ts"() { + init_utils(); + parsers = [ + new LineParser(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/, (result, [branch, root, commit]) => { + result.branch = branch; + result.commit = commit; + result.root = !!root; + }), + new LineParser(/\s*Author:\s(.+)/i, (result, [author]) => { + const parts = author.split("<"); + const email = parts.pop(); + if (!email || !email.includes("@")) { + return; + } + result.author = { + email: email.substr(0, email.length - 1), + name: parts.join("<").trim() + }; + }), + new LineParser(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g, (result, [changes, insertions, deletions]) => { + result.summary.changes = parseInt(changes, 10) || 0; + result.summary.insertions = parseInt(insertions, 10) || 0; + result.summary.deletions = parseInt(deletions, 10) || 0; + }), + new LineParser(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/, (result, [changes, lines, direction]) => { + result.summary.changes = parseInt(changes, 10) || 0; + const count = parseInt(lines, 10) || 0; + if (direction === "-") { + result.summary.deletions = count; + } else if (direction === "+") { + result.summary.insertions = count; + } + }) + ]; + } +}); +function commitTask(message, files, customArgs) { + const commands = [ + "-c", + "core.abbrev=40", + "commit", + ...prefixedArray(message, "-m"), + ...files, + ...customArgs + ]; + return { + commands, + format: "utf-8", + parser: parseCommitResult + }; +} +function commit_default() { + return { + commit(message, ...rest) { + const next = trailingFunctionArgument(arguments); + const task = rejectDeprecatedSignatures(message) || commitTask(asArray(message), asArray(filterType(rest[0], filterStringOrStringArray, [])), [...filterType(rest[1], filterArray, []), ...getTrailingOptions(arguments, 0, true)]); + return this._runTask(task, next); + } + }; + function rejectDeprecatedSignatures(message) { + return !filterStringOrStringArray(message) && configurationErrorTask(`git.commit: requires the commit message to be supplied as a string/string[]`); + } +} +var init_commit = __esm({ + "src/lib/tasks/commit.ts"() { + init_parse_commit(); + init_utils(); + init_task(); + } +}); +function first_commit_default() { + return { + firstCommit() { + return this._runTask(straightThroughStringTask(["rev-list", "--max-parents=0", "HEAD"], true), trailingFunctionArgument(arguments)); + } + }; +} +var init_first_commit = __esm({ + "src/lib/tasks/first-commit.ts"() { + init_utils(); + init_task(); + } +}); +function hashObjectTask(filePath, write) { + const commands = ["hash-object", filePath]; + if (write) { + commands.push("-w"); + } + return straightThroughStringTask(commands, true); +} +var init_hash_object = __esm({ + "src/lib/tasks/hash-object.ts"() { + init_task(); + } +}); +function parseInit(bare, path, text) { + const response = String(text).trim(); + let result; + if (result = initResponseRegex.exec(response)) { + return new InitSummary(bare, path, false, result[1]); + } + if (result = reInitResponseRegex.exec(response)) { + return new InitSummary(bare, path, true, result[1]); + } + let gitDir = ""; + const tokens = response.split(" "); + while (tokens.length) { + const token = tokens.shift(); + if (token === "in") { + gitDir = tokens.join(" "); + break; + } + } + return new InitSummary(bare, path, /^re/i.test(response), gitDir); +} +var InitSummary; +var initResponseRegex; +var reInitResponseRegex; +var init_InitSummary = __esm({ + "src/lib/responses/InitSummary.ts"() { + InitSummary = class { + constructor(bare, path, existing, gitDir) { + this.bare = bare; + this.path = path; + this.existing = existing; + this.gitDir = gitDir; + } + }; + initResponseRegex = /^Init.+ repository in (.+)$/; + reInitResponseRegex = /^Rein.+ in (.+)$/; + } +}); +function hasBareCommand(command) { + return command.includes(bareCommand); +} +function initTask(bare = false, path, customArgs) { + const commands = ["init", ...customArgs]; + if (bare && !hasBareCommand(commands)) { + commands.splice(1, 0, bareCommand); + } + return { + commands, + format: "utf-8", + parser(text) { + return parseInit(commands.includes("--bare"), path, text); + } + }; +} +var bareCommand; +var init_init = __esm({ + "src/lib/tasks/init.ts"() { + init_InitSummary(); + bareCommand = "--bare"; + } +}); +function logFormatFromCommand(customArgs) { + for (let i = 0; i < customArgs.length; i++) { + const format = logFormatRegex.exec(customArgs[i]); + if (format) { + return `--${format[1]}`; + } + } + return ""; +} +function isLogFormat(customArg) { + return logFormatRegex.test(customArg); +} +var logFormatRegex; +var init_log_format = __esm({ + "src/lib/args/log-format.ts"() { + logFormatRegex = /^--(stat|numstat|name-only|name-status)(=|$)/; + } +}); +var DiffSummary; +var init_DiffSummary = __esm({ + "src/lib/responses/DiffSummary.ts"() { + DiffSummary = class { + constructor() { + this.changed = 0; + this.deletions = 0; + this.insertions = 0; + this.files = []; + } + }; + } +}); +function getDiffParser(format = "") { + const parser3 = diffSummaryParsers[format]; + return (stdOut) => parseStringResponse(new DiffSummary(), parser3, stdOut, false); +} +var statParser; +var numStatParser; +var nameOnlyParser; +var nameStatusParser; +var diffSummaryParsers; +var init_parse_diff_summary = __esm({ + "src/lib/parsers/parse-diff-summary.ts"() { + init_log_format(); + init_DiffSummary(); + init_diff_name_status(); + init_utils(); + statParser = [ + new LineParser(/(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/, (result, [file, changes, alterations = ""]) => { + result.files.push({ + file: file.trim(), + changes: asNumber(changes), + insertions: alterations.replace(/[^+]/g, "").length, + deletions: alterations.replace(/[^-]/g, "").length, + binary: false + }); + }), + new LineParser(/(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/, (result, [file, before, after]) => { + result.files.push({ + file: file.trim(), + before: asNumber(before), + after: asNumber(after), + binary: true + }); + }), + new LineParser(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/, (result, [changed, summary]) => { + const inserted = /(\d+) i/.exec(summary); + const deleted = /(\d+) d/.exec(summary); + result.changed = asNumber(changed); + result.insertions = asNumber(inserted == null ? void 0 : inserted[1]); + result.deletions = asNumber(deleted == null ? void 0 : deleted[1]); + }) + ]; + numStatParser = [ + new LineParser(/(\d+)\t(\d+)\t(.+)$/, (result, [changesInsert, changesDelete, file]) => { + const insertions = asNumber(changesInsert); + const deletions = asNumber(changesDelete); + result.changed++; + result.insertions += insertions; + result.deletions += deletions; + result.files.push({ + file, + changes: insertions + deletions, + insertions, + deletions, + binary: false + }); + }), + new LineParser(/-\t-\t(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + after: 0, + before: 0, + binary: true + }); + }) + ]; + nameOnlyParser = [ + new LineParser(/(.+)$/, (result, [file]) => { + result.changed++; + result.files.push({ + file, + changes: 0, + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + nameStatusParser = [ + new LineParser(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/, (result, [status, _similarity, from, _to, to]) => { + result.changed++; + result.files.push({ + file: to != null ? to : from, + changes: 0, + status: orVoid(isDiffNameStatus(status) && status), + insertions: 0, + deletions: 0, + binary: false + }); + }) + ]; + diffSummaryParsers = { + [ + "" + /* NONE */ + ]: statParser, + [ + "--stat" + /* STAT */ + ]: statParser, + [ + "--numstat" + /* NUM_STAT */ + ]: numStatParser, + [ + "--name-status" + /* NAME_STATUS */ + ]: nameStatusParser, + [ + "--name-only" + /* NAME_ONLY */ + ]: nameOnlyParser + }; + } +}); +function lineBuilder(tokens, fields) { + return fields.reduce((line, field, index) => { + line[field] = tokens[index] || ""; + return line; + }, /* @__PURE__ */ Object.create({ diff: null })); +} +function createListLogSummaryParser(splitter = SPLITTER, fields = defaultFieldNames, logFormat = "") { + const parseDiffResult = getDiffParser(logFormat); + return function(stdOut) { + const all = toLinesWithContent(stdOut, true, START_BOUNDARY).map(function(item) { + const lineDetail = item.trim().split(COMMIT_BOUNDARY); + const listLogLine = lineBuilder(lineDetail[0].trim().split(splitter), fields); + if (lineDetail.length > 1 && !!lineDetail[1].trim()) { + listLogLine.diff = parseDiffResult(lineDetail[1]); + } + return listLogLine; + }); + return { + all, + latest: all.length && all[0] || null, + total: all.length + }; + }; +} +var START_BOUNDARY; +var COMMIT_BOUNDARY; +var SPLITTER; +var defaultFieldNames; +var init_parse_list_log_summary = __esm({ + "src/lib/parsers/parse-list-log-summary.ts"() { + init_utils(); + init_parse_diff_summary(); + init_log_format(); + START_BOUNDARY = "\xF2\xF2\xF2\xF2\xF2\xF2 "; + COMMIT_BOUNDARY = " \xF2\xF2"; + SPLITTER = " \xF2 "; + defaultFieldNames = ["hash", "date", "message", "refs", "author_name", "author_email"]; + } +}); +var diff_exports = {}; +__export2(diff_exports, { + diffSummaryTask: () => diffSummaryTask, + validateLogFormatConfig: () => validateLogFormatConfig +}); +function diffSummaryTask(customArgs) { + let logFormat = logFormatFromCommand(customArgs); + const commands = ["diff"]; + if (logFormat === "") { + logFormat = "--stat"; + commands.push("--stat=4096"); + } + commands.push(...customArgs); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: getDiffParser(logFormat) + }; +} +function validateLogFormatConfig(customArgs) { + const flags = customArgs.filter(isLogFormat); + if (flags.length > 1) { + return configurationErrorTask(`Summary flags are mutually exclusive - pick one of ${flags.join(",")}`); + } + if (flags.length && customArgs.includes("-z")) { + return configurationErrorTask(`Summary flag ${flags} parsing is not compatible with null termination option '-z'`); + } +} +var init_diff = __esm({ + "src/lib/tasks/diff.ts"() { + init_log_format(); + init_parse_diff_summary(); + init_task(); + } +}); +function prettyFormat(format, splitter) { + const fields = []; + const formatStr = []; + Object.keys(format).forEach((field) => { + fields.push(field); + formatStr.push(String(format[field])); + }); + return [fields, formatStr.join(splitter)]; +} +function userOptions(input) { + return Object.keys(input).reduce((out, key) => { + if (!(key in excludeOptions)) { + out[key] = input[key]; + } + return out; + }, {}); +} +function parseLogOptions(opt = {}, customArgs = []) { + const splitter = filterType(opt.splitter, filterString, SPLITTER); + const format = !filterPrimitives(opt.format) && opt.format ? opt.format : { + hash: "%H", + date: opt.strictDate === false ? "%ai" : "%aI", + message: "%s", + refs: "%D", + body: opt.multiLine ? "%B" : "%b", + author_name: opt.mailMap !== false ? "%aN" : "%an", + author_email: opt.mailMap !== false ? "%aE" : "%ae" + }; + const [fields, formatStr] = prettyFormat(format, splitter); + const suffix = []; + const command = [ + `--pretty=format:${START_BOUNDARY}${formatStr}${COMMIT_BOUNDARY}`, + ...customArgs + ]; + const maxCount = opt.n || opt["max-count"] || opt.maxCount; + if (maxCount) { + command.push(`--max-count=${maxCount}`); + } + if (opt.from || opt.to) { + const rangeOperator = opt.symmetric !== false ? "..." : ".."; + suffix.push(`${opt.from || ""}${rangeOperator}${opt.to || ""}`); + } + if (filterString(opt.file)) { + command.push("--follow", pathspec(opt.file)); + } + appendTaskOptions(userOptions(opt), command); + return { + fields, + splitter, + commands: [...command, ...suffix] + }; +} +function logTask(splitter, fields, customArgs) { + const parser3 = createListLogSummaryParser(splitter, fields, logFormatFromCommand(customArgs)); + return { + commands: ["log", ...customArgs], + format: "utf-8", + parser: parser3 + }; +} +function log_default() { + return { + log(...rest) { + const next = trailingFunctionArgument(arguments); + const options = parseLogOptions(trailingOptionsArgument(arguments), filterType(arguments[0], filterArray)); + const task = rejectDeprecatedSignatures(...rest) || validateLogFormatConfig(options.commands) || createLogTask(options); + return this._runTask(task, next); + } + }; + function createLogTask(options) { + return logTask(options.splitter, options.fields, options.commands); + } + function rejectDeprecatedSignatures(from, to) { + return filterString(from) && filterString(to) && configurationErrorTask(`git.log(string, string) should be replaced with git.log({ from: string, to: string })`); + } +} +var excludeOptions; +var init_log = __esm({ + "src/lib/tasks/log.ts"() { + init_log_format(); + init_pathspec(); + init_parse_list_log_summary(); + init_utils(); + init_task(); + init_diff(); + excludeOptions = /* @__PURE__ */ ((excludeOptions2) => { + excludeOptions2[excludeOptions2["--pretty"] = 0] = "--pretty"; + excludeOptions2[excludeOptions2["max-count"] = 1] = "max-count"; + excludeOptions2[excludeOptions2["maxCount"] = 2] = "maxCount"; + excludeOptions2[excludeOptions2["n"] = 3] = "n"; + excludeOptions2[excludeOptions2["file"] = 4] = "file"; + excludeOptions2[excludeOptions2["format"] = 5] = "format"; + excludeOptions2[excludeOptions2["from"] = 6] = "from"; + excludeOptions2[excludeOptions2["to"] = 7] = "to"; + excludeOptions2[excludeOptions2["splitter"] = 8] = "splitter"; + excludeOptions2[excludeOptions2["symmetric"] = 9] = "symmetric"; + excludeOptions2[excludeOptions2["mailMap"] = 10] = "mailMap"; + excludeOptions2[excludeOptions2["multiLine"] = 11] = "multiLine"; + excludeOptions2[excludeOptions2["strictDate"] = 12] = "strictDate"; + return excludeOptions2; + })(excludeOptions || {}); + } +}); +var MergeSummaryConflict; +var MergeSummaryDetail; +var init_MergeSummary = __esm({ + "src/lib/responses/MergeSummary.ts"() { + MergeSummaryConflict = class { + constructor(reason, file = null, meta) { + this.reason = reason; + this.file = file; + this.meta = meta; + } + toString() { + return `${this.file}:${this.reason}`; + } + }; + MergeSummaryDetail = class { + constructor() { + this.conflicts = []; + this.merges = []; + this.result = "success"; + } + get failed() { + return this.conflicts.length > 0; + } + get reason() { + return this.result; + } + toString() { + if (this.conflicts.length) { + return `CONFLICTS: ${this.conflicts.join(", ")}`; + } + return "OK"; + } + }; + } +}); +var PullSummary; +var PullFailedSummary; +var init_PullSummary = __esm({ + "src/lib/responses/PullSummary.ts"() { + PullSummary = class { + constructor() { + this.remoteMessages = { + all: [] + }; + this.created = []; + this.deleted = []; + this.files = []; + this.deletions = {}; + this.insertions = {}; + this.summary = { + changes: 0, + deletions: 0, + insertions: 0 + }; + } + }; + PullFailedSummary = class { + constructor() { + this.remote = ""; + this.hash = { + local: "", + remote: "" + }; + this.branch = { + local: "", + remote: "" + }; + this.message = ""; + } + toString() { + return this.message; + } + }; + } +}); +function objectEnumerationResult(remoteMessages) { + return remoteMessages.objects = remoteMessages.objects || { + compressing: 0, + counting: 0, + enumerating: 0, + packReused: 0, + reused: { count: 0, delta: 0 }, + total: { count: 0, delta: 0 } + }; +} +function asObjectCount(source) { + const count = /^\s*(\d+)/.exec(source); + const delta = /delta (\d+)/i.exec(source); + return { + count: asNumber(count && count[1] || "0"), + delta: asNumber(delta && delta[1] || "0") + }; +} +var remoteMessagesObjectParsers; +var init_parse_remote_objects = __esm({ + "src/lib/parsers/parse-remote-objects.ts"() { + init_utils(); + remoteMessagesObjectParsers = [ + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i, (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + }), + new RemoteLineParser(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i, (result, [action, count]) => { + const key = action.toLowerCase(); + const enumeration = objectEnumerationResult(result.remoteMessages); + Object.assign(enumeration, { [key]: asNumber(count) }); + }), + new RemoteLineParser(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i, (result, [total, reused, packReused]) => { + const objects = objectEnumerationResult(result.remoteMessages); + objects.total = asObjectCount(total); + objects.reused = asObjectCount(reused); + objects.packReused = asNumber(packReused); + }) + ]; + } +}); +function parseRemoteMessages(_stdOut, stdErr) { + return parseStringResponse({ remoteMessages: new RemoteMessageSummary() }, parsers2, stdErr); +} +var parsers2; +var RemoteMessageSummary; +var init_parse_remote_messages = __esm({ + "src/lib/parsers/parse-remote-messages.ts"() { + init_utils(); + init_parse_remote_objects(); + parsers2 = [ + new RemoteLineParser(/^remote:\s*(.+)$/, (result, [text]) => { + result.remoteMessages.all.push(text.trim()); + return false; + }), + ...remoteMessagesObjectParsers, + new RemoteLineParser([/create a (?:pull|merge) request/i, /\s(https?:\/\/\S+)$/], (result, [pullRequestUrl]) => { + result.remoteMessages.pullRequestUrl = pullRequestUrl; + }), + new RemoteLineParser([/found (\d+) vulnerabilities.+\(([^)]+)\)/i, /\s(https?:\/\/\S+)$/], (result, [count, summary, url]) => { + result.remoteMessages.vulnerabilities = { + count: asNumber(count), + summary, + url + }; + }) + ]; + RemoteMessageSummary = class { + constructor() { + this.all = []; + } + }; + } +}); +function parsePullErrorResult(stdOut, stdErr) { + const pullError = parseStringResponse(new PullFailedSummary(), errorParsers, [stdOut, stdErr]); + return pullError.message && pullError; +} +var FILE_UPDATE_REGEX; +var SUMMARY_REGEX; +var ACTION_REGEX; +var parsers3; +var errorParsers; +var parsePullDetail; +var parsePullResult; +var init_parse_pull = __esm({ + "src/lib/parsers/parse-pull.ts"() { + init_PullSummary(); + init_utils(); + init_parse_remote_messages(); + FILE_UPDATE_REGEX = /^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/; + SUMMARY_REGEX = /(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/; + ACTION_REGEX = /^(create|delete) mode \d+ (.+)/; + parsers3 = [ + new LineParser(FILE_UPDATE_REGEX, (result, [file, insertions, deletions]) => { + result.files.push(file); + if (insertions) { + result.insertions[file] = insertions.length; + } + if (deletions) { + result.deletions[file] = deletions.length; + } + }), + new LineParser(SUMMARY_REGEX, (result, [changes, , insertions, , deletions]) => { + if (insertions !== void 0 || deletions !== void 0) { + result.summary.changes = +changes || 0; + result.summary.insertions = +insertions || 0; + result.summary.deletions = +deletions || 0; + return true; + } + return false; + }), + new LineParser(ACTION_REGEX, (result, [action, file]) => { + append(result.files, file); + append(action === "create" ? result.created : result.deleted, file); + }) + ]; + errorParsers = [ + new LineParser(/^from\s(.+)$/i, (result, [remote]) => void (result.remote = remote)), + new LineParser(/^fatal:\s(.+)$/, (result, [message]) => void (result.message = message)), + new LineParser(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/, (result, [hashLocal, hashRemote, branchLocal, branchRemote]) => { + result.branch.local = branchLocal; + result.hash.local = hashLocal; + result.branch.remote = branchRemote; + result.hash.remote = hashRemote; + }) + ]; + parsePullDetail = (stdOut, stdErr) => { + return parseStringResponse(new PullSummary(), parsers3, [stdOut, stdErr]); + }; + parsePullResult = (stdOut, stdErr) => { + return Object.assign(new PullSummary(), parsePullDetail(stdOut, stdErr), parseRemoteMessages(stdOut, stdErr)); + }; + } +}); +var parsers4; +var parseMergeResult; +var parseMergeDetail; +var init_parse_merge = __esm({ + "src/lib/parsers/parse-merge.ts"() { + init_MergeSummary(); + init_utils(); + init_parse_pull(); + parsers4 = [ + new LineParser(/^Auto-merging\s+(.+)$/, (summary, [autoMerge]) => { + summary.merges.push(autoMerge); + }), + new LineParser(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/, (summary, [reason, file]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file)); + }), + new LineParser(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/, (summary, [reason, file, deleteRef]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, file, { deleteRef })); + }), + new LineParser(/^CONFLICT\s+\((.+)\):/, (summary, [reason]) => { + summary.conflicts.push(new MergeSummaryConflict(reason, null)); + }), + new LineParser(/^Automatic merge failed;\s+(.+)$/, (summary, [result]) => { + summary.result = result; + }) + ]; + parseMergeResult = (stdOut, stdErr) => { + return Object.assign(parseMergeDetail(stdOut, stdErr), parsePullResult(stdOut, stdErr)); + }; + parseMergeDetail = (stdOut) => { + return parseStringResponse(new MergeSummaryDetail(), parsers4, stdOut); + }; + } +}); +function mergeTask(customArgs) { + if (!customArgs.length) { + return configurationErrorTask("Git.merge requires at least one option"); + } + return { + commands: ["merge", ...customArgs], + format: "utf-8", + parser(stdOut, stdErr) { + const merge = parseMergeResult(stdOut, stdErr); + if (merge.failed) { + throw new GitResponseError(merge); + } + return merge; + } + }; +} +var init_merge = __esm({ + "src/lib/tasks/merge.ts"() { + init_git_response_error(); + init_parse_merge(); + init_task(); + } +}); +function pushResultPushedItem(local, remote, status) { + const deleted = status.includes("deleted"); + const tag = status.includes("tag") || /^refs\/tags/.test(local); + const alreadyUpdated = !status.includes("new"); + return { + deleted, + tag, + branch: !tag, + new: !alreadyUpdated, + alreadyUpdated, + local, + remote + }; +} +var parsers5; +var parsePushResult; +var parsePushDetail; +var init_parse_push = __esm({ + "src/lib/parsers/parse-push.ts"() { + init_utils(); + init_parse_remote_messages(); + parsers5 = [ + new LineParser(/^Pushing to (.+)$/, (result, [repo]) => { + result.repo = repo; + }), + new LineParser(/^updating local tracking ref '(.+)'/, (result, [local]) => { + result.ref = __spreadProps(__spreadValues({}, result.ref || {}), { + local + }); + }), + new LineParser(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/, (result, [local, remote, type]) => { + result.pushed.push(pushResultPushedItem(local, remote, type)); + }), + new LineParser(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/, (result, [local, remote, remoteName]) => { + result.branch = __spreadProps(__spreadValues({}, result.branch || {}), { + local, + remote, + remoteName + }); + }), + new LineParser(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/, (result, [local, remote, from, to]) => { + result.update = { + head: { + local, + remote + }, + hash: { + from, + to + } + }; + }) + ]; + parsePushResult = (stdOut, stdErr) => { + const pushDetail = parsePushDetail(stdOut, stdErr); + const responseDetail = parseRemoteMessages(stdOut, stdErr); + return __spreadValues(__spreadValues({}, pushDetail), responseDetail); + }; + parsePushDetail = (stdOut, stdErr) => { + return parseStringResponse({ pushed: [] }, parsers5, [stdOut, stdErr]); + }; + } +}); +var push_exports = {}; +__export2(push_exports, { + pushTagsTask: () => pushTagsTask, + pushTask: () => pushTask +}); +function pushTagsTask(ref = {}, customArgs) { + append(customArgs, "--tags"); + return pushTask(ref, customArgs); +} +function pushTask(ref = {}, customArgs) { + const commands = ["push", ...customArgs]; + if (ref.branch) { + commands.splice(1, 0, ref.branch); + } + if (ref.remote) { + commands.splice(1, 0, ref.remote); + } + remove(commands, "-v"); + append(commands, "--verbose"); + append(commands, "--porcelain"); + return { + commands, + format: "utf-8", + parser: parsePushResult + }; +} +var init_push = __esm({ + "src/lib/tasks/push.ts"() { + init_parse_push(); + init_utils(); + } +}); +function show_default() { + return { + showBuffer() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + if (!commands.includes("--binary")) { + commands.splice(1, 0, "--binary"); + } + return this._runTask(straightThroughBufferTask(commands), trailingFunctionArgument(arguments)); + }, + show() { + const commands = ["show", ...getTrailingOptions(arguments, 1)]; + return this._runTask(straightThroughStringTask(commands), trailingFunctionArgument(arguments)); + } + }; +} +var init_show = __esm({ + "src/lib/tasks/show.ts"() { + init_utils(); + init_task(); + } +}); +var fromPathRegex; +var FileStatusSummary; +var init_FileStatusSummary = __esm({ + "src/lib/responses/FileStatusSummary.ts"() { + fromPathRegex = /^(.+) -> (.+)$/; + FileStatusSummary = class { + constructor(path, index, working_dir) { + this.path = path; + this.index = index; + this.working_dir = working_dir; + if (index + working_dir === "R") { + const detail = fromPathRegex.exec(path) || [null, path, path]; + this.from = detail[1] || ""; + this.path = detail[2] || ""; + } + } + }; + } +}); +function renamedFile(line) { + const [to, from] = line.split(NULL); + return { + from: from || to, + to + }; +} +function parser2(indexX, indexY, handler) { + return [`${indexX}${indexY}`, handler]; +} +function conflicts(indexX, ...indexY) { + return indexY.map((y) => parser2(indexX, y, (result, file) => append(result.conflicted, file))); +} +function splitLine(result, lineStr) { + const trimmed2 = lineStr.trim(); + switch (" ") { + case trimmed2.charAt(2): + return data(trimmed2.charAt(0), trimmed2.charAt(1), trimmed2.substr(3)); + case trimmed2.charAt(1): + return data(" ", trimmed2.charAt(0), trimmed2.substr(2)); + default: + return; + } + function data(index, workingDir, path) { + const raw = `${index}${workingDir}`; + const handler = parsers6.get(raw); + if (handler) { + handler(result, path); + } + if (raw !== "##" && raw !== "!!") { + result.files.push(new FileStatusSummary(path.replace(/\0.+$/, ""), index, workingDir)); + } + } +} +var StatusSummary; +var parsers6; +var parseStatusSummary; +var init_StatusSummary = __esm({ + "src/lib/responses/StatusSummary.ts"() { + init_utils(); + init_FileStatusSummary(); + StatusSummary = 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 = false; + this.isClean = () => { + return !this.files.length; + }; + } + }; + parsers6 = new Map([ + parser2(" ", "A", (result, file) => append(result.created, file)), + parser2(" ", "D", (result, file) => append(result.deleted, file)), + parser2(" ", "M", (result, file) => append(result.modified, file)), + parser2("A", " ", (result, file) => append(result.created, file) && append(result.staged, file)), + parser2("A", "M", (result, file) => append(result.created, file) && append(result.staged, file) && append(result.modified, file)), + parser2("D", " ", (result, file) => append(result.deleted, file) && append(result.staged, file)), + parser2("M", " ", (result, file) => append(result.modified, file) && append(result.staged, file)), + parser2("M", "M", (result, file) => append(result.modified, file) && append(result.staged, file)), + parser2("R", " ", (result, file) => { + append(result.renamed, renamedFile(file)); + }), + parser2("R", "M", (result, file) => { + const renamed = renamedFile(file); + append(result.renamed, renamed); + append(result.modified, renamed.to); + }), + parser2("!", "!", (_result, _file) => { + append(_result.ignored = _result.ignored || [], _file); + }), + parser2("?", "?", (result, file) => append(result.not_added, file)), + ...conflicts( + "A", + "A", + "U" + /* UNMERGED */ + ), + ...conflicts( + "D", + "D", + "U" + /* UNMERGED */ + ), + ...conflicts( + "U", + "A", + "D", + "U" + /* UNMERGED */ + ), + [ + "##", + (result, line) => { + const aheadReg = /ahead (\d+)/; + const behindReg = /behind (\d+)/; + const currentReg = /^(.+?(?=(?:\.{3}|\s|$)))/; + const trackingReg = /\.{3}(\S*)/; + const onEmptyBranchReg = /\son\s([\S]+)$/; + let regexResult; + regexResult = aheadReg.exec(line); + result.ahead = regexResult && +regexResult[1] || 0; + regexResult = behindReg.exec(line); + result.behind = regexResult && +regexResult[1] || 0; + regexResult = currentReg.exec(line); + result.current = regexResult && regexResult[1]; + regexResult = trackingReg.exec(line); + result.tracking = regexResult && regexResult[1]; + regexResult = onEmptyBranchReg.exec(line); + result.current = regexResult && regexResult[1] || result.current; + result.detached = /\(no branch\)/.test(line); + } + ] + ]); + parseStatusSummary = function(text) { + const lines = text.split(NULL); + const status = new StatusSummary(); + for (let i = 0, l = lines.length; i < l; ) { + let line = lines[i++].trim(); + if (!line) { + continue; + } + if (line.charAt(0) === "R") { + line += NULL + (lines[i++] || ""); + } + splitLine(status, line); + } + return status; + }; + } +}); +function statusTask(customArgs) { + const commands = [ + "status", + "--porcelain", + "-b", + "-u", + "--null", + ...customArgs.filter((arg) => !ignoredOptions.includes(arg)) + ]; + return { + format: "utf-8", + commands, + parser(text) { + return parseStatusSummary(text); + } + }; +} +var ignoredOptions; +var init_status = __esm({ + "src/lib/tasks/status.ts"() { + init_StatusSummary(); + ignoredOptions = ["--null", "-z"]; + } +}); +function versionResponse(major = 0, minor = 0, patch = 0, agent = "", installed = true) { + return Object.defineProperty({ + major, + minor, + patch, + agent, + installed + }, "toString", { + value() { + return `${this.major}.${this.minor}.${this.patch}`; + }, + configurable: false, + enumerable: false + }); +} +function notInstalledResponse() { + return versionResponse(0, 0, 0, "", false); +} +function version_default() { + return { + version() { + return this._runTask({ + commands: ["--version"], + format: "utf-8", + parser: versionParser, + onError(result, error, done, fail) { + if (result.exitCode === -2) { + return done(Buffer.from(NOT_INSTALLED)); + } + fail(error); + } + }); + } + }; +} +function versionParser(stdOut) { + if (stdOut === NOT_INSTALLED) { + return notInstalledResponse(); + } + return parseStringResponse(versionResponse(0, 0, 0, stdOut), parsers7, stdOut); +} +var NOT_INSTALLED; +var parsers7; +var init_version = __esm({ + "src/lib/tasks/version.ts"() { + init_utils(); + NOT_INSTALLED = "installed=false"; + parsers7 = [ + new LineParser(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), asNumber(patch), agent)); + }), + new LineParser(/version (\d+)\.(\d+)\.(\D+)(.+)?$/, (result, [major, minor, patch, agent = ""]) => { + Object.assign(result, versionResponse(asNumber(major), asNumber(minor), patch, agent)); + }) + ]; + } +}); +var simple_git_api_exports = {}; +__export2(simple_git_api_exports, { + SimpleGitApi: () => SimpleGitApi +}); +var SimpleGitApi; +var init_simple_git_api = __esm({ + "src/lib/simple-git-api.ts"() { + init_task_callback(); + init_change_working_directory(); + init_checkout(); + init_commit(); + init_config(); + init_first_commit(); + init_grep(); + init_hash_object(); + init_init(); + init_log(); + init_merge(); + init_push(); + init_show(); + init_status(); + init_task(); + init_version(); + init_utils(); + SimpleGitApi = class { + constructor(_executor) { + this._executor = _executor; + } + _runTask(task, then) { + const chain = this._executor.chain(); + const promise = chain.push(task); + if (then) { + taskCallback(task, promise, then); + } + return Object.create(this, { + then: { value: promise.then.bind(promise) }, + catch: { value: promise.catch.bind(promise) }, + _executor: { value: chain } + }); + } + add(files) { + return this._runTask(straightThroughStringTask(["add", ...asArray(files)]), trailingFunctionArgument(arguments)); + } + cwd(directory) { + const next = trailingFunctionArgument(arguments); + if (typeof directory === "string") { + return this._runTask(changeWorkingDirectoryTask(directory, this._executor), next); + } + if (typeof (directory == null ? void 0 : directory.path) === "string") { + return this._runTask(changeWorkingDirectoryTask(directory.path, directory.root && this._executor || void 0), next); + } + return this._runTask(configurationErrorTask("Git.cwd: workingDirectory must be supplied as a string"), next); + } + hashObject(path, write) { + return this._runTask(hashObjectTask(path, write === true), trailingFunctionArgument(arguments)); + } + init(bare) { + return this._runTask(initTask(bare === true, this._executor.cwd, getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + merge() { + return this._runTask(mergeTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + mergeFromTo(remote, branch) { + if (!(filterString(remote) && filterString(branch))) { + return this._runTask(configurationErrorTask(`Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings`)); + } + return this._runTask(mergeTask([remote, branch, ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments, false)); + } + outputHandler(handler) { + this._executor.outputHandler = handler; + return this; + } + push() { + const task = pushTask({ + remote: filterType(arguments[0], filterString), + branch: filterType(arguments[1], filterString) + }, getTrailingOptions(arguments)); + return this._runTask(task, trailingFunctionArgument(arguments)); + } + stash() { + return this._runTask(straightThroughStringTask(["stash", ...getTrailingOptions(arguments)]), trailingFunctionArgument(arguments)); + } + status() { + return this._runTask(statusTask(getTrailingOptions(arguments)), trailingFunctionArgument(arguments)); + } + }; + Object.assign(SimpleGitApi.prototype, checkout_default(), commit_default(), config_default(), first_commit_default(), grep_default(), log_default(), show_default(), version_default()); + } +}); +var scheduler_exports = {}; +__export2(scheduler_exports, { + Scheduler: () => Scheduler +}); +var createScheduledTask; +var Scheduler; +var init_scheduler = __esm({ + "src/lib/runners/scheduler.ts"() { + init_utils(); + init_git_logger(); + createScheduledTask = (() => { + let id = 0; + return () => { + id++; + const { promise, done } = (0, import_promise_deferred.createDeferred)(); + return { + promise, + done, + id + }; + }; + })(); + Scheduler = class { + constructor(concurrency = 2) { + this.concurrency = concurrency; + this.logger = createLogger("", "scheduler"); + this.pending = []; + this.running = []; + this.logger(`Constructed, concurrency=%s`, concurrency); + } + 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; + } + const task = append(this.running, this.pending.shift()); + this.logger(`Attempting id=%s`, task.id); + task.done(() => { + this.logger(`Completing id=`, task.id); + remove(this.running, task); + this.schedule(); + }); + } + next() { + const { promise, id } = append(this.pending, createScheduledTask()); + this.logger(`Scheduling id=%s`, id); + this.schedule(); + return promise; + } + }; + } +}); +var apply_patch_exports = {}; +__export2(apply_patch_exports, { + applyPatchTask: () => applyPatchTask +}); +function applyPatchTask(patches, customArgs) { + return straightThroughStringTask(["apply", ...customArgs, ...patches]); +} +var init_apply_patch = __esm({ + "src/lib/tasks/apply-patch.ts"() { + init_task(); + } +}); +function branchDeletionSuccess(branch, hash) { + return { + branch, + hash, + success: true + }; +} +function branchDeletionFailure(branch) { + return { + branch, + hash: null, + success: false + }; +} +var BranchDeletionBatch; +var init_BranchDeleteSummary = __esm({ + "src/lib/responses/BranchDeleteSummary.ts"() { + BranchDeletionBatch = class { + constructor() { + this.all = []; + this.branches = {}; + this.errors = []; + } + get success() { + return !this.errors.length; + } + }; + } +}); +function hasBranchDeletionError(data, processExitCode) { + return processExitCode === 1 && deleteErrorRegex.test(data); +} +var deleteSuccessRegex; +var deleteErrorRegex; +var parsers8; +var parseBranchDeletions; +var init_parse_branch_delete = __esm({ + "src/lib/parsers/parse-branch-delete.ts"() { + init_BranchDeleteSummary(); + init_utils(); + deleteSuccessRegex = /(\S+)\s+\(\S+\s([^)]+)\)/; + deleteErrorRegex = /^error[^']+'([^']+)'/m; + parsers8 = [ + new LineParser(deleteSuccessRegex, (result, [branch, hash]) => { + const deletion = branchDeletionSuccess(branch, hash); + result.all.push(deletion); + result.branches[branch] = deletion; + }), + new LineParser(deleteErrorRegex, (result, [branch]) => { + const deletion = branchDeletionFailure(branch); + result.errors.push(deletion); + result.all.push(deletion); + result.branches[branch] = deletion; + }) + ]; + parseBranchDeletions = (stdOut, stdErr) => { + return parseStringResponse(new BranchDeletionBatch(), parsers8, [stdOut, stdErr]); + }; + } +}); +var BranchSummaryResult; +var init_BranchSummary = __esm({ + "src/lib/responses/BranchSummary.ts"() { + BranchSummaryResult = class { + constructor() { + this.all = []; + this.branches = {}; + this.current = ""; + this.detached = false; + } + push(status, detached, name, commit, label) { + if (status === "*") { + this.detached = detached; + this.current = name; + } + this.all.push(name); + this.branches[name] = { + current: status === "*", + linkedWorkTree: status === "+", + name, + commit, + label + }; + } + }; + } +}); +function branchStatus(input) { + return input ? input.charAt(0) : ""; +} +function parseBranchSummary(stdOut) { + return parseStringResponse(new BranchSummaryResult(), parsers9, stdOut); +} +var parsers9; +var init_parse_branch = __esm({ + "src/lib/parsers/parse-branch.ts"() { + init_BranchSummary(); + init_utils(); + parsers9 = [ + new LineParser(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/, (result, [current, name, commit, label]) => { + result.push(branchStatus(current), true, name, commit, label); + }), + new LineParser(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s, (result, [current, name, commit, label]) => { + result.push(branchStatus(current), false, name, commit, label); + }) + ]; + } +}); +var branch_exports = {}; +__export2(branch_exports, { + branchLocalTask: () => branchLocalTask, + branchTask: () => branchTask, + containsDeleteBranchCommand: () => containsDeleteBranchCommand, + deleteBranchTask: () => deleteBranchTask, + deleteBranchesTask: () => deleteBranchesTask +}); +function containsDeleteBranchCommand(commands) { + const deleteCommands = ["-d", "-D", "--delete"]; + return commands.some((command) => deleteCommands.includes(command)); +} +function branchTask(customArgs) { + const isDelete = containsDeleteBranchCommand(customArgs); + const commands = ["branch", ...customArgs]; + if (commands.length === 1) { + commands.push("-a"); + } + if (!commands.includes("-v")) { + commands.splice(1, 0, "-v"); + } + return { + format: "utf-8", + commands, + parser(stdOut, stdErr) { + if (isDelete) { + return parseBranchDeletions(stdOut, stdErr).all[0]; + } + return parseBranchSummary(stdOut); + } + }; +} +function branchLocalTask() { + const parser3 = parseBranchSummary; + return { + format: "utf-8", + commands: ["branch", "-v"], + parser: parser3 + }; +} +function deleteBranchesTask(branches, forceDelete = false) { + return { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", ...branches], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr); + }, + onError({ exitCode, stdOut }, error, done, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + done(stdOut); + } + }; +} +function deleteBranchTask(branch, forceDelete = false) { + const task = { + format: "utf-8", + commands: ["branch", "-v", forceDelete ? "-D" : "-d", branch], + parser(stdOut, stdErr) { + return parseBranchDeletions(stdOut, stdErr).branches[branch]; + }, + onError({ exitCode, stdErr, stdOut }, error, _, fail) { + if (!hasBranchDeletionError(String(error), exitCode)) { + return fail(error); + } + throw new GitResponseError(task.parser(bufferToString(stdOut), bufferToString(stdErr)), String(error)); + } + }; + return task; +} +var init_branch = __esm({ + "src/lib/tasks/branch.ts"() { + init_git_response_error(); + init_parse_branch_delete(); + init_parse_branch(); + init_utils(); + } +}); +var parseCheckIgnore; +var init_CheckIgnore = __esm({ + "src/lib/responses/CheckIgnore.ts"() { + parseCheckIgnore = (text) => { + return text.split(/\n/g).map((line) => line.trim()).filter((file) => !!file); + }; + } +}); +var check_ignore_exports = {}; +__export2(check_ignore_exports, { + checkIgnoreTask: () => checkIgnoreTask +}); +function checkIgnoreTask(paths) { + return { + commands: ["check-ignore", ...paths], + format: "utf-8", + parser: parseCheckIgnore + }; +} +var init_check_ignore = __esm({ + "src/lib/tasks/check-ignore.ts"() { + init_CheckIgnore(); + } +}); +var clone_exports = {}; +__export2(clone_exports, { + cloneMirrorTask: () => cloneMirrorTask, + cloneTask: () => cloneTask +}); +function disallowedCommand(command) { + return /^--upload-pack(=|$)/.test(command); +} +function cloneTask(repo, directory, customArgs) { + const commands = ["clone", ...customArgs]; + filterString(repo) && commands.push(repo); + filterString(directory) && commands.push(directory); + const banned = commands.find(disallowedCommand); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return straightThroughStringTask(commands); +} +function cloneMirrorTask(repo, directory, customArgs) { + append(customArgs, "--mirror"); + return cloneTask(repo, directory, customArgs); +} +var init_clone = __esm({ + "src/lib/tasks/clone.ts"() { + init_task(); + init_utils(); + } +}); +function parseFetchResult(stdOut, stdErr) { + const result = { + raw: stdOut, + remote: null, + branches: [], + tags: [], + updated: [], + deleted: [] + }; + return parseStringResponse(result, parsers10, [stdOut, stdErr]); +} +var parsers10; +var init_parse_fetch = __esm({ + "src/lib/parsers/parse-fetch.ts"() { + init_utils(); + parsers10 = [ + new LineParser(/From (.+)$/, (result, [remote]) => { + result.remote = remote; + }), + new LineParser(/\* \[new branch]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.branches.push({ + name, + tracking + }); + }), + new LineParser(/\* \[new tag]\s+(\S+)\s*-> (.+)$/, (result, [name, tracking]) => { + result.tags.push({ + name, + tracking + }); + }), + new LineParser(/- \[deleted]\s+\S+\s*-> (.+)$/, (result, [tracking]) => { + result.deleted.push({ + tracking + }); + }), + new LineParser(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/, (result, [from, to, name, tracking]) => { + result.updated.push({ + name, + tracking, + to, + from + }); + }) + ]; + } +}); +var fetch_exports = {}; +__export2(fetch_exports, { + fetchTask: () => fetchTask +}); +function disallowedCommand2(command) { + return /^--upload-pack(=|$)/.test(command); +} +function fetchTask(remote, branch, customArgs) { + const commands = ["fetch", ...customArgs]; + if (remote && branch) { + commands.push(remote, branch); + } + const banned = commands.find(disallowedCommand2); + if (banned) { + return configurationErrorTask(`git.fetch: potential exploit argument blocked.`); + } + return { + commands, + format: "utf-8", + parser: parseFetchResult + }; +} +var init_fetch = __esm({ + "src/lib/tasks/fetch.ts"() { + init_parse_fetch(); + init_task(); + } +}); +function parseMoveResult(stdOut) { + return parseStringResponse({ moves: [] }, parsers11, stdOut); +} +var parsers11; +var init_parse_move = __esm({ + "src/lib/parsers/parse-move.ts"() { + init_utils(); + parsers11 = [ + new LineParser(/^Renaming (.+) to (.+)$/, (result, [from, to]) => { + result.moves.push({ from, to }); + }) + ]; + } +}); +var move_exports = {}; +__export2(move_exports, { + moveTask: () => moveTask +}); +function moveTask(from, to) { + return { + commands: ["mv", "-v", ...asArray(from), to], + format: "utf-8", + parser: parseMoveResult + }; +} +var init_move = __esm({ + "src/lib/tasks/move.ts"() { + init_parse_move(); + init_utils(); + } +}); +var pull_exports = {}; +__export2(pull_exports, { + pullTask: () => pullTask +}); +function pullTask(remote, branch, customArgs) { + const commands = ["pull", ...customArgs]; + if (remote && branch) { + commands.splice(1, 0, remote, branch); + } + return { + commands, + format: "utf-8", + parser(stdOut, stdErr) { + return parsePullResult(stdOut, stdErr); + }, + onError(result, _error, _done, fail) { + const pullError = parsePullErrorResult(bufferToString(result.stdOut), bufferToString(result.stdErr)); + if (pullError) { + return fail(new GitResponseError(pullError)); + } + fail(_error); + } + }; +} +var init_pull = __esm({ + "src/lib/tasks/pull.ts"() { + init_git_response_error(); + init_parse_pull(); + init_utils(); + } +}); +function parseGetRemotes(text) { + const remotes = {}; + forEach(text, ([name]) => remotes[name] = { name }); + return Object.values(remotes); +} +function parseGetRemotesVerbose(text) { + const remotes = {}; + forEach(text, ([name, url, purpose]) => { + if (!remotes.hasOwnProperty(name)) { + remotes[name] = { + name, + refs: { fetch: "", push: "" } + }; + } + if (purpose && url) { + remotes[name].refs[purpose.replace(/[^a-z]/g, "")] = url; + } + }); + return Object.values(remotes); +} +function forEach(text, handler) { + forEachLineWithContent(text, (line) => handler(line.split(/\s+/))); +} +var init_GetRemoteSummary = __esm({ + "src/lib/responses/GetRemoteSummary.ts"() { + init_utils(); + } +}); +var remote_exports = {}; +__export2(remote_exports, { + addRemoteTask: () => addRemoteTask, + getRemotesTask: () => getRemotesTask, + listRemotesTask: () => listRemotesTask, + remoteTask: () => remoteTask, + removeRemoteTask: () => removeRemoteTask +}); +function addRemoteTask(remoteName, remoteRepo, customArgs = []) { + return straightThroughStringTask(["remote", "add", ...customArgs, remoteName, remoteRepo]); +} +function getRemotesTask(verbose) { + const commands = ["remote"]; + if (verbose) { + commands.push("-v"); + } + return { + commands, + format: "utf-8", + parser: verbose ? parseGetRemotesVerbose : parseGetRemotes + }; +} +function listRemotesTask(customArgs = []) { + const commands = [...customArgs]; + if (commands[0] !== "ls-remote") { + commands.unshift("ls-remote"); + } + return straightThroughStringTask(commands); +} +function remoteTask(customArgs = []) { + const commands = [...customArgs]; + if (commands[0] !== "remote") { + commands.unshift("remote"); + } + return straightThroughStringTask(commands); +} +function removeRemoteTask(remoteName) { + return straightThroughStringTask(["remote", "remove", remoteName]); +} +var init_remote = __esm({ + "src/lib/tasks/remote.ts"() { + init_GetRemoteSummary(); + init_task(); + } +}); +var stash_list_exports = {}; +__export2(stash_list_exports, { + stashListTask: () => stashListTask +}); +function stashListTask(opt = {}, customArgs) { + const options = parseLogOptions(opt); + const commands = ["stash", "list", ...options.commands, ...customArgs]; + const parser3 = createListLogSummaryParser(options.splitter, options.fields, logFormatFromCommand(commands)); + return validateLogFormatConfig(commands) || { + commands, + format: "utf-8", + parser: parser3 + }; +} +var init_stash_list = __esm({ + "src/lib/tasks/stash-list.ts"() { + init_log_format(); + init_parse_list_log_summary(); + init_diff(); + init_log(); + } +}); +var sub_module_exports = {}; +__export2(sub_module_exports, { + addSubModuleTask: () => addSubModuleTask, + initSubModuleTask: () => initSubModuleTask, + subModuleTask: () => subModuleTask, + updateSubModuleTask: () => updateSubModuleTask +}); +function addSubModuleTask(repo, path) { + return subModuleTask(["add", repo, path]); +} +function initSubModuleTask(customArgs) { + return subModuleTask(["init", ...customArgs]); +} +function subModuleTask(customArgs) { + const commands = [...customArgs]; + if (commands[0] !== "submodule") { + commands.unshift("submodule"); + } + return straightThroughStringTask(commands); +} +function updateSubModuleTask(customArgs) { + return subModuleTask(["update", ...customArgs]); +} +var init_sub_module = __esm({ + "src/lib/tasks/sub-module.ts"() { + init_task(); + } +}); +function singleSorted(a, b) { + const aIsNum = isNaN(a); + const bIsNum = isNaN(b); + if (aIsNum !== bIsNum) { + return aIsNum ? 1 : -1; + } + return aIsNum ? sorted(a, b) : 0; +} +function sorted(a, b) { + return a === b ? 0 : a > b ? 1 : -1; +} +function trimmed(input) { + return input.trim(); +} +function toNumber(input) { + if (typeof input === "string") { + return parseInt(input.replace(/^\D+/g, ""), 10) || 0; + } + return 0; +} +var TagList; +var parseTagList; +var init_TagList = __esm({ + "src/lib/responses/TagList.ts"() { + TagList = class { + constructor(all, latest) { + this.all = all; + this.latest = latest; + } + }; + parseTagList = function(data, customSort = false) { + const tags = data.split("\n").map(trimmed).filter(Boolean); + if (!customSort) { + tags.sort(function(tagA, tagB) { + const partsA = tagA.split("."); + const partsB = tagB.split("."); + if (partsA.length === 1 || partsB.length === 1) { + return singleSorted(toNumber(partsA[0]), toNumber(partsB[0])); + } + for (let i = 0, l = Math.max(partsA.length, partsB.length); i < l; i++) { + const diff = sorted(toNumber(partsA[i]), toNumber(partsB[i])); + if (diff) { + return diff; + } + } + return 0; + }); + } + const latest = customSort ? tags[0] : [...tags].reverse().find((tag) => tag.indexOf(".") >= 0); + return new TagList(tags, latest); + }; + } +}); +var tag_exports = {}; +__export2(tag_exports, { + addAnnotatedTagTask: () => addAnnotatedTagTask, + addTagTask: () => addTagTask, + tagListTask: () => tagListTask +}); +function tagListTask(customArgs = []) { + const hasCustomSort = customArgs.some((option) => /^--sort=/.test(option)); + return { + format: "utf-8", + commands: ["tag", "-l", ...customArgs], + parser(text) { + return parseTagList(text, hasCustomSort); + } + }; +} +function addTagTask(name) { + return { + format: "utf-8", + commands: ["tag", name], + parser() { + return { name }; + } + }; +} +function addAnnotatedTagTask(name, tagMessage) { + return { + format: "utf-8", + commands: ["tag", "-a", "-m", tagMessage, name], + parser() { + return { name }; + } + }; +} +var init_tag = __esm({ + "src/lib/tasks/tag.ts"() { + init_TagList(); + } +}); +var require_git = __commonJS2({ + "src/git.js"(exports, module2) { + var { GitExecutor: GitExecutor2 } = (init_git_executor(), __toCommonJS2(git_executor_exports)); + var { SimpleGitApi: SimpleGitApi2 } = (init_simple_git_api(), __toCommonJS2(simple_git_api_exports)); + var { Scheduler: Scheduler2 } = (init_scheduler(), __toCommonJS2(scheduler_exports)); + var { configurationErrorTask: configurationErrorTask2 } = (init_task(), __toCommonJS2(task_exports)); + var { + asArray: asArray2, + filterArray: filterArray2, + filterPrimitives: filterPrimitives2, + filterString: filterString2, + filterStringOrStringArray: filterStringOrStringArray2, + filterType: filterType2, + getTrailingOptions: getTrailingOptions2, + trailingFunctionArgument: trailingFunctionArgument2, + trailingOptionsArgument: trailingOptionsArgument2 + } = (init_utils(), __toCommonJS2(utils_exports)); + var { applyPatchTask: applyPatchTask2 } = (init_apply_patch(), __toCommonJS2(apply_patch_exports)); + var { + branchTask: branchTask2, + branchLocalTask: branchLocalTask2, + deleteBranchesTask: deleteBranchesTask2, + deleteBranchTask: deleteBranchTask2 + } = (init_branch(), __toCommonJS2(branch_exports)); + var { checkIgnoreTask: checkIgnoreTask2 } = (init_check_ignore(), __toCommonJS2(check_ignore_exports)); + var { checkIsRepoTask: checkIsRepoTask2 } = (init_check_is_repo(), __toCommonJS2(check_is_repo_exports)); + var { cloneTask: cloneTask2, cloneMirrorTask: cloneMirrorTask2 } = (init_clone(), __toCommonJS2(clone_exports)); + var { cleanWithOptionsTask: cleanWithOptionsTask2, isCleanOptionsArray: isCleanOptionsArray2 } = (init_clean(), __toCommonJS2(clean_exports)); + var { diffSummaryTask: diffSummaryTask2 } = (init_diff(), __toCommonJS2(diff_exports)); + var { fetchTask: fetchTask2 } = (init_fetch(), __toCommonJS2(fetch_exports)); + var { moveTask: moveTask2 } = (init_move(), __toCommonJS2(move_exports)); + var { pullTask: pullTask2 } = (init_pull(), __toCommonJS2(pull_exports)); + var { pushTagsTask: pushTagsTask2 } = (init_push(), __toCommonJS2(push_exports)); + var { + addRemoteTask: addRemoteTask2, + getRemotesTask: getRemotesTask2, + listRemotesTask: listRemotesTask2, + remoteTask: remoteTask2, + removeRemoteTask: removeRemoteTask2 + } = (init_remote(), __toCommonJS2(remote_exports)); + var { getResetMode: getResetMode2, resetTask: resetTask2 } = (init_reset(), __toCommonJS2(reset_exports)); + var { stashListTask: stashListTask2 } = (init_stash_list(), __toCommonJS2(stash_list_exports)); + var { + addSubModuleTask: addSubModuleTask2, + initSubModuleTask: initSubModuleTask2, + subModuleTask: subModuleTask2, + updateSubModuleTask: updateSubModuleTask2 + } = (init_sub_module(), __toCommonJS2(sub_module_exports)); + var { addAnnotatedTagTask: addAnnotatedTagTask2, addTagTask: addTagTask2, tagListTask: tagListTask2 } = (init_tag(), __toCommonJS2(tag_exports)); + var { straightThroughBufferTask: straightThroughBufferTask2, straightThroughStringTask: straightThroughStringTask2 } = (init_task(), __toCommonJS2(task_exports)); + function Git2(options, plugins) { + this._executor = new GitExecutor2(options.binary, options.baseDir, new Scheduler2(options.maxConcurrentProcesses), plugins); + this._trimmed = options.trimmed; + } + (Git2.prototype = Object.create(SimpleGitApi2.prototype)).constructor = Git2; + Git2.prototype.customBinary = function(command) { + this._executor.binary = command; + return this; + }; + Git2.prototype.env = function(name, value) { + if (arguments.length === 1 && typeof name === "object") { + this._executor.env = name; + } else { + (this._executor.env = this._executor.env || {})[name] = value; + } + return this; + }; + Git2.prototype.stashList = function(options) { + return this._runTask(stashListTask2(trailingOptionsArgument2(arguments) || {}, filterArray2(options) && options || []), trailingFunctionArgument2(arguments)); + }; + function createCloneTask(api, task, repoPath, localPath) { + if (typeof repoPath !== "string") { + return configurationErrorTask2(`git.${api}() requires a string 'repoPath'`); + } + return task(repoPath, filterType2(localPath, filterString2), getTrailingOptions2(arguments)); + } + Git2.prototype.clone = function() { + return this._runTask(createCloneTask("clone", cloneTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mirror = function() { + return this._runTask(createCloneTask("mirror", cloneMirrorTask2, ...arguments), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.mv = function(from, to) { + return this._runTask(moveTask2(from, to), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkoutLatestTag = function(then) { + var git2 = this; + return this.pull(function() { + git2.tags(function(err, tags) { + git2.checkout(tags.latest, then); + }); + }); + }; + Git2.prototype.pull = function(remote, branch, options, then) { + return this._runTask(pullTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.fetch = function(remote, branch) { + return this._runTask(fetchTask2(filterType2(remote, filterString2), filterType2(branch, filterString2), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.silent = function(silence) { + console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this will be an error in version 3"); + return this; + }; + Git2.prototype.tags = function(options, then) { + return this._runTask(tagListTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rebase = function() { + return this._runTask(straightThroughStringTask2(["rebase", ...getTrailingOptions2(arguments)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.reset = function(mode) { + return this._runTask(resetTask2(getResetMode2(mode), getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revert = function(commit) { + const next = trailingFunctionArgument2(arguments); + if (typeof commit !== "string") { + return this._runTask(configurationErrorTask2("Commit must be a string"), next); + } + return this._runTask(straightThroughStringTask2(["revert", ...getTrailingOptions2(arguments, 0, true), commit]), next); + }; + Git2.prototype.addTag = function(name) { + const task = typeof name === "string" ? addTagTask2(name) : configurationErrorTask2("Git.addTag requires a tag name"); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addAnnotatedTag = function(tagName, tagMessage) { + return this._runTask(addAnnotatedTagTask2(tagName, tagMessage), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranch = function(branchName, forceDelete, then) { + return this._runTask(deleteBranchTask2(branchName, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.deleteLocalBranches = function(branchNames, forceDelete, then) { + return this._runTask(deleteBranchesTask2(branchNames, typeof forceDelete === "boolean" ? forceDelete : false), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branch = function(options, then) { + return this._runTask(branchTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.branchLocal = function(then) { + return this._runTask(branchLocalTask2(), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.raw = function(commands) { + const createRestCommands = !Array.isArray(commands); + const command = [].slice.call(createRestCommands ? arguments : commands, 0); + for (let i = 0; i < command.length && createRestCommands; i++) { + if (!filterPrimitives2(command[i])) { + command.splice(i, command.length - i); + break; + } + } + command.push(...getTrailingOptions2(arguments, 0, true)); + var next = trailingFunctionArgument2(arguments); + if (!command.length) { + return this._runTask(configurationErrorTask2("Raw: must supply one or more command to execute"), next); + } + return this._runTask(straightThroughStringTask2(command, this._trimmed), next); + }; + Git2.prototype.submoduleAdd = function(repo, path, then) { + return this._runTask(addSubModuleTask2(repo, path), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleUpdate = function(args, then) { + return this._runTask(updateSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.submoduleInit = function(args, then) { + return this._runTask(initSubModuleTask2(getTrailingOptions2(arguments, true)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.subModule = function(options, then) { + return this._runTask(subModuleTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.listRemote = function() { + return this._runTask(listRemotesTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.addRemote = function(remoteName, remoteRepo, then) { + return this._runTask(addRemoteTask2(remoteName, remoteRepo, getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.removeRemote = function(remoteName, then) { + return this._runTask(removeRemoteTask2(remoteName), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.getRemotes = function(verbose, then) { + return this._runTask(getRemotesTask2(verbose === true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.remote = function(options, then) { + return this._runTask(remoteTask2(getTrailingOptions2(arguments)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.tag = function(options, then) { + const command = getTrailingOptions2(arguments); + if (command[0] !== "tag") { + command.unshift("tag"); + } + return this._runTask(straightThroughStringTask2(command), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.updateServerInfo = function(then) { + return this._runTask(straightThroughStringTask2(["update-server-info"]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.pushTags = function(remote, then) { + const task = pushTagsTask2({ remote: filterType2(remote, filterString2) }, getTrailingOptions2(arguments)); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rm = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "-f", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.rmKeepLocal = function(files) { + return this._runTask(straightThroughStringTask2(["rm", "--cached", ...asArray2(files)]), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.catFile = function(options, then) { + return this._catFile("utf-8", arguments); + }; + Git2.prototype.binaryCatFile = function() { + return this._catFile("buffer", arguments); + }; + Git2.prototype._catFile = function(format, args) { + var handler = trailingFunctionArgument2(args); + var command = ["cat-file"]; + var options = args[0]; + if (typeof options === "string") { + return this._runTask(configurationErrorTask2("Git.catFile: options must be supplied as an array of strings"), handler); + } + if (Array.isArray(options)) { + command.push.apply(command, options); + } + const task = format === "buffer" ? straightThroughBufferTask2(command) : straightThroughStringTask2(command); + return this._runTask(task, handler); + }; + Git2.prototype.diff = function(options, then) { + const task = filterString2(options) ? configurationErrorTask2("git.diff: supplying options as a single string is no longer supported, switch to an array of strings") : straightThroughStringTask2(["diff", ...getTrailingOptions2(arguments)]); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.diffSummary = function() { + return this._runTask(diffSummaryTask2(getTrailingOptions2(arguments, 1)), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.applyPatch = function(patches) { + const task = !filterStringOrStringArray2(patches) ? configurationErrorTask2(`git.applyPatch requires one or more string patches as the first argument`) : applyPatchTask2(asArray2(patches), getTrailingOptions2([].slice.call(arguments, 1))); + return this._runTask(task, trailingFunctionArgument2(arguments)); + }; + Git2.prototype.revparse = function() { + const commands = ["rev-parse", ...getTrailingOptions2(arguments, true)]; + return this._runTask(straightThroughStringTask2(commands, true), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.clean = function(mode, options, then) { + const usingCleanOptionsArray = isCleanOptionsArray2(mode); + const cleanMode = usingCleanOptionsArray && mode.join("") || filterType2(mode, filterString2) || ""; + const customArgs = getTrailingOptions2([].slice.call(arguments, usingCleanOptionsArray ? 1 : 0)); + return this._runTask(cleanWithOptionsTask2(cleanMode, customArgs), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.exec = function(then) { + const task = { + commands: [], + format: "utf-8", + parser() { + if (typeof then === "function") { + then(); + } + } + }; + return this._runTask(task); + }; + Git2.prototype.clearQueue = function() { + return this; + }; + Git2.prototype.checkIgnore = function(pathnames, then) { + return this._runTask(checkIgnoreTask2(asArray2(filterType2(pathnames, filterStringOrStringArray2, []))), trailingFunctionArgument2(arguments)); + }; + Git2.prototype.checkIsRepo = function(checkType, then) { + return this._runTask(checkIsRepoTask2(filterType2(checkType, filterString2)), trailingFunctionArgument2(arguments)); + }; + module2.exports = Git2; + } +}); +init_pathspec(); +init_git_error(); +var GitConstructError = class extends GitError { + constructor(config, message) { + super(void 0, message); + this.config = config; + } +}; +init_git_error(); +init_git_error(); +var GitPluginError = class extends GitError { + constructor(task, plugin, message) { + super(task, message); + this.task = task; + this.plugin = plugin; + Object.setPrototypeOf(this, new.target.prototype); + } +}; +init_git_response_error(); +init_task_configuration_error(); +init_check_is_repo(); +init_clean(); +init_config(); +init_diff_name_status(); +init_grep(); +init_reset(); +function abortPlugin(signal) { + if (!signal) { + return; + } + const onSpawnAfter = { + type: "spawn.after", + action(_data, context) { + function kill() { + context.kill(new GitPluginError(void 0, "abort", "Abort signal received")); + } + signal.addEventListener("abort", kill); + context.spawned.on("close", () => signal.removeEventListener("abort", kill)); + } + }; + const onSpawnBefore = { + type: "spawn.before", + action(_data, context) { + if (signal.aborted) { + context.kill(new GitPluginError(void 0, "abort", "Abort already signaled")); + } + } + }; + return [onSpawnBefore, onSpawnAfter]; +} +function isConfigSwitch(arg) { + return typeof arg === "string" && arg.trim().toLowerCase() === "-c"; +} +function preventProtocolOverride(arg, next) { + if (!isConfigSwitch(arg)) { + return; + } + if (!/^\s*protocol(.[a-z]+)?.allow/.test(next)) { + return; + } + throw new GitPluginError(void 0, "unsafe", "Configuring protocol.allow is not permitted without enabling allowUnsafeExtProtocol"); +} +function preventUploadPack(arg, method) { + if (/^\s*--(upload|receive)-pack/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of --upload-pack or --receive-pack is not permitted without enabling allowUnsafePack`); + } + if (method === "clone" && /^\s*-u\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of clone with option -u is not permitted without enabling allowUnsafePack`); + } + if (method === "push" && /^\s*--exec\b/.test(arg)) { + throw new GitPluginError(void 0, "unsafe", `Use of push with option --exec is not permitted without enabling allowUnsafePack`); + } +} +function blockUnsafeOperationsPlugin({ + allowUnsafeProtocolOverride = false, + allowUnsafePack = false +} = {}) { + return { + type: "spawn.args", + action(args, context) { + args.forEach((current, index) => { + const next = index < args.length ? args[index + 1] : ""; + allowUnsafeProtocolOverride || preventProtocolOverride(current, next); + allowUnsafePack || preventUploadPack(current, context.method); + }); + return args; + } + }; +} +init_utils(); +function commandConfigPrefixingPlugin(configuration) { + const prefix = prefixedArray(configuration, "-c"); + return { + type: "spawn.args", + action(data) { + return [...prefix, ...data]; + } + }; +} +init_utils(); +var never = (0, import_promise_deferred2.deferred)().promise; +function completionDetectionPlugin({ + onClose = true, + onExit = 50 +} = {}) { + function createEvents() { + let exitCode = -1; + const events = { + close: (0, import_promise_deferred2.deferred)(), + closeTimeout: (0, import_promise_deferred2.deferred)(), + exit: (0, import_promise_deferred2.deferred)(), + exitTimeout: (0, import_promise_deferred2.deferred)() + }; + const result = Promise.race([ + onClose === false ? never : events.closeTimeout.promise, + onExit === false ? never : events.exitTimeout.promise + ]); + configureTimeout(onClose, events.close, events.closeTimeout); + configureTimeout(onExit, events.exit, events.exitTimeout); + return { + close(code) { + exitCode = code; + events.close.done(); + }, + exit(code) { + exitCode = code; + events.exit.done(); + }, + get exitCode() { + return exitCode; + }, + result + }; + } + function configureTimeout(flag, event, timeout) { + if (flag === false) { + return; + } + (flag === true ? event.promise : event.promise.then(() => delay(flag))).then(timeout.done); + } + return { + type: "spawn.after", + action(_0, _1) { + return __async(this, arguments, function* (_data, { spawned, close }) { + var _a2, _b; + const events = createEvents(); + let deferClose = true; + let quickClose = () => void (deferClose = false); + (_a2 = spawned.stdout) == null ? void 0 : _a2.on("data", quickClose); + (_b = spawned.stderr) == null ? void 0 : _b.on("data", quickClose); + spawned.on("error", quickClose); + spawned.on("close", (code) => events.close(code)); + spawned.on("exit", (code) => events.exit(code)); + try { + yield events.result; + if (deferClose) { + yield delay(50); + } + close(events.exitCode); + } catch (err) { + close(events.exitCode, err); + } + }); + } + }; +} +init_git_error(); +function isTaskError(result) { + return !!(result.exitCode && result.stdErr.length); +} +function getErrorMessage(result) { + return Buffer.concat([...result.stdOut, ...result.stdErr]); +} +function errorDetectionHandler(overwrite = false, isError = isTaskError, errorMessage = getErrorMessage) { + return (error, result) => { + if (!overwrite && error || !isError(result)) { + return error; + } + return errorMessage(result); + }; +} +function errorDetectionPlugin(config) { + return { + type: "task.error", + action(data, context) { + const error = config(data.error, { + stdErr: context.stdErr, + stdOut: context.stdOut, + exitCode: context.exitCode + }); + if (Buffer.isBuffer(error)) { + return { error: new GitError(void 0, error.toString("utf-8")) }; + } + return { + error + }; + } + }; +} +init_utils(); +var PluginStore = class { + constructor() { + this.plugins = /* @__PURE__ */ new Set(); + } + add(plugin) { + const plugins = []; + asArray(plugin).forEach((plugin2) => plugin2 && this.plugins.add(append(plugins, plugin2))); + return () => { + plugins.forEach((plugin2) => this.plugins.delete(plugin2)); + }; + } + exec(type, data, context) { + let output = data; + const contextual = Object.freeze(Object.create(context)); + for (const plugin of this.plugins) { + if (plugin.type === type) { + output = plugin.action(output, contextual); + } + } + return output; + } +}; +init_utils(); +function progressMonitorPlugin(progress) { + const progressCommand = "--progress"; + const progressMethods = ["checkout", "clone", "fetch", "pull", "push"]; + const onProgress = { + type: "spawn.after", + action(_data, context) { + var _a2; + if (!context.commands.includes(progressCommand)) { + return; + } + (_a2 = context.spawned.stderr) == null ? void 0 : _a2.on("data", (chunk) => { + const message = /^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(chunk.toString("utf8")); + if (!message) { + return; + } + progress({ + method: context.method, + stage: progressEventStage(message[1]), + progress: asNumber(message[2]), + processed: asNumber(message[3]), + total: asNumber(message[4]) + }); + }); + } + }; + const onArgs = { + type: "spawn.args", + action(args, context) { + if (!progressMethods.includes(context.method)) { + return args; + } + return including(args, progressCommand); + } + }; + return [onArgs, onProgress]; +} +function progressEventStage(input) { + return String(input.toLowerCase().split(" ", 1)) || "unknown"; +} +init_utils(); +function spawnOptionsPlugin(spawnOptions) { + const options = pick(spawnOptions, ["uid", "gid"]); + return { + type: "spawn.options", + action(data) { + return __spreadValues(__spreadValues({}, options), data); + } + }; +} +function timeoutPlugin({ + block, + stdErr = true, + stdOut = true +}) { + if (block > 0) { + return { + type: "spawn.after", + action(_data, context) { + var _a2, _b; + let timeout; + function wait() { + timeout && clearTimeout(timeout); + timeout = setTimeout(kill, block); + } + function stop() { + var _a3, _b2; + (_a3 = context.spawned.stdout) == null ? void 0 : _a3.off("data", wait); + (_b2 = context.spawned.stderr) == null ? void 0 : _b2.off("data", wait); + context.spawned.off("exit", stop); + context.spawned.off("close", stop); + timeout && clearTimeout(timeout); + } + function kill() { + stop(); + context.kill(new GitPluginError(void 0, "timeout", `block timeout reached`)); + } + stdOut && ((_a2 = context.spawned.stdout) == null ? void 0 : _a2.on("data", wait)); + stdErr && ((_b = context.spawned.stderr) == null ? void 0 : _b.on("data", wait)); + context.spawned.on("exit", stop); + context.spawned.on("close", stop); + wait(); + } + }; + } +} +init_pathspec(); +function suffixPathsPlugin() { + return { + type: "spawn.args", + action(data) { + const prefix = []; + let suffix; + function append2(args) { + (suffix = suffix || []).push(...args); + } + for (let i = 0; i < data.length; i++) { + const param = data[i]; + if (isPathSpec(param)) { + append2(toPaths(param)); + continue; + } + if (param === "--") { + append2(data.slice(i + 1).flatMap((item) => isPathSpec(item) && toPaths(item) || item)); + break; + } + prefix.push(param); + } + return !suffix ? prefix : [...prefix, "--", ...suffix.map(String)]; + } + }; +} +init_utils(); +var Git = require_git(); +function gitInstanceFactory(baseDir, options) { + const plugins = new PluginStore(); + const config = createInstanceConfig(baseDir && (typeof baseDir === "string" ? { baseDir } : baseDir) || {}, options); + if (!folderExists(config.baseDir)) { + throw new GitConstructError(config, `Cannot use simple-git on a directory that does not exist`); + } + if (Array.isArray(config.config)) { + plugins.add(commandConfigPrefixingPlugin(config.config)); + } + plugins.add(blockUnsafeOperationsPlugin(config.unsafe)); + plugins.add(suffixPathsPlugin()); + plugins.add(completionDetectionPlugin(config.completion)); + config.abort && plugins.add(abortPlugin(config.abort)); + config.progress && plugins.add(progressMonitorPlugin(config.progress)); + config.timeout && plugins.add(timeoutPlugin(config.timeout)); + config.spawnOptions && plugins.add(spawnOptionsPlugin(config.spawnOptions)); + plugins.add(errorDetectionPlugin(errorDetectionHandler(true))); + config.errors && plugins.add(errorDetectionPlugin(config.errors)); + return new Git(config, plugins); +} +init_git_response_error(); +var simpleGit = gitInstanceFactory; + +// node_modules/set-interval-async/dist/dynamic/set-interval-async.mjs +var import_clear_interval_async = __toESM(require_clear_interval_async(), 1); +var import_set_interval_async = __toESM(require_set_interval_async(), 1); + +// main.ts +var simpleGitOptions; +var git; +var DEFAULT_SETTINGS = { + remoteURL: "", + gitLocation: "", + syncinterval: 0, + isSyncOnLoad: false, + checkStatusOnLoad: true +}; +var GHSyncPlugin = class extends import_obsidian.Plugin { + async SyncNotes() { + new import_obsidian.Notice("Syncing to GitHub remote"); + const remote = this.settings.remoteURL.trim(); + simpleGitOptions = { + //@ts-ignore + baseDir: this.app.vault.adapter.getBasePath(), + binary: this.settings.gitLocation + "git", + maxConcurrentProcesses: 6, + trimmed: false + }; + git = simpleGit(simpleGitOptions); + let os = require("os"); + let hostname = os.hostname(); + let statusResult = await git.status().catch((e) => { + new import_obsidian.Notice("Vault is not a Git repo or git binary cannot be found.", 1e4); + return; + }); + let clean = statusResult.isClean(); + let date = new Date(); + let msg = hostname + " " + date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + ":" + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds(); + if (!clean) { + try { + await git.add("./*").commit(msg); + } catch (e) { + new import_obsidian.Notice(e); + return; + } + } else { + new import_obsidian.Notice("Working branch clean"); + } + try { + await git.removeRemote("origin").catch((e) => { + new import_obsidian.Notice(e); + }); + await git.addRemote("origin", remote).catch((e) => { + new import_obsidian.Notice(e); + }); + } catch (e) { + new import_obsidian.Notice(e); + return; + } + try { + await git.fetch(); + } catch (e) { + new import_obsidian.Notice(e + "\nGitHub Sync: Invalid remote URL.", 1e4); + return; + } + new import_obsidian.Notice("GitHub Sync: Successfully set remote origin url"); + try { + await git.pull("origin", "main", { "--no-rebase": null }, (err, update) => { + if (update) { + new import_obsidian.Notice("GitHub Sync: Pulled " + update.summary.changes + " changes"); + } + }); + } catch (e) { + let conflictStatus = await git.status().catch((e2) => { + new import_obsidian.Notice(e2, 1e4); + return; + }); + let conflictMsg = "Merge conflicts in:"; + for (let c of conflictStatus.conflicted) { + conflictMsg += "\n " + c; + } + conflictMsg += "\nResolve them or click sync button again to push with unresolved conflicts."; + new import_obsidian.Notice(conflictMsg); + for (let c of conflictStatus.conflicted) { + this.app.workspace.openLinkText("", c, true); + } + return; + } + if (!clean) { + try { + git.push("origin", "main", ["-u"]); + new import_obsidian.Notice("GitHub Sync: Pushed on " + msg); + } catch (e) { + new import_obsidian.Notice(e, 1e4); + } + } + } + async CheckStatusOnStart() { + try { + simpleGitOptions = { + //@ts-ignore + baseDir: this.app.vault.adapter.getBasePath(), + binary: this.settings.gitLocation + "git", + maxConcurrentProcesses: 6, + trimmed: false + }; + git = simpleGit(simpleGitOptions); + await git.branch({ "--set-upstream-to": "origin/main" }); + let statusUponOpening = await git.fetch().status(); + if (statusUponOpening.behind > 0) { + if (this.settings.isSyncOnLoad == true) { + this.SyncNotes(); + } else { + new import_obsidian.Notice("GitHub Sync: " + statusUponOpening.behind + " commits behind remote.\nClick the GitHub ribbon icon to sync."); + } + } else { + new import_obsidian.Notice("GitHub Sync: up to date with remote."); + } + } catch (e) { + } + } + async onload() { + await this.loadSettings(); + const ribbonIconEl = this.addRibbonIcon("github", "Sync with Remote", (evt) => { + this.SyncNotes(); + }); + ribbonIconEl.addClass("gh-sync-ribbon"); + this.addCommand({ + id: "github-sync-command", + name: "Sync with Remote", + callback: () => { + this.SyncNotes(); + } + }); + this.addSettingTab(new GHSyncSettingTab(this.app, this)); + if (!isNaN(this.settings.syncinterval)) { + let interval = this.settings.syncinterval; + if (interval >= 1) { + try { + (0, import_set_interval_async.setIntervalAsync)(async () => { + await this.SyncNotes(); + }, interval * 60 * 1e3); + new import_obsidian.Notice("Auto sync enabled"); + } catch (e) { + } + } + } + if (this.settings.checkStatusOnLoad) { + this.CheckStatusOnStart(); + } + } + onunload() { + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + async saveSettings() { + await this.saveData(this.settings); + } +}; +var GHSyncSettingTab = class extends import_obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + const howto = containerEl.createEl("div", { cls: "howto" }); + howto.createEl("div", { text: "How to use this plugin", cls: "howto_title" }); + howto.createEl("small", { text: "Grab your GitHub repository's HTTPS or SSH url and paste it into the settings here. If you're not authenticated, the first sync with this plugin should prompt you to authenticate. If you've already setup SSH on your device with GitHub, you won't need to authenticate - just paste your repo's SSH url into the settings here.", cls: "howto_text" }); + howto.createEl("br"); + const linkEl = howto.createEl("p"); + linkEl.createEl("span", { text: "See the " }); + linkEl.createEl("a", { href: "https://github.com/kevinmkchin/Obsidian-GitHub-Sync/blob/main/README.md", text: "README" }); + linkEl.createEl("span", { text: " for more information and troubleshooting." }); + new import_obsidian.Setting(containerEl).setName("Remote URL").setDesc("").addText((text) => text.setPlaceholder("").setValue(this.plugin.settings.remoteURL).onChange(async (value) => { + this.plugin.settings.remoteURL = value; + await this.plugin.saveSettings(); + }).inputEl.addClass("my-plugin-setting-text")); + new import_obsidian.Setting(containerEl).setName("git binary location").setDesc("This is optional! Set this only if git is not findable via your system PATH, then provide its location here. See README for more info.").addText((text) => text.setPlaceholder("").setValue(this.plugin.settings.gitLocation).onChange(async (value) => { + this.plugin.settings.gitLocation = value; + await this.plugin.saveSettings(); + }).inputEl.addClass("my-plugin-setting-text2")); + new import_obsidian.Setting(containerEl).setName("Check status on startup").setDesc("Check to see if you are behind remote when you start Obsidian.").addToggle((toggle) => toggle.setValue(this.plugin.settings.checkStatusOnLoad).onChange(async (value) => { + this.plugin.settings.checkStatusOnLoad = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Auto sync on startup").setDesc("Automatically sync with remote when you start Obsidian if there are unsynced changes.").addToggle((toggle) => toggle.setValue(this.plugin.settings.isSyncOnLoad).onChange(async (value) => { + this.plugin.settings.isSyncOnLoad = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Auto sync at interval").setDesc("Set minute interval after which your vault is synced automatically. Auto sync is disabled if this field is left empty or not a positive integer. Restart Obsidan to take effect.").addText((text) => text.setValue(String(this.plugin.settings.syncinterval)).onChange(async (value) => { + this.plugin.settings.syncinterval = Number(value); + await this.plugin.saveSettings(); + })); + } +}; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/github-sync/manifest.json b/.obsidian/plugins/github-sync/manifest.json new file mode 100644 index 00000000..6857a22d --- /dev/null +++ b/.obsidian/plugins/github-sync/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "github-sync", + "name": "GitHub Sync", + "version": "1.0.6", + "minAppVersion": "0.15.0", + "description": "Sync vault to personal GitHub.", + "author": "Kevin Chin", + "authorUrl": "https://kevin.gd/", + "isDesktopOnly": true +} \ No newline at end of file diff --git a/.obsidian/plugins/github-sync/styles.css b/.obsidian/plugins/github-sync/styles.css new file mode 100644 index 00000000..cdfa1738 --- /dev/null +++ b/.obsidian/plugins/github-sync/styles.css @@ -0,0 +1,42 @@ +/* + +This CSS file will be included with your plugin, and +available in the app when your plugin is enabled. + +If your plugin does not need CSS, delete this file. + +*/ + + +.gh-sync-ribbon +{ + order: 100; +} + +.gh-sync-status +{ + order: -1; +} + +.howto { + border: 1px solid var(--background-modifier-border); + padding: 10px; +} + +.howto_title { + font-weight: 600; +} + +.howto_text { + color: var(--text-muted); + font-size: smaller; +} + +.my-plugin-setting-text { + width: 30em; +} + +.my-plugin-setting-text2 { + width: 30em; +} + diff --git a/.obsidian/plugins/link-favicon/manifest.json b/.obsidian/plugins/link-favicon/manifest.json deleted file mode 100644 index 55a52137..00000000 --- a/.obsidian/plugins/link-favicon/manifest.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "link-favicon", - "name": "Link Favicons", - "version": "1.8.4", - "minAppVersion": "1.3.0", - "description": "See the favicon for a linked website. ", - "author": "Johannes Theiner", - "authorUrl": "https://github.com/joethei", - "isDesktopOnly": false -} diff --git a/.obsidian/plugins/obsidian-livesync/main.js b/.obsidian/plugins/obsidian-livesync/main.js new file mode 100644 index 00000000..8b3ee7ca --- /dev/null +++ b/.obsidian/plugins/obsidian-livesync/main.js @@ -0,0 +1,12 @@ +/* +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,key2){_logger(message,level,key2)}function info(message,flagsOrKey,key2){(function __logger(message,baseLevel,flagsOrKey,key2){let level=baseLevel;"string"==typeof flagsOrKey?key2=flagsOrKey:void 0!==flagsOrKey&&(level|=flagsOrKey);_logger(message,level,key2)})(message,LEVEL_INFO,flagsOrKey,key2)}function statusDisplay(status){return status?"EXPERIMENTAL"==status?" (Experimental)":"ALPHA"==status?" (Alpha)":"BETA"==status?" (Beta)":` (${status})`:""}function confName(key2,alt=""){var _a8,_b4;return key2 in configurationNames?`${null==(_a8=configurationNames[key2])?void 0:_a8.name}${statusDisplay(null==(_b4=configurationNames[key2])?void 0:_b4.status)}`:`${alt||""}`}function numeric(str){return isNaN(str)?str.charCodeAt(0):parseInt(str,10)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(str){if(!str)return[""];const parts=[],m3=balanced("{","}",str);if(!m3)return str.split(",");const{pre,body,post}=m3,p4=pre.split(",");p4[p4.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){p4[p4.length-1]+=postParts.shift();p4.push.apply(p4,postParts)}parts.push.apply(parts,p4);return parts}function expand(str){if(!str)return[];"{}"===str.slice(0,2)&&(str="\\{\\}"+str.slice(2));return expand_(function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}(str),!0).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el){return/^-?0\d/.test(el)}function lte(i2,y2){return i2<=y2}function gte(i2,y2){return i2>=y2}function expand_(str,isTop){const expansions=[],m3=balanced("{","}",str);if(!m3)return[str];const pre=m3.pre,post=m3.post.length?expand_(m3.post,!1):[""];if(/\$$/.test(m3.pre))for(let k2=0;k2=0;if(!isSequence&&!isOptions)return m3.post.match(/,(?!,).*\}/)?expand_(str=m3.pre+"{"+m3.body+escClose+m3.post):[str];let n3,N2;if(isSequence)n3=m3.body.split(/\.\./);else{n3=parseCommaParts(m3.body);if(1===n3.length&&void 0!==n3[0]){n3=expand_(n3[0],!1).map(embrace);if(1===n3.length)return post.map((p4=>m3.pre+n3[0]+p4))}}if(isSequence&&void 0!==n3[0]&&void 0!==n3[1]){const x2=numeric(n3[0]),y2=numeric(n3[1]),width=Math.max(n3[0].length,n3[1].length);let incr=3===n3.length&&void 0!==n3[2]?Math.abs(numeric(n3[2])):1,test=lte;if(y20){const z2=new Array(need+1).join("0");c3=i2<0?"-"+z2+c3.slice(1):z2+c3}}}N2.push(c3)}}else{N2=[];for(let j2=0;j2base64ToArrayBufferInternalBrowser(e3))),len=bufItems.reduce(((p4,c3)=>p4+c3.byteLength),0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach((e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength}));return joinedArray.buffer}function 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 _a8,_b4;const dataURI=(null==(_b4=null==(_a8=evt.target)?void 0:_a8.result)?void 0:_b4.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)}))}async function arrayBufferToBase64Single(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return buf.byteLength128)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 base64ToString(base64){try{if("string"!=typeof base64)return base64.map((e3=>base64ToString(e3))).join("");const binary_string=atob(base64),len=binary_string.length,bytes=new Uint8Array(len);for(let i2=0;i2=38&&char<=126&&58!=char?char:revTable[char]}return out.buffer}function hexStringToUint8Array(src){const len=src.length/2,ret=new Uint8Array(len);for(let i2=0;i2numMap[e3])).join("")}function concatUInt8Array(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 function decodeToArrayBuffer(src){if(1==src.length)return _decodeToArrayBuffer(src[0]);const bufItems=src.map((e3=>_decodeToArrayBuffer(e3))),len=bufItems.reduce(((p4,c3)=>p4+c3.byteLength),0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach((e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength}));return joinedArray.buffer}([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 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 stripAllPrefixes(prefixedPath){if(function isFilePath(path2){return-1===path2.indexOf(":")}(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 hashString(key2){return _hashString(key2)}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]=function expandDocumentIDPrefix(id){let[prefix,body]=id.split(":",2);if(body)prefix+=":";else{body=prefix;prefix=""}return[prefix,body]}(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 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 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 isSomeResolved(promises){return 0!=promises.length&&await Promise.race([...promises,Promise.resolve(UNRESOLVED)])!==UNRESOLVED}function fireAndForget(p4){if("function"==typeof p4)return fireAndForget(p4());p4.then(noop).catch(noop)}function yieldMicrotask(){return new Promise((res2=>queueMicrotask(res2)))}function cancelableDelay(timeout,cancel2=TIMED_OUT_SIGNAL){let timer;const promise=promiseWithResolver();timer=setTimeout((()=>{timer=void 0;promise.resolve(cancel2)}),timeout);return{promise:promise.promise,cancel(){if(timer){clearTimeout(timer);timer=void 0}}}}function Semaphore(limit){let counter=0;const _limit=limit,queue2=[];return{get waiting(){return queue2.length},async tryAcquire(quantity=1,timeout){if(counter<_limit){counter+=quantity;return()=>{this.release(quantity)}}const d4=cancelableDelay(timeout,TIMED_OUT_SIGNAL),aq2=this.acquire(quantity),p4=await Promise.race([d4.promise,aq2]);if(p4===TIMED_OUT_SIGNAL){fireAndForget((()=>aq2.then((release=>release()))));return!1}return p4},async acquire(quantity=1){if(counter<_limit){counter+=quantity;return()=>this.release()}const n3=promiseWithResolver();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 resetV3Buf(){_nonceV3[0]=0;const _wk=webcrypto2.getRandomValues(new Uint8Array(12));bufV3.set(_wk);bufV3.set(_nonceV3,8)}async function generateKey(passphrase){const passphraseBin=(new TextEncoder).encode(passphrase),salt=(await webcrypto2.subtle.digest("SHA-256",new Uint8Array([...passphraseBin,...SALT]))).slice(0,16),baseKey=await webcrypto2.subtle.importKey("raw",passphraseBin,"PBKDF2",!1,["deriveBits","deriveKey"]),pbkdf2Params={name:"PBKDF2",hash:"SHA-256",salt,iterations:1e5};return await webcrypto2.subtle.deriveKey(pbkdf2Params,baseKey,{name:"AES-GCM",length:256},!1,["decrypt","encrypt"])}async function getKeyForEncrypt(passphrase,autoCalculateIterations){const buffKey=`${passphrase}-${autoCalculateIterations}`,f4=KeyBuffs.get(buffKey);if(f4){f4.count--;if(f4.count>0)return[f4.key,f4.salt];f4.count--}const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto3.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto3.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),salt=webcrypto3.getRandomValues(new Uint8Array(16)),key2=await webcrypto3.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]);KeyBuffs.set(buffKey,{key:key2,salt,count:KEY_RECYCLE_COUNT});return[key2,salt]}async function getKeyForDecryption(passphrase,salt,autoCalculateIterations){if(--keyGCCount<0){keyGCCount=KEY_RECYCLE_COUNT;const threshold=(decKeyIdx-decKeyMin)/2;for(const[key3,buff]of decKeyBuffs){buff.count0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto3.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto3.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),key2=await webcrypto3.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["decrypt"]);decKeyBuffs.set(bufKey,{key:key2,salt,count:0});return[key2,salt]}function getSemiStaticField(reset2){return null==semiStaticFieldBuffer||reset2?semiStaticFieldBuffer=webcrypto3.getRandomValues(new Uint8Array(12)):semiStaticFieldBuffer}function getNonce(){nonceBuffer[0]++;nonceBuffer[0]>1e4&&getSemiStaticField(!0);return nonceBuffer}async function encrypt(input,passphrase,autoCalculateIterations){const[key2,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto3.subtle.encrypt({name:"AES-GCM",iv},key2,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`}function isPathProbablyObfuscated(path2){return path2.startsWith("%")&&path2.length>64}async function decrypt(encryptedResult,passphrase,autoCalculateIterations){try{if("%"==encryptedResult[0])return"~"===encryptedResult[1]?async function decryptV3(encryptedResult,passphrase){if(previousDecryptionPassphrase!==passphrase){const key2=await generateKey(passphrase);decryptionKey=key2;previousDecryptionPassphrase=passphrase}const ivStr=encryptedResult.substring(2,26),encryptedData=encryptedResult.substring(26),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=base64ToArrayBuffer(encryptedData),dataBuffer=await webcrypto2.subtle.decrypt({name:"AES-GCM",iv},decryptionKey,encryptedDataArrayBuffer);return readString(new Uint8Array(dataBuffer))}(encryptedResult,passphrase):async function decryptV2(encryptedResult,passphrase,autoCalculateIterations){try{const ivStr=encryptedResult.substring(1,33),salt=encryptedResult.substring(33,65),encryptedData=encryptedResult.substring(65),[key2]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=decodeBinary(encryptedData),dataBuffer=await webcrypto3.subtle.decrypt({name:"AES-GCM",iv},key2,encryptedDataArrayBuffer);return readString(new Uint8Array(dataBuffer))}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}(encryptedResult,passphrase,autoCalculateIterations);if(!encryptedResult.startsWith("[")||!encryptedResult.endsWith("]"))throw new Error("Encrypted data corrupted!");const w2=encryptedResult.substring(1,encryptedResult.length-1).split(",").map((e3=>'"'==e3[0]?e3.substring(1,e3.length-1):e3)),[encryptedData,ivString,salt]=w2,[key2]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivString),encryptedDataBin=atob(encryptedData),len=encryptedDataBin.length,encryptedDataArrayBuffer=new Uint8Array(len);for(let i2=len;i2>=0;--i2)encryptedDataArrayBuffer[i2]=encryptedDataBin.charCodeAt(i2);const plainStringBuffer=await webcrypto3.subtle.decrypt({name:"AES-GCM",iv},key2,encryptedDataArrayBuffer),plainStringified=readString(new Uint8Array(plainStringBuffer));return JSON.parse(plainStringified)}catch(ex){Logger("Couldn't decode! You should wrong the passphrases",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function testCrypt(){const src="✨supercalifragilisticexpialidocious✨⛰️",encoded=await encrypt(src,"passwordTest",!1);if(src!=await decrypt(encoded,"passwordTest",!1)){Logger("WARNING! Your device would not support encryption.",LOG_LEVEL_VERBOSE);return!1}{Logger("CRYPT LOGIC OK",LOG_LEVEL_VERBOSE);const w2=(new TextEncoder).encode(src),encodedBinary=await encryptBinary(w2,"passwordTest",!1),decryptedBinary=await decryptBinary(encodedBinary,"passwordTest",!1);if(w2.join("-")!==decryptedBinary.join("-")){Logger("WARNING! Your device would not support encryption (Binary).",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC OK (Binary)",LOG_LEVEL_VERBOSE);return await async function testCryptV3(){const src="✨supercalifragilisticexpialidocious✨⛰️",encoded=await async function encryptV3(input,passphrase){if(previousPassphrase!==passphrase){resetV3Buf();const key2=await generateKey(passphrase);encryptionKey=key2;previousPassphrase=passphrase}const iv=function incIV(){_nonceV3[0]++;bufV3.set(_nonceV3,8);_nonceV3[0]>1500&&resetV3Buf();return bufV3}(),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto2.subtle.encrypt({name:"AES-GCM",iv},encryptionKey,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%~${uint8ArrayToHexString(iv)}${encryptedData2}`}(src,"passwordTest");if(src!=await decrypt(encoded,"passwordTest",!1)){Logger("WARNING! Your device would not support encryption V3.",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC (V3) OK",LOG_LEVEL_VERBOSE);return!0}()}}async function encryptBinary(input,passphrase,autoCalculateIterations){const[key2,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=input,encryptedDataArrayBuffer=new Uint8Array(await webcrypto3.subtle.encrypt({name:"AES-GCM",iv},key2,dataBuf)),ret=new Uint8Array(encryptedDataArrayBuffer.byteLength+iv.byteLength+salt.byteLength);ret.set(iv,0);ret.set(salt,iv.byteLength);ret.set(encryptedDataArrayBuffer,iv.byteLength+salt.byteLength);return ret}async function decryptBinary(encryptedResult,passphrase,autoCalculateIterations){try{const iv=encryptedResult.slice(0,16),salt=encryptedResult.slice(16,32),encryptedData=encryptedResult.slice(32),[key2]=await getKeyForDecryption(passphrase,salt,autoCalculateIterations),dataBuffer=await webcrypto3.subtle.decrypt({name:"AES-GCM",iv},key2,encryptedData);return new Uint8Array(dataBuffer)}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2 Bin)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}function handleTaskSplit(process2,data){const key2=data.key,task=process2.task;if("result"in data)if(null===data.result){task.resolve(null);tasks.delete(key2)}else{task.resolve(data.result);process2.task=promiseWithResolver()}else{data.error?task.reject(data.error):task.reject(new Error("Unknown error in background splitting"));tasks.delete(key2)}}function handleTaskEncrypt(process2,data){const key2=data.key,task=process2.task;"result"in data?task.resolve(data.result):data.error?task.reject(data.error):task.reject(new Error("Unknown error in background encryption"));tasks.delete(key2)}function splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,1,null!=useSegmenter&&useSegmenter)}function splitPieces2WorkerV2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,2,null!=useSegmenter&&useSegmenter)}function startWorker(data){const _key=key++,inst=function nextWorker(){const inst=workers[roundRobinIdx];roundRobinIdx=(roundRobinIdx+1)%workers.length;return inst}(),item={key:_key,task:promiseWithResolver(),type:data.type,finalize:()=>{inst.processing--}};tasks.set(_key,item);inst.processing++;inst.worker.postMessage({data:{...data,key:_key}});return item}function encryptionOnWorker(data){const process2=startWorker(data);return(async()=>{const ret=await process2.task.promise;process2.finalize();return ret})()}function _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,splitVersion,useSegmenter){const process2=startWorker({type:"split",dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter,splitVersion}),_key=process2.key;return async function*(){for(;tasks.has(_key);){const{task}=tasks.get(_key),result=await task.promise;if(null===result){process2.finalize();return}yield result}}}function serialized(key2,proc){var _a8;const prev=serializedMap.get(key2),p4=promiseWithResolver();queueCount.set(key2,(null!=(_a8=queueCount.get(key2))?_a8:0)+1);const nextTask=async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{const count=queueCount.get(key2)-1;if(0===count){serializedMap.delete(key2);queueCount.delete(key2)}else queueCount.set(key2,count)}};if(prev){const newP=prev.then((()=>nextTask()));serializedMap.set(key2,newP)}else serializedMap.set(key2,nextTask());return p4.promise}function shareRunningResult(key2,proc){const prev=shareSerializedMap.get(key2);if(prev)return prev;const p4=promiseWithResolver();shareSerializedMap.set(key2,p4.promise);fireAndForget((()=>(async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{shareSerializedMap.delete(key2)}})()));return p4.promise}function skipIfDuplicated(key2,proc){if(skipDuplicatedMap.get(key2))return Promise.resolve(null);const p4=promiseWithResolver();skipDuplicatedMap.set(key2,p4.promise);fireAndForget((()=>(async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{skipDuplicatedMap.delete(key2)}})()));return p4.promise}async function scheduleOnceIfDuplicated(key2,proc){if(isLockAcquired(key2)){waitingProcessMap.set(key2,proc);return Promise.resolve(void 0)}return await serialized(key2,proc).then((()=>{const nextProc=waitingProcessMap.get(key2);if(nextProc){waitingProcessMap.delete(key2);return scheduleOnceIfDuplicated(key2,nextProc)}}))}function isLockAcquired(key2){var _a8;return(null!=(_a8=queueCount.get(key2))?_a8:0)>0}function deflateSync(data,opts){return dopt(data,opts||{},0,0)}function inflateSync(data,opts){return inflt(data,{i:2},opts&&opts.out,opts&&opts.dictionary)}function isCloudantURI(uri){return-1!==uri.indexOf(".cloudantnosqldb.")||-1!==uri.indexOf(".cloudant.com")}function wrapFflateFunc(func){return(data,opts)=>new Promise(((res2,rej)=>{func(data,opts,((err2,result)=>{err2?rej(err2):res2(result)}))}))}function isErrorOfMissingDoc(ex){return 404==(ex&&(null==ex?void 0:ex.status))}async function collectChunks(db,type){const rows=await async function collectChunksUsage(db){if(!await async function prepareChunkDesignDoc(db){var _a8;const chunkDesignDoc={_id:"_design/chunks",_rev:void 0,ver:2,views:{collectDangling:{map:(function(doc){doc._id.startsWith("h:")?emit([doc._id],0):"children"in doc&&doc.children.forEach((e3=>emit([e3],1)))}).toString(),reduce:"_sum"}}};let updateDDoc=!1;try{const old=await db.get(chunkDesignDoc._id);if(null!=(_a8=null==old?void 0:old.ver)?_a8:0"DANGLING"==type?0==e3.value:0!=e3.value))).flatMap((e3=>e3.key));return(await db.allDocs({keys:ids})).rows.filter((e3=>!("error"in e3))).map((e3=>({id:e3.id,rev:e3.value.rev})))}function sizeToHumanReadable(size){if(!size)return"-";const i2=Math.floor(Math.log(size)/Math.log(1024));return Number.parseInt((size/Math.pow(1024,i2)).toFixed(2))+" "+["B","kB","MB","GB","TB"][i2]}async function purgeUnreferencedChunks(db,dryRun,connSetting,performCompact=!1){const info3=await db.info();let resultCount=0;const getSize=function(info4,key2){var _a8,_b4;return Number.parseInt(null!=(_b4=null==(_a8=null==info4?void 0:info4.sizes)?void 0:_a8[key2])?_b4:0)},keySuffix=connSetting?"-remote":"-local";Logger(`${dryRun?"Counting":"Cleaning"} ${connSetting?"remote":"local"} database`,LOG_LEVEL_NOTICE);connSetting&&Logger(`Database active-size: ${sizeToHumanReadable(getSize(info3,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Collecting unreferenced chunks on ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);const chunks=await function collectUnreferencedChunks(db){return collectChunks(db,"DANGLING")}(db);resultCount=chunks.length;if(0==chunks.length)Logger(`No unreferenced chunks! ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);else{Logger(`Number of unreferenced chunks on ${info3.db_name}: ${chunks.length}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);if(dryRun){Logger(`DryRun of cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}if(connSetting){Logger("Cleaning unreferenced chunks on remote",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await async function purgeChunksRemote(setting,docs){await serialized("purge-remote",(async()=>{const buffer=function makeChunkedArrayFromArray(items){const chunked=[];for(let i2=0;i2[e3.id,[e3.rev]]))),"POST");Logger(JSON.stringify(await rets.json()),LOG_LEVEL_VERBOSE)}}))}(connSetting,chunks)}else{Logger("Cleaning unreferenced chunks on local",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await async function purgeChunksLocal(db,docs){await serialized("purge-local",(async()=>{try{Logger(`Purging unused ${docs.length} chunks `,LOG_LEVEL_NOTICE,"purge-local-backup");const batchDocsBackup=arrayToChunkedArray(docs,100);let total={ok:0,exist:0,error:0};for(const docsInBatch of batchDocsBackup){const backupDocs=(await db.allDocs({keys:docsInBatch.map((e3=>e3.id)),include_docs:!0})).rows.filter((e3=>"doc"in e3)).map((e3=>{const chunk={...e3.doc};delete chunk._rev;chunk._id=`_local/${chunk._id}`;return chunk})),ret=await db.bulkDocs(backupDocs);total=ret.map((e3=>({ok:"ok"in e3?1:0,exist:"status"in e3&&409==e3.status?1:0,error:"status"in e3&&409!=e3.status?1:0}))).reduce(((p4,c3)=>({ok:p4.ok+c3.ok,exist:p4.exist+c3.exist,error:p4.error+c3.error})),total);Logger(`Local chunk backed up: new:${total.ok} ,exist:${total.exist}, error:${total.error}`,LOG_LEVEL_NOTICE,"purge-local-backup");const erroredItems=ret.filter((e3=>"error"in e3&&409!=e3.status));for(const item of erroredItems)Logger(`Failed to back up: ${item.id} / ${item.rev}`,LOG_LEVEL_VERBOSE)}}catch(ex){Logger("Could not back up chunks");Logger(ex,LOG_LEVEL_VERBOSE)}Logger(`Purging unused ${docs.length} chunks... `,LOG_LEVEL_NOTICE,"purge-local");const batchDocs=arrayToChunkedArray(docs,100);let totalRemoved=0;for(const docsInBatch of batchDocs){const removed=await db.purgeMulti(docsInBatch.map((e3=>[e3.id,e3.rev])));totalRemoved+=Object.values(removed).filter((e3=>"ok"in e3)).length;Logger(`Purging: ${totalRemoved} / ${docs.length}`,LOG_LEVEL_NOTICE,"purge-local")}Logger(`Purging unused chunks done!: ${totalRemoved} chunks has been deleted.`,LOG_LEVEL_NOTICE,"purge-local")}))}(db,chunks)}Logger("Cleaning unreferenced chunks done!",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix)}if(performCompact){Logger("Compacting database...",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix);await db.compact();Logger("Compacting database done",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix)}if(connSetting){const endInfo=await db.info();Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(info3,"active")-getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external")-getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file")-getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE)}Logger(`Cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}function transferChunks(key2,label,dbFrom,dbTo,items){let totalProcessed=0;const total=items.length;return new QueueProcessor((async batched=>{const requestItems=batched.map((e3=>e3.id));return(await dbTo.allDocs({keys:requestItems})).rows.filter((e3=>"error"in e3&&"not_found"==e3.error)).map((e3=>e3.key))}),{batchSize:50,concurrentLimit:5,suspended:!0,delay:100},items).pipeTo(new QueueProcessor((async chunkIds=>(await dbFrom.allDocs({keys:chunkIds,include_docs:!0})).rows.filter((e3=>!("error"in e3))).map((e3=>e3.doc))),{batchSize:25,concurrentLimit:1,suspended:!0,delay:100})).pipeTo(new QueueProcessor((async docs=>{try{await dbTo.bulkDocs(docs,{new_edits:!1})}catch(ex){Logger(`${label}: Something went wrong on balancing`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{totalProcessed+=docs.length;Logger(`${label}: ${totalProcessed} / ${total}`,LOG_LEVEL_NOTICE,"balance-"+key2)}}),{batchSize:100,delay:100,concurrentLimit:2,suspended:!1})).startPipeline().waitForAllDoneAndTerminate()}async function balanceChunkPurgedDBs(local,remote){Logger("Complement missing chunks between databases",LOG_LEVEL_NOTICE);try{const{onlyOnLocal,onlyOnRemote}=await async function collectUnbalancedChunkIDs(local,remote){const chunksOnLocal=await collectChunks(local,"INUSE"),chunksOnRemote=await collectChunks(remote,"INUSE");return{onlyOnLocal:chunksOnLocal.filter((e3=>!chunksOnRemote.some((ee=>ee.id==e3.id)))),onlyOnRemote:chunksOnRemote.filter((e3=>!chunksOnLocal.some((ee=>ee.id==e3.id))))}}(local,remote),localToRemote=transferChunks("l2r","local -> remote",local,remote,onlyOnLocal),remoteToLocal=transferChunks("r2l","remote -> local",remote,local,onlyOnRemote);await Promise.all([localToRemote,remoteToLocal]);Logger("local -> remote: Done",LOG_LEVEL_NOTICE,"balance-l2r");Logger("remote -> local: Done",LOG_LEVEL_NOTICE,"balance-r2l")}catch(ex){Logger("Something went wrong on balancing!",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}Logger("Complement completed!",LOG_LEVEL_NOTICE)}function extractObject(template2,obj){const ret={...template2};for(const key2 in ret)ret[key2]=obj[key2];return ret}function isObjectDifferent(a2,b3,ignoreUndefined=!1){if(typeof a2!=typeof b3)return!0;if("object"==typeof a2){if(null===a2||null===b3)return a2!==b3;const keys3=[...new Set([...Object.keys(a2),...Object.keys(b3)])];return ignoreUndefined?keys3.map((key2=>void 0!==(null==a2?void 0:a2[key2])&&void 0!==(null==b3?void 0:b3[key2])&&isObjectDifferent(null==a2?void 0:a2[key2],null==b3?void 0:b3[key2]))).some((e3=>1==e3)):keys3.map((key2=>isObjectDifferent(key2 in a2?a2[key2]:SYMBOL_A,key2 in b3?b3[key2]:SYMBOL_B))).some((e3=>1==e3))}return a2!==b3}function sizeToHumanReadable2(size){const units=["B","KB","MB","GB","TB"];let i2=0;for(;size>=1024&&i2{p4.then(res2).catch((ex=>isErrorOfMissingDoc(ex)?res2(def):rej(ex)))}))}function getDocData(doc){return"string"==typeof doc?doc:doc.join("")}function getDocDataAsArray(doc){return"string"==typeof doc?[doc]:doc}function isTextBlob(blob){return"text/plain"===blob.type}function createTextBlob(data){const d4=Array.isArray(data)?data:[data];return new Blob(d4,{endings:"transparent",type:"text/plain"})}function createBinaryBlob(data){return new Blob([data],{endings:"transparent",type:"application/octet-stream"})}function createBlob(data){return data instanceof Blob?data:data instanceof Uint8Array||data instanceof ArrayBuffer?createBinaryBlob(data):createTextBlob(data)}function isTextDocument(doc){return"plain"==doc.type||"plain"==doc.datatype||!!isPlainText(doc.path)}function readAsBlob(doc){return isTextDocument(doc)?createTextBlob(doc.data):createBinaryBlob(decodeBinary(doc.data))}function readContent(doc){return isTextDocument(doc)?getDocData(doc.data):decodeBinary(doc.data)}async function isDocContentSame(docA,docB){const blob1=createBlob(docA),blob2=createBlob(docB);if(blob1.size!=blob2.size)return!1;if(isIndexDBCmpExist)return 0===globalThis.indexedDB.cmp(await blob1.arrayBuffer(),await blob2.arrayBuffer());const length=blob1.size;let i2=0;for(;i2set2.add(e3)));return set2}function escapeMarkdownValue(value){return"string"==typeof value?function replaceAllPairs(str,...fromTo){let r4=`${str}`;for(const[from,to]of fromTo)r4=replaceAll(r4,from,to);return r4}(value,["|","\\|"],["`","\\`"]):value}async function wrapException(func){try{return await func()}catch(ex){return ex instanceof Error?ex:new Error(ex)}}function isDirty(key2,value){if(previousValues.get(key2)===value)return!1;previousValues.set(key2,value);return!0}function isSensibleMargeApplicable(path2){return!!path2.endsWith(".md")}function isObjectMargeApplicable(path2){return!!path2.endsWith(".canvas")||!!path2.endsWith(".json")}function tryParseJSON(str,fallbackValue){try{return JSON.parse(str)}catch(e3){return fallbackValue}}function unorderedArrayToObject(obj){return obj.map((e3=>({[e3.id]:e3}))).reduce(((p4,c3)=>({...p4,...c3})),{})}function objectToUnorderedArray(obj){const entries2=Object.entries(obj);if(entries2.some((e3=>{var _a8;return e3[0]!=(null==(_a8=e3[1])?void 0:_a8.id)})))throw new Error("Item looks like not unordered array");return entries2.map((e3=>e3[1]))}function generatePatchUnorderedArray(from,to){if(from.every((e3=>"object"==typeof e3&&"id"in e3))&&to.every((e3=>"object"==typeof e3&&"id"in e3))){const diff=generatePatchObj(unorderedArrayToObject(from),unorderedArrayToObject(to));return Object.keys(diff).length>0?{[MARK_ISARRAY]:diff}:{}}return{[MARK_SWAPPED]:to}}function generatePatchObj(from,to){const entries2=Object.entries(from),tempMap=new Map(entries2),ret={},newEntries=Object.entries(to);for(const[key2,value]of newEntries)if(tempMap.has(key2)){const v2=tempMap.get(key2);if(typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value))ret[key2]={[MARK_SWAPPED]:value};else if(null===v2&&null===value);else if(null===v2&&null!==value)ret[key2]={[MARK_SWAPPED]:value};else if(null!==v2&&null===value)ret[key2]={[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[key2]=wk2)}else"object"!=typeof v2&&"object"!=typeof value?JSON.stringify(tempMap.get(key2))!==JSON.stringify(value)&&(ret[key2]=value):JSON.stringify(tempMap.get(key2))!==JSON.stringify(value)&&(ret[key2]={[MARK_SWAPPED]:value});else{const wk2=generatePatchObj(v2,value);Object.keys(wk2).length>0&&(ret[key2]=wk2)}tempMap.delete(key2)}else{ret[key2]=value;tempMap.delete(key2)}for(const[key2]of tempMap)ret[key2]=MARK_DELETED;return ret}function applyPatch(from,patch){const ret=from,patches=Object.entries(patch);for(const[key2,value]of patches)if(value!=MARK_DELETED)if(null!==value)if("object"==typeof value){if(MARK_SWAPPED in value){ret[key2]=value[MARK_SWAPPED];continue}if(MARK_ISARRAY in value){key2 in ret||(ret[key2]=[]);if(!Array.isArray(ret[key2]))throw new Error("Patch target type is mismatched (array to something)");const appliedArray=objectToUnorderedArray(applyPatch(unorderedArrayToObject(ret[key2]),value[MARK_ISARRAY]));ret[key2]=[...appliedArray]}else{if(!(key2 in ret)){ret[key2]=value;continue}ret[key2]=applyPatch(ret[key2],value)}}else ret[key2]=value;else ret[key2]=null;else delete ret[key2];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[key2,v2]of newEntries)if(key2 in ret){const value=ret[key2];typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value)?ret[key2]=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[key2]=[...new Set([...v2,...value])]:ret[key2]=v2:ret[key2]=mergeObject(v2,value)}else ret[key2]=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[key2,value]of e3){const p4=flattenObject(value,[...path2,key2]);ret.push(...p4)}return ret}function parseHeaderValues(strHeader){const headers={},lines=strHeader.split("\n");for(const line of lines){const[key2,value]=line.split(":",2).map((e3=>e3.trim()));key2&&value&&(headers[key2]=value)}return headers}function parseCustomRegExp(regexp){return regexp.startsWith("!!")?[!0,regexp.slice(2)]:[!1,regexp]}function isInvertedRegExp(regexp){const[negate3]=parseCustomRegExp(regexp);return negate3}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,key2){const flagCase=settings.handleFilenameCaseSensitive?"":"i";return function parseCustomRegExpList(list,flags,delimiter){const d4=null!=delimiter?delimiter:",";return list.replace(/\n| /g,"").split(d4).filter((e3=>e3)).map((e3=>new CustomRegExp(e3,flags)))}(settings[key2],flagCase,"syncInternalFilesIgnorePatterns"===key2||"syncInternalFilesTargetPatterns"===key2?",":"|[]|")}async function e(){function c3(t3,n4){if(e3.buffer.byteLength(a2.set(h4),o3(i3(0)))}}function d4(t3){return t3>>>0}function y2(t3){return t3&f4}function p4(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(3*t3.length,0),d4(n3(0,b3.encodeInto(t3,a2).written,e4))}function v2(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(3*t3.length,0),y2(r4(0,b3.encodeInto(t3,a2).written,e4))}const{instance:{exports:{mem:e3,xxh32:n3,xxh64:r4,init32:i2,update32:o2,digest32:h3,init64:s2,update64:u2,digest64:g2}}}=await WebAssembly.instantiate(t);let a2=new Uint8Array(e3.buffer);const f4=BigInt(2)**BigInt(64)-BigInt(1),b3=new TextEncoder,w2=BigInt(0);return{h32:p4,h32ToString(t3){return p4(t3,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0).toString(16).padStart(8,"0")},h32Raw(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(t3.byteLength,0),a2.set(t3),d4(n3(0,t3.byteLength,e4))},create32(){return l2(48,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,i2,o2,h3,d4)},h64:v2,h64ToString(t3){return v2(t3,arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2).toString(16).padStart(16,"0")},h64Raw(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(t3.byteLength,0),a2.set(t3),y2(r4(0,t3.byteLength,e4))},create64(){return l2(88,arguments.length>0&&void 0!==arguments[0]?arguments[0]:w2,s2,u2,g2,y2)}}}function mixedHash(str,seed,fnv1aHash_=epochFNV1a){let h1=seed,fnv1aHash=fnv1aHash_;const len=str.length;for(let i2=0;i2>>0;k1*=c1;k1=k1<>>32-r1;k1*=c2;h1^=k1;h1=h1<>>32-r2;h1=h1*m+n}h1^=len;h1^=h1>>>16;h1=Math.imul(h1,2246822507);h1^=h1>>>13;h1=Math.imul(h1,3266489909);h1^=h1>>>16;return[h1>>>0,fnv1aHash]}function fallbackMixedHashEach(src){let m3=1,f4=epochFNV1a;[m3,f4]=mixedHash(`${src.length}${src}`,m3,f4);return`${m3.toString(36)}${f4.toString(36)}`}async function sha1(src){const bytes=writeString(src),digest=await globalThis.crypto.subtle.digest({name:"SHA-1"},bytes);return await arrayBufferToBase64Single(digest)}function digestHash(src){let hash2="";for(const v2 of src)hash2=hashFunc(hash2+v2);return""==hash2?hashFunc("**"):hash2}function isTextBlob2(blob){return"text/plain"===blob.type}function*pickPiece(leftData,minimumChunkSize){let buffer="";L1:do{const curLine=leftData.shift();if(void 0===curLine){yield buffer;break L1}if(curLine.startsWith("```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")){yield buffer;buffer=curLine+(0!=leftData.length?"\n":"");L2:do{const curPx=leftData.shift();if(void 0===curPx)break L2;buffer+=curPx+(0!=leftData.length?"\n":"")}while(leftData.length>0&&!(leftData[0].startsWith("```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")));const isLooksLikeBASE64=buffer.endsWith("="),maybeUneditable=buffer.length>2048,endOfCodeBlock=leftData.shift();if(void 0!==endOfCodeBlock){buffer+=endOfCodeBlock;buffer+=0!=leftData.length?"\n":""}if(isLooksLikeBASE64||maybeUneditable)yield buffer;else{const splitExpr=/(.*?[;,:<])/g,sx=buffer.split(splitExpr).filter((e3=>""!=e3));for(const v2 of sx)yield v2}buffer=""}else{buffer+=curLine+(0!=leftData.length?"\n":"");if(buffer.length>=minimumChunkSize||0==leftData.length||"#"==leftData[0]||"#"==buffer[0]){yield buffer;buffer=""}}}while(leftData.length>0)}function*splitStringWithinLength(text2,pieceSize){let leftData=text2;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}function*splitTextInSegment(text2,pieceSize,minimumChunkSize){const segments=segmenter.segment(text2);let prev="",buf="";for(const seg of segments){const buffer=seg.segment;if(prev==buffer||buf.length0&&(yield*splitStringWithinLength(buf,pieceSize));buf=buffer}}buf.length>0&&(yield*splitStringWithinLength(buf,pieceSize))}function*chunkStringGenerator(source2,maxLength){const strLen=source2.length;if(strLen>maxLength){let from=0;do{let end=from+maxLength;if(end>strLen){yield source2.substring(from);break}for(;source2.charCodeAt(end-1)!=source2.codePointAt(end-1);)end++;yield source2.substring(from,end);from=end}while(fromMAX_ITEMS;)xMinimumChunkSize+=minimumChunkSize;const gen1=function*splitByDelimiterWithMinLength(sources,delimiter,minimumChunkLength=25,splitThreshold){let buf="",last=!1;const dl=delimiter.length;for(const source2 of sources){const max3=source2.length;if(splitThreshold&&max3>splitThreshold){yield buf+source2;last=!1;buf="";continue}let i2=-1,prev=0;L1:do{i2=source2.indexOf(delimiter,prev);if(-1==i2)break L1;buf+=source2.slice(prev,i2)+delimiter;if(buf.length>minimumChunkLength){yield buf;buf="";last=!1}else last=!0;prev=i2+dl}while(i210;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i2=0;const buf=new Uint8Array(await dataSrc.arrayBuffer());do{const findStart=i2+minimumChunkSize,defaultSplitEnd=i2+pieceSize;let splitEnd,i1=buf.indexOf(delimiter,findStart);-1==i1&&(i1=buf.indexOf(charNewLine,findStart));splitEnd=-1==i1?defaultSplitEnd:i10){yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize);buf.length=0}flushBefore=!1}buf.push(line);if(flush2){if(buf.length>0){yield*splitStringWithinLength(buf.join(""),pieceSize);buf.length=0}flush2=!1}}buf.length>0&&(0==inCodeBlock?yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize):yield*splitStringWithinLength(buf.join(""),pieceSize))}}(dataSrc,pieceSize,minimumChunkSize):function binaryTextSplit(data,pieceSize){return function*pieces(){yield*splitStringWithinLength(data,pieceSize)}}(dataSrc,pieceSize):function splitPiecesTextV1(dataSrc,pieceSize,plainSplit,minimumChunkSize){const dataList="string"==typeof dataSrc?[dataSrc]:dataSrc;return function*pieces(){for(const data of dataList)if(plainSplit){const f4=pickPiece(data.split("\n"),minimumChunkSize);for(const piece of f4){let buffer=piece;do{let ps=pieceSize;buffer.charCodeAt(ps-1)!=buffer.codePointAt(ps-1)&&ps++;yield buffer.substring(0,ps);buffer=buffer.substring(ps)}while(""!=buffer)}}else{let leftData=data;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}}}(dataSrc,pieceSize,plainSplit,minimumChunkSize)}(await dataSrc.text(),pieceSize,plainSplit,minimumChunkSize,null!=useSegmenter&&useSegmenter);let delimiter=0,canBeSmall=!1;if(filename&&filename.endsWith(".pdf"))delimiter="/".charCodeAt(0);else if(filename&&filename.endsWith(".json")){canBeSmall=!0;delimiter=",".charCodeAt(0)}const clampMin=canBeSmall?100:1e5;let step=1,w2=Math.max(clampMin,Math.min(1e8,dataSrc.size));for(;w2>10;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i2=0;do{let splitSize=pieceSize;const currentData=new Uint8Array(await dataSrc.slice(i2,i2+pieceSize).arrayBuffer());let nextIdx=currentData.indexOf(delimiter,minimumChunkSize);splitSize=-1==nextIdx?pieceSize:Math.min(pieceSize,nextIdx);-1==nextIdx&&(nextIdx=currentData.indexOf(charNewLine,minimumChunkSize));const piece=currentData.slice(0,splitSize);i2+=piece.length;const b64=await arrayBufferToBase64Single(piece);yield b64}while(i2{const unlisten=()=>{request2.removeEventListener("success",success);request2.removeEventListener("error",error)},success=()=>{resolve(wrap(request2.result));unlisten()},error=()=>{reject(request2.error);unlisten()};request2.addEventListener("success",success);request2.addEventListener("error",error)}));reverseTransformCache.set(promise,request2);return promise}(value);if(transformCache.has(value))return transformCache.get(value);const newValue=function transformCachableValue(value){if("function"==typeof value)return function wrapFunction(func){return function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}().includes(func)?function(...args){func.apply(unwrap(this),args);return wrap(this.request)}:function(...args){return wrap(func.apply(unwrap(this),args))}}(value);value instanceof IDBTransaction&&function cacheDonePromiseForTransaction(tx){if(transactionDoneMap.has(tx))return;const done=new Promise(((resolve,reject)=>{const unlisten=()=>{tx.removeEventListener("complete",complete);tx.removeEventListener("error",error);tx.removeEventListener("abort",error)},complete=()=>{resolve();unlisten()},error=()=>{reject(tx.error||new DOMException("AbortError","AbortError"));unlisten()};tx.addEventListener("complete",complete);tx.addEventListener("error",error);tx.addEventListener("abort",error)}));transactionDoneMap.set(tx,done)}(value);return instanceOfAny(value,function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}())?new Proxy(value,idbProxyTraps):value}(value);if(newValue!==value){transformCache.set(value,newValue);reverseTransformCache.set(newValue,value)}return newValue}function getMethod(target,prop2){if(!(target instanceof IDBDatabase)||prop2 in target||"string"!=typeof prop2)return;if(cachedMethods.get(prop2))return cachedMethods.get(prop2);const targetFuncName=prop2.replace(/FromIndex$/,""),useIndex=prop2!==targetFuncName,isWrite=writeMethods.includes(targetFuncName);if(!(targetFuncName in(useIndex?IDBIndex:IDBObjectStore).prototype)||!isWrite&&!readMethods.includes(targetFuncName))return;const method=async function(storeName,...args){const tx=this.transaction(storeName,isWrite?"readwrite":"readonly");let target2=tx.store;useIndex&&(target2=target2.index(args.shift()));return(await Promise.all([target2[targetFuncName](...args),isWrite&&tx.done]))[0]};cachedMethods.set(prop2,method);return method}async function*iterate(...args){let cursor=this;cursor instanceof IDBCursor||(cursor=await cursor.openCursor(...args));if(!cursor)return;const proxiedCursor=new Proxy(cursor,cursorIteratorTraps);ittrProxiedCursorToOriginalProxy.set(proxiedCursor,cursor);reverseTransformCache.set(proxiedCursor,unwrap(cursor));for(;cursor;){yield proxiedCursor;cursor=await(advanceResults.get(proxiedCursor)||cursor.continue());advanceResults.delete(proxiedCursor)}}function isIteratorProp(target,prop2){return prop2===Symbol.asyncIterator&&instanceOfAny(target,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===prop2&&instanceOfAny(target,[IDBIndex,IDBObjectStore])}function isTaskWaiting(task){if(task instanceof Promise)return!1;if(task instanceof Function)return!0;throw new Error("Invalid state")}async function wrapEachProcess(key2,task){try{return{key:key2,ok:await task}}catch(ex){return{key:key2,err:ex instanceof Error?ex:new Error(`${ex}`)}}}function scheduleTask(key2,timeout,proc,skipIfTaskExist){if(tasks2.has(key2)){if(skipIfTaskExist)return;cancelTask(key2)}const newTask=setTimeout((()=>{tasks2.delete(key2);proc()}),timeout);tasks2.set(key2,newTask)}function cancelTask(key2){const old=tasks2.get(key2);if(old){clearTimeout(old);tasks2.delete(key2)}}function cancelPeriodicTask(key2){if(key2 in intervals){clearInterval(intervals[key2]);delete intervals[key2]}}async function waitForTimeout(key2,timeout){return await shareRunningResult(key2,(async()=>{waitingItems.add(key2);try{const ret=await globalSlipBoard.awaitNext("wait-for-timeout",key2,{timeout});return ret===TIMED_OUT_SIGNAL||ret}finally{waitingItems.delete(key2)}}))}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"}}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 getStoragePathFromUXFileInfo(file){return stripAllPrefixes("string"==typeof file?file:file.path)}function getDatabasePathFromUXFileInfo(file){if("string"==typeof file&&file.startsWith(ICXHeader))return file;const prefix=function isInternalFile(file){return"string"==typeof file?file.startsWith(ICHeader):!!file.isInternal}(file)?ICHeader:"";return"string"==typeof file?prefix+stripAllPrefixes(file):prefix+stripAllPrefixes(file.path)}function memoObject(key2,obj){memos[key2]=obj;return memos[key2]}async function memoIfNotExist(key2,func){if(!(key2 in memos)){const w2=func(),v2=w2 instanceof Promise?await w2:w2;memos[key2]=v2}return memos[key2]}function retrieveMemoObject(key2){return key2 in memos&&memos[key2]}function disposeMemoObject(key2){delete memos[key2]}function isValidPath(filename){if(import_obsidian.Platform.isDesktop)return"darwin"==process.platform?isValidFilenameInDarwin(filename):"linux"==process.platform?function isValidFilenameInLinux(filename){return!/[\u0000-\u001f]|[:]/g.test(filename)}(filename):isValidFilenameInWidows(filename);if(import_obsidian.Platform.isAndroidApp)return function isValidFilenameInAndroid(filename){return!/[\u0000-\u001f]|[\\":?<>|*#]/g.test(filename)}(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 isPluginMetadata(str){return str.startsWith(PSCHeader)}function isCustomisationSyncMetadata(str){return str.startsWith(ICXHeader)}function requestToCouchDBWithCredentials(baseUri,credentials,origin2="",key2,body,method,customHeaders){return _requestToCouchDB(baseUri,credentials,origin2,"_node/_local/_config"+(key2?"/"+key2:""),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(key2,[...new Set([...pairs,mtime1,mtime2])]):sameChangePairs.set(key2,[mtime1,mtime2])}function unmarkChanges(file){const key2=getKey(file);sameChangePairs.delete(key2)}function isMarkedAsSameChanges(file,mtimes){const key2=getKey(file),pairs=sameChangePairs.get(key2,[])||[];if(mtimes.every((e3=>-1!==pairs.indexOf(e3))))return EVEN}function compareFileFreshness(baseFile,checkTarget){var _a8,_b4,_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!=(_b4=null==(_a8=null==baseFile?void 0:baseFile.stat)?void 0:_a8.mtime)?_b4: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 displayRev(rev3){const[number,hash2]=rev3.split("-");return`${number}-${hash2.substring(0,6)}`}function getLogLevel(showNotice){return showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO}async function autosaveCache(db,mapKey){var _a8;const savedData=null!=(_a8=await db.get(mapKey))?_a8:new Map,_commit=()=>{try{scheduleTask("commit-map-save-"+mapKey,250,(async()=>{await db.set(mapKey,savedData)}))}catch(e3){}};return{set(key2,value){const modified=savedData.get(key2)!==value,result=savedData.set(key2,value);modified&&_commit();return result},clear(){savedData.clear();_commit()},delete(key2){const result=savedData.delete(key2);result&&_commit();return result},get:key2=>savedData.get(key2),has:key2=>savedData.has(key2),keys:()=>savedData.keys(),get size(){return savedData.size}}}function onlyInNTimes(n3,proc){let counter=0;return function(){counter++%n3==0&&proc(counter)}}function updatePreviousExecutionTime(key2,timeDelta=0){key2 in waitingTasks||(waitingTasks[key2]={task:void 0,previous:0,leastNext:0});waitingTasks[key2].leastNext=Math.max(Date.now()+timeDelta,waitingTasks[key2].leastNext)}function reactiveSource(initialValue){return _reactive({initialValue})}function reactive(expression,initialValue){return _reactive({expression,initialValue})}function topologicalSort(startNode){if(topologicalSortCache.has(startNode.id)){const ref=topologicalSortCache.get(startNode.id);if(ref){const result2=ref.map((e3=>e3.instance.deref())).filter((e3=>e3));if(result2.length===ref.length)return result2}}const visited=new Set,sorted=[],recursionStack=new Set;(function visit(node){if(!visited.has(node)){if(recursionStack.has(node))throw new Error("Circular dependency detected!");visited.add(node);recursionStack.add(node);for(const dependant of node.dependants)visit(dependant);sorted.push(node);recursionStack.delete(node)}})(startNode);const result=sorted.reverse();topologicalSortCache.set(startNode.id,result.map((e3=>({id:e3.id,instance:new FallbackWeakRef(e3)}))));return result}function _reactive({expression,initialValue,isSource}){let value,_isDirty=!1;const id=_reactiveSourceId++,changeHandlers=new Set,instance3={id,dependants:new Set,_markDirty(){_isDirty||(_isDirty=!0)},markDirty(){topologicalSort(instance3).forEach((node=>node._markDirty()))},_rippleChanged(){changeHandlers.forEach((e3=>e3(instance3)))},rippleChanged(){topologicalSort(instance3).forEach((node=>node._rippleChanged()))},markClean(){_isDirty=!1},get isDirty(){return _isDirty},get value(){if(context&&!instance3.dependants.has(context)){instance3.dependants.add(context);(function resetTopologicalSortCacheFor(ids){ids.forEach((id=>topologicalSortCache.delete(id)));topologicalSortCache.forEach(((value,key2)=>{ids.includes(key2)||topologicalSortCache.delete(key2)}))})([instance3.id,context.id])}if(_isDirty){if(expression){const oldValue=value,newValue=expression();isObjectDifferent(oldValue,newValue)&&(value=newValue)}instance3.markClean()}return value},set value(newValue){if(_isDirty&&!expression)value=newValue;else if(isObjectDifferent(value,newValue)){value=newValue;if(!_isDirty){instance3.markDirty();instance3.rippleChanged()}}},onChanged(handler){changeHandlers.add(handler)},offChanged(handler){changeHandlers.delete(handler)}};value=function initialize(){const previousContext=context;context=instance3;const r4=expression?expression(initialValue):initialValue;context=previousContext;return r4}();return instance3}function computed(expression){const v2=reactive(expression);return()=>v2.value}function isOverridableKey(key2){return key2.startsWith("$")}function isInjectableKey(key2){return key2.startsWith("$$")}function isAllExecuteKey(key2){return key2.startsWith("$all")}function isEveryExecuteKey(key2){return key2.startsWith("$every")}function isAnyExecuteKey(key2){return key2.startsWith("$any")}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 is_function(thing){return"function"==typeof thing}function run(fn){return fn()}function run_all(arr){for(var i2=0;i2{var result,previous_reaction=active_reaction;set_active_reaction(reaction);result=fn();set_active_reaction(previous_reaction);return result};is_proxied_array&&sources.set("length",state(value.length,stack2));return new Proxy(value,{defineProperty(_,prop2,descriptor){"value"in descriptor&&!1!==descriptor.configurable&&!1!==descriptor.enumerable&&!1!==descriptor.writable||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")}();var s2=sources.get(prop2);if(void 0===s2){s2=with_parent((()=>state(descriptor.value,stack2)));sources.set(prop2,s2)}else set(s2,with_parent((()=>proxy(descriptor.value))));return!0},deleteProperty(target,prop2){var ls,n3,s2=sources.get(prop2);if(void 0===s2){if(prop2 in target){sources.set(prop2,with_parent((()=>state(UNINITIALIZED,stack2))));update_version(version2)}}else{if(is_proxied_array&&"string"==typeof prop2){ls=sources.get("length");n3=Number(prop2);Number.isInteger(n3)&&n3state(proxy(exists?target[prop2]:UNINITIALIZED),stack2)));sources.set(prop2,s2)}return void 0!==s2?(v2=get(s2))===UNINITIALIZED?void 0:v2:Reflect.get(target,prop2,receiver)},getOwnPropertyDescriptor(target,prop2){var s2,source2,value2,descriptor=Reflect.getOwnPropertyDescriptor(target,prop2);if(descriptor&&"value"in descriptor)(s2=sources.get(prop2))&&(descriptor.value=get(s2));else if(void 0===descriptor){value2=null==(source2=sources.get(prop2))?void 0:source2.v;if(void 0!==source2&&value2!==UNINITIALIZED)return{enumerable:!0,configurable:!0,value:value2,writable:!0}}return descriptor},has(target,prop2){var _a8,s2,has;if(prop2===STATE_SYMBOL)return!0;s2=sources.get(prop2);has=void 0!==s2&&s2.v!==UNINITIALIZED||Reflect.has(target,prop2);if(void 0!==s2||null!==active_effect&&(!has||(null==(_a8=get_descriptor(target,prop2))?void 0:_a8.writable))){if(void 0===s2){s2=with_parent((()=>state(has?proxy(target[prop2]):UNINITIALIZED,stack2)));sources.set(prop2,s2)}if(get(s2)===UNINITIALIZED)return!1}return has},set(target,prop2,value2,receiver){var _a8,i2,other_s,descriptor,ls,n3,s2=sources.get(prop2),has=prop2 in target;if(is_proxied_array&&"length"===prop2)for(i2=value2;i2state(UNINITIALIZED,stack2)));sources.set(i2+"",other_s)}if(void 0===s2){if(!has||(null==(_a8=get_descriptor(target,prop2))?void 0:_a8.writable)){set(s2=with_parent((()=>state(void 0,stack2))),with_parent((()=>proxy(value2))));sources.set(prop2,s2)}}else{has=s2.v!==UNINITIALIZED;set(s2,with_parent((()=>proxy(value2))))}(null==(descriptor=Reflect.getOwnPropertyDescriptor(target,prop2))?void 0:descriptor.set)&&descriptor.set.call(receiver,value2);if(!has){if(is_proxied_array&&"string"==typeof prop2){ls=sources.get("length");n3=Number(prop2);Number.isInteger(n3)&&n3>=ls.v&&set(ls,n3+1)}update_version(version2)}return!0},ownKeys(target){var own_keys;get(version2);own_keys=Reflect.ownKeys(target).filter((key3=>{var source3=sources.get(key3);return void 0===source3||source3.v!==UNINITIALIZED}));for(var[key2,source2]of sources)source2.v===UNINITIALIZED||key2 in target||own_keys.push(key2);return own_keys},setPrototypeOf(){(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 update_version(signal,d4=1){set(signal,signal.v+d4)}function get_proxied_value(value){try{if(null!==value&&"object"==typeof value&&STATE_SYMBOL in value)return value[STATE_SYMBOL]}catch(e3){}return value}function is(a2,b3){return Object.is(get_proxied_value(a2),get_proxied_value(b3))}function create_text(value=""){return document.createTextNode(value)}function get_first_child(node){return first_child_getter.call(node)}function get_next_sibling(node){return next_sibling_getter.call(node)}function child(node,is_text){var child2,text2;if(!hydrating)return get_first_child(node);if(null===(child2=get_first_child(hydrate_node)))child2=hydrate_node.appendChild(create_text());else if(is_text&&3!==child2.nodeType){text2=create_text();null==child2||child2.before(text2);set_hydrate_node(text2);return text2}set_hydrate_node(child2);return child2}function first_child(fragment,is_text){var _a8,_b4,first,text2;if(!hydrating)return(first=get_first_child(fragment))instanceof Comment&&""===first.data?get_next_sibling(first):first;if(is_text&&3!==(null==(_a8=hydrate_node)?void 0:_a8.nodeType)){text2=create_text();null==(_b4=hydrate_node)||_b4.before(text2);set_hydrate_node(text2);return text2}return hydrate_node}function sibling(node,count=1,is_text=!1){var last_sibling,type,text2;let next_sibling=hydrating?hydrate_node:node;for(;count--;){last_sibling=next_sibling;next_sibling=get_next_sibling(next_sibling)}if(!hydrating)return next_sibling;type=null==next_sibling?void 0:next_sibling.nodeType;if(is_text&&3!==type){text2=create_text();null===next_sibling?null==last_sibling||last_sibling.after(text2):next_sibling.before(text2);set_hydrate_node(text2);return text2}set_hydrate_node(next_sibling);return next_sibling}function equals2(value){return value===this.v}function safe_not_equal(a2,b3){return a2!=a2?b3==b3:a2!==b3||null!==a2&&"object"==typeof a2||"function"==typeof a2}function safe_equals(value){return!safe_not_equal(value,this.v)}function derived(fn){var flags=DERIVED|DIRTY,parent_derived=null!==active_reaction&&active_reaction.f&DERIVED?active_reaction:null;null===active_effect||null!==parent_derived&&parent_derived.f&UNOWNED?flags|=UNOWNED:active_effect.f|=EFFECT_HAS_DERIVED;const signal={ctx:component_context,deps:null,effects:null,equals:equals2,f:flags,fn,reactions:null,rv:0,v:null,wv:0,parent:null!=parent_derived?parent_derived:active_effect};dev_fallback_default&&tracing_mode_flag&&(signal.created=get_stack("CreatedAt"));return signal}function user_derived(fn){const d4=derived(fn);push_reaction_value(d4);return d4}function derived_safe_equal(fn){const signal=derived(fn);signal.equals=safe_equals;return signal}function destroy_derived_effects(derived3){var i2,effects=derived3.effects;if(null!==effects){derived3.effects=null;for(i2=0;i2{deps();if(!token.ran){token.ran=!0;set(context2.l.r2,!0);untrack(fn)}}))}function legacy_pre_effect_reset(){var context2=component_context;render_effect((()=>{var token,effect2;if(get(context2.l.r2)){for(token of context2.l.r1){(effect2=token.effect).f&CLEAN&&set_signal_status(effect2,MAYBE_DIRTY);check_dirtiness(effect2)&&update_effect(effect2);token.ran=!1}context2.l.r2.v=!1}}))}function render_effect(fn){return create_effect(RENDER_EFFECT,fn,!0)}function template_effect(fn,thunks=[],d4=derived){const deriveds=thunks.map(d4),effect2=()=>fn(...deriveds.map(get));dev_fallback_default&&define_property(effect2,"name",{value:"{expression}"});return block(effect2)}function block(fn,flags=0){return create_effect(RENDER_EFFECT|BLOCK_EFFECT|flags,fn,!0)}function branch(fn,push2=!0){return create_effect(RENDER_EFFECT|BRANCH_EFFECT,fn,!0,push2)}function execute_effect_teardown(effect2){var teardown2=effect2.teardown;if(null!==teardown2){const previously_destroying_effect=is_destroying_effect,previous_reaction=active_reaction;set_is_destroying_effect(!0);set_active_reaction(null);try{teardown2.call(null)}finally{set_is_destroying_effect(previously_destroying_effect);set_active_reaction(previous_reaction)}}}function destroy_effect_children(signal,remove_dom=!1){var next2,effect2=signal.first;signal.first=signal.last=null;for(;null!==effect2;){next2=effect2.next;effect2.f&ROOT_EFFECT?effect2.parent=null:destroy_effect(effect2,remove_dom);effect2=next2}}function destroy_effect(effect2,remove_dom=!0){var transitions,parent,removed=!1;if((remove_dom||effect2.f&HEAD_EFFECT)&&null!==effect2.nodes_start){(function remove_effect_dom(node,end){for(;null!==node;){var next2=node===end?null:get_next_sibling(node);node.remove();node=next2}})(effect2.nodes_start,effect2.nodes_end);removed=!0}destroy_effect_children(effect2,remove_dom&&!removed);remove_reactions(effect2,0);set_signal_status(effect2,DESTROYED);if(null!==(transitions=effect2.transitions))for(const transition2 of transitions)transition2.stop();execute_effect_teardown(effect2);null!==(parent=effect2.parent)&&null!==parent.first&&unlink_effect(effect2);dev_fallback_default&&(effect2.component_function=null);effect2.next=effect2.prev=effect2.teardown=effect2.ctx=effect2.deps=effect2.fn=effect2.nodes_start=effect2.nodes_end=null}function unlink_effect(effect2){var parent=effect2.parent,prev=effect2.prev,next2=effect2.next;null!==prev&&(prev.next=next2);null!==next2&&(next2.prev=prev);if(null!==parent){parent.first===effect2&&(parent.first=next2);parent.last===effect2&&(parent.last=prev)}}function pause_effect(effect2,callback){var transitions=[];pause_children(effect2,transitions,!0);run_out_transitions(transitions,(()=>{destroy_effect(effect2);callback&&callback()}))}function run_out_transitions(transitions,fn){var check,transition2,remaining=transitions.length;if(remaining>0){check=()=>--remaining||fn();for(transition2 of transitions)transition2.out(check)}else fn()}function pause_children(effect2,transitions,local){var child2,sibling2;if(!(effect2.f&INERT)){effect2.f^=INERT;if(null!==effect2.transitions)for(const transition2 of effect2.transitions)(transition2.is_global||local)&&transitions.push(transition2);child2=effect2.first;for(;null!==child2;){sibling2=child2.next;pause_children(child2,transitions,!!(child2.f&EFFECT_TRANSPARENT||child2.f&BRANCH_EFFECT)&&local);child2=sibling2}}}function resume_effect(effect2){resume_children(effect2,!0)}function resume_children(effect2,local){var child2,sibling2;if(effect2.f&INERT){effect2.f^=INERT;effect2.f&CLEAN||(effect2.f^=CLEAN);if(check_dirtiness(effect2)){set_signal_status(effect2,DIRTY);schedule_effect(effect2)}child2=effect2.first;for(;null!==child2;){sibling2=child2.next;resume_children(child2,!!(child2.f&EFFECT_TRANSPARENT||child2.f&BRANCH_EFFECT)&&local);child2=sibling2}if(null!==effect2.transitions)for(const transition2 of effect2.transitions)(transition2.is_global||local)&&transition2.in()}}function run_micro_tasks(){var tasks3=micro_tasks;micro_tasks=[];run_all(tasks3)}function run_idle_tasks(){var tasks3=idle_tasks;idle_tasks=[];run_all(tasks3)}function queue_micro_task(fn){0===micro_tasks.length&&queueMicrotask(run_micro_tasks);micro_tasks.push(fn)}function set_is_destroying_effect(value){is_destroying_effect=value}function set_active_reaction(reaction){active_reaction=reaction}function set_active_effect(effect2){active_effect=effect2}function push_reaction_value(value){null!==active_reaction&&active_reaction.f&EFFECT_IS_UPDATING&&(null===reaction_sources?reaction_sources=[value]:reaction_sources.push(value))}function increment_write_version(){return++write_version}function check_dirtiness(reaction){var _a8,_b4,dependencies,is_unowned,i2,dependency,is_disconnected,is_unowned_connected,length,derived3,parent,flags=reaction.f;if(flags&DIRTY)return!0;if(flags&MAYBE_DIRTY){dependencies=reaction.deps;is_unowned=!!(flags&UNOWNED);if(null!==dependencies){is_disconnected=!!(flags&DISCONNECTED);is_unowned_connected=is_unowned&&null!==active_effect&&!skip_reaction;length=dependencies.length;if(is_disconnected||is_unowned_connected){parent=(derived3=reaction).parent;for(i2=0;i2reaction.wv)return!0}}is_unowned&&(null===active_effect||skip_reaction)||set_signal_status(reaction,CLEAN)}return!1}function should_rethrow_error(effect2){return!(effect2.f&DESTROYED||null!==effect2.parent&&effect2.parent.f&BOUNDARY_EFFECT)}function handle_error(error,effect2,previous_effect,component_context2){var _a8,_b4,filename;if(is_throwing_error){null===previous_effect&&(is_throwing_error=!1);if(should_rethrow_error(effect2))throw error}else{null!==previous_effect&&(is_throwing_error=!0);if(dev_fallback_default&&null!==component_context2&&error instanceof Error&&!handled_errors.has(error)){handled_errors.add(error);const component_stack=[],effect_name=null==(_a8=effect2.fn)?void 0:_a8.name;effect_name&&component_stack.push(effect_name);let current_context=component_context2;for(;null!==current_context;){if(filename=null==(_b4=current_context.function)?void 0:_b4[FILENAME]){const file=filename.split("/").pop();component_stack.push(file)}current_context=current_context.p}const indent=is_firefox?" ":"\t";define_property(error,"message",{value:error.message+`\n${component_stack.map((name=>`\n${indent}in ${name}`)).join("")}\n`});define_property(error,"component_stack",{value:component_stack});const stack2=error.stack;if(stack2){const lines=stack2.split("\n"),new_lines=[];for(let i2=0;i20){deps.length=skipped_deps+new_deps.length;for(i2=0;i2d4.fn)));dev_effect_stack=[]}function infinite_loop_guard(){try{(function effect_update_depth_exceeded(){if(dev_fallback_default){const error=new Error("effect_update_depth_exceeded\nMaximum update depth exceeded. This can happen when a reactive block or effect repeatedly sets a new value. Svelte limits the number of nested updates to prevent infinite loops\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")})()}catch(error){dev_fallback_default&&define_property(error,"stack",{value:""});if(null===last_scheduled_effect){dev_fallback_default&&log_effect_stack();throw error}if(dev_fallback_default)try{handle_error(error,last_scheduled_effect,null,null)}catch(e3){log_effect_stack();throw e3}else handle_error(error,last_scheduled_effect,null,null)}}function flush_queued_root_effects(){var flush_count,root_effects,length,i2,was_updating_effect=is_updating_effect;try{flush_count=0;is_updating_effect=!0;for(;queued_root_effects.length>0;){flush_count++>1e3&&infinite_loop_guard();length=(root_effects=queued_root_effects).length;queued_root_effects=[];for(i2=0;i2untrack(fn)));for(signal of captured)if(signal.f&LEGACY_DERIVED_PROP)for(const dep of signal.deps||[])dep.f&DERIVED||internal_set(dep,dep.v);else internal_set(signal,signal.v)}function untrack(fn){var previous_untracking=untracking;try{untracking=!0;return fn()}finally{untracking=previous_untracking}}function set_signal_status(signal,status){signal.f=signal.f&STATUS_MASK|status}function deep_read_state(value){if("object"==typeof value&&value&&!(value instanceof EventTarget))if(STATE_SYMBOL in value)deep_read(value);else if(!Array.isArray(value))for(let key2 in value){const prop2=value[key2];"object"==typeof prop2&&prop2&&STATE_SYMBOL in prop2&&deep_read(prop2)}}function deep_read(value,visited=new Set){if(!("object"!=typeof value||null===value||value instanceof EventTarget||visited.has(value))){visited.add(value);value instanceof Date&&value.getTime();for(let key2 in value)try{deep_read(value[key2],visited)}catch(e3){}const proto=get_prototype_of(value);if(proto!==Object.prototype&&proto!==Array.prototype&&proto!==Map.prototype&&proto!==Set.prototype&&proto!==Date.prototype){const descriptors=get_descriptors(proto);for(let key2 in descriptors){const get4=descriptors[key2].get;if(get4)try{get4.call(value)}catch(e3){}}}}}function set_inspect_effects(v2){inspect_effects=v2}function source(v2,stack2){var signal={f:0,v:v2,reactions:null,equals:equals2,rv:0,wv:0};if(dev_fallback_default&&tracing_mode_flag){signal.created=null!=stack2?stack2:get_stack("CreatedAt");signal.debug=null}return signal}function state(v2,stack2){const s2=source(v2,stack2);push_reaction_value(s2);return s2}function mutable_source(initial_value,immutable=!1){var _a8,_b4;const s2=source(initial_value);immutable||(s2.equals=safe_equals);legacy_mode_flag&&null!==component_context&&null!==component_context.l&&(null!=(_b4=(_a8=component_context.l).s)?_b4:_a8.s=[]).push(s2);return s2}function set(source2,value,should_proxy=!1){var _a8;null!==active_reaction&&!untracking&&is_runes()&&active_reaction.f&(DERIVED|BLOCK_EFFECT)&&!(null==(_a8=reaction_sources)?void 0:_a8.includes(source2))&&function state_unsafe_mutation(){if(dev_fallback_default){const error=new Error("state_unsafe_mutation\nUpdating state inside a derived 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")}();return internal_set(source2,should_proxy?proxy(value):value)}function internal_set(source2,value){var old_value;if(!source2.equals(value)){old_value=source2.v;is_destroying_effect?old_values.set(source2,value):old_values.set(source2,old_value);source2.v=value;if(dev_fallback_default&&tracing_mode_flag){source2.updated=get_stack("UpdatedAt");if(null!=active_effect){source2.trace_need_increase=!0;null!=source2.trace_v||(source2.trace_v=old_value)}}if(source2.f&DERIVED){source2.f&DIRTY&&execute_derived(source2);set_signal_status(source2,source2.f&UNOWNED?MAYBE_DIRTY:CLEAN)}source2.wv=increment_write_version();mark_reactions(source2,DIRTY);is_runes()&&null!==active_effect&&active_effect.f&CLEAN&&!(active_effect.f&(BRANCH_EFFECT|ROOT_EFFECT))&&(null===untracked_writes?function set_untracked_writes(value){untracked_writes=value}([source2]):untracked_writes.push(source2));if(dev_fallback_default&&inspect_effects.size>0){const inspects=Array.from(inspect_effects);for(const effect2 of inspects){effect2.f&CLEAN&&set_signal_status(effect2,MAYBE_DIRTY);check_dirtiness(effect2)&&update_effect(effect2)}inspect_effects.clear()}}return value}function update(source2,d4=1){var value=get(source2),result=1===d4?value++:value--;set(source2,value);return result}function mark_reactions(signal,status){var runes,length,i2,reaction,flags,reactions=signal.reactions;if(null!==reactions){runes=is_runes();length=reactions.length;for(i2=0;i2{ctx.d=!0}));if(dev_fallback_default){component_context.function=fn;dev_current_component_function=fn}}function pop(component2){var _a8,_b4,previous_effect,previous_reaction,i2,component_effect;const context_stack_item=component_context;if(null!==context_stack_item){void 0!==component2&&(context_stack_item.x=component2);const component_effects=context_stack_item.e;if(null!==component_effects){previous_effect=active_effect;previous_reaction=active_reaction;context_stack_item.e=null;try{for(i2=0;i2{Promise.resolve().then((()=>{var _a8;if(!evt.defaultPrevented)for(const e3 of evt.target.elements)null==(_a8=e3.__on_r)||_a8.call(e3)}))}),{capture:!0})}}function without_reactive_context(fn){var previous_reaction=active_reaction,previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{return fn()}finally{set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}function listen_to_event_and_reset_event(element2,event2,handler,on_reset=handler){element2.addEventListener(event2,(()=>without_reactive_context(handler)));const prev=element2.__on_r;element2.__on_r=prev?()=>{prev();on_reset(!0)}:()=>on_reset(!0);add_form_reset_listener()}function event(event_name,dom,handler,capture,passive2){var options={capture,passive:passive2},target_handler=function create_event(event_name,dom,handler,options={}){function target_handler(event2){options.capture||handle_event_propagation.call(dom,event2);if(!event2.cancelBubble)return without_reactive_context((()=>null==handler?void 0:handler.call(this,event2)))}event_name.startsWith("pointer")||event_name.startsWith("touch")||"wheel"===event_name?queue_micro_task((()=>{dom.addEventListener(event_name,target_handler,options)})):dom.addEventListener(event_name,target_handler,options);return target_handler}(event_name,dom,handler,options);dom!==document.body&&dom!==window&&dom!==document||teardown((()=>{dom.removeEventListener(event_name,target_handler,options)}))}function delegate(events){var i2,fn;for(i2=0;i2current_target||owner_document});previous_reaction=active_reaction;previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{other_errors=[];for(;null!==current_target;){parent_element=current_target.assignedSlot||current_target.parentNode||current_target.host||null;try{if(null!=(delegated=current_target["__"+event_name])&&(!current_target.disabled||event2.target===current_target))if(is_array(delegated)){var[fn,...data]=delegated;fn.apply(current_target,[event2,...data])}else delegated.call(current_target,event2)}catch(error){throw_error?other_errors.push(error):throw_error=error}if(event2.cancelBubble||parent_element===handler_element||null===parent_element)break;current_target=parent_element}if(throw_error){for(let error of other_errors)queueMicrotask((()=>{throw error}));throw throw_error}}finally{event2.__root=handler_element;delete event2.currentTarget;set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}}function assign_nodes(start,end){var effect2=active_effect;if(null===effect2.nodes_start){effect2.nodes_start=start;effect2.nodes_end=end}}function template(content,flags){var node,is_fragment=!!(flags&TEMPLATE_FRAGMENT),use_import_node=!!(flags&TEMPLATE_USE_IMPORT_NODE),has_start=!content.startsWith("");return()=>{var clone3;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}if(void 0===node){node=function create_fragment_from_html(html2){var elem=document.createElement("template");elem.innerHTML=html2;return elem.content}(has_start?content:""+content);is_fragment||(node=get_first_child(node))}clone3=use_import_node||is_firefox?document.importNode(node,!0):node.cloneNode(!0);is_fragment?assign_nodes(get_first_child(clone3),clone3.lastChild):assign_nodes(clone3,clone3);return clone3}}function text(value=""){var t3,node;if(!hydrating){assign_nodes(t3=create_text(value+""),t3);return t3}if(3!==(node=hydrate_node).nodeType){node.before(node=create_text());set_hydrate_node(node)}assign_nodes(node,node);return node}function comment(){var frag,start,anchor;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}frag=document.createDocumentFragment();start=document.createComment("");anchor=create_text();frag.append(start,anchor);assign_nodes(start,anchor);return frag}function append(anchor,dom){if(hydrating){active_effect.nodes_end=hydrate_node;hydrate_next()}else null!==anchor&&anchor.before(dom)}function set_text(text2,value){var _a8,str=null==value?"":"object"==typeof value?value+"":value;if(str!==(null!=(_a8=text2.__t)?_a8:text2.__t=text2.nodeValue)){text2.__t=str;text2.nodeValue=str+""}}function mount(component2,options){return function _mount(Component,{target,anchor,props={},events,context:context2,intro=!0}){var registered_events,event_handle,component2,unmount2;(function init_operations(){var element_prototype,node_prototype,text_prototype;if(void 0===$window){$window=window;document;is_firefox=/Firefox/.test(navigator.userAgent);element_prototype=Element.prototype;node_prototype=Node.prototype;text_prototype=Text.prototype;first_child_getter=get_descriptor(node_prototype,"firstChild").get;next_sibling_getter=get_descriptor(node_prototype,"nextSibling").get;if(is_extensible(element_prototype)){element_prototype.__click=void 0;element_prototype.__className=void 0;element_prototype.__attributes=null;element_prototype.__style=void 0;element_prototype.__e=void 0}is_extensible(text_prototype)&&(text_prototype.__t=void 0);if(dev_fallback_default){element_prototype.__svelte_meta=null;(function init_array_prototype_warnings(){const array_prototype2=Array.prototype,cleanup=Array.__svelte_cleanup;cleanup&&cleanup();const{indexOf,lastIndexOf,includes}=array_prototype2;array_prototype2.indexOf=function(item,from_index){const index6=indexOf.call(this,item,from_index);if(-1===index6)for(let i2=null!=from_index?from_index:0;i2{array_prototype2.indexOf=indexOf;array_prototype2.lastIndexOf=lastIndexOf;array_prototype2.includes=includes}})()}}})();registered_events=new Set;event_handle=events2=>{var i2,event_name,passive2,n3,name;for(i2=0;i2new Promise((fulfil=>{if(options.outro)pause_effect(effect2,(()=>{destroy_effect(effect2);fulfil(void 0)}));else{destroy_effect(effect2);fulfil(void 0)}}))}((()=>{var anchor_node=null!=anchor?anchor:target.appendChild(create_text());branch((()=>{if(context2){push({});component_context.c=context2}events&&(props.$$events=events);hydrating&&assign_nodes(anchor_node,null);component2=Component(anchor_node,props)||{};hydrating&&(active_effect.nodes_end=hydrate_node);context2&&pop()}));return()=>{var _a8,event_name,n3;for(event_name of registered_events){target.removeEventListener(event_name,handle_event_propagation);n3=document_listeners.get(event_name);if(0==--n3){document.removeEventListener(event_name,handle_event_propagation);document_listeners.delete(event_name)}else document_listeners.set(event_name,n3)}root_event_handles.delete(event_handle);anchor_node!==anchor&&(null==(_a8=anchor_node.parentNode)||_a8.removeChild(anchor_node))}}));mounted_components.set(component2,unmount2);return component2}(component2,options)}function unmount(component2,options){const fn=mounted_components.get(component2);if(fn){mounted_components.delete(component2);return fn(options)}dev_fallback_default&&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")}();return Promise.resolve()}function if_block(node,fn,[root_index,hydrate_index]=[0,0]){var anchor,consequent_effect,alternate_effect,condition,has_branch;hydrating&&0===root_index&&hydrate_next();anchor=node;consequent_effect=null;alternate_effect=null;condition=UNINITIALIZED;has_branch=!1;const set_branch=(fn2,flag=!0)=>{has_branch=!0;update_branch(flag,fn2)},update_branch=(new_condition,fn2)=>{if(condition===(condition=new_condition))return;let mismatch=!1;if(hydrating&&-1!==hydrate_index){if(0===root_index){const data=anchor.data;data===HYDRATION_START?hydrate_index=0:data===HYDRATION_START_ELSE?hydrate_index=1/0:(hydrate_index=parseInt(data.substring(1)))!=hydrate_index&&(hydrate_index=condition?1/0:-1)}if(!!condition==hydrate_index>root_index){set_hydrate_node(anchor=remove_nodes());set_hydrating(!1);mismatch=!0;hydrate_index=-1}}if(condition){consequent_effect?resume_effect(consequent_effect):fn2&&(consequent_effect=branch((()=>fn2(anchor))));alternate_effect&&pause_effect(alternate_effect,(()=>{alternate_effect=null}))}else{alternate_effect?resume_effect(alternate_effect):fn2&&(alternate_effect=branch((()=>fn2(anchor,[root_index+1,hydrate_index]))));consequent_effect&&pause_effect(consequent_effect,(()=>{consequent_effect=null}))}mismatch&&set_hydrating(!0)};block((()=>{has_branch=!1;fn(set_branch);has_branch||update_branch(null,null)}),root_index>0?EFFECT_TRANSPARENT:0);hydrating&&(anchor=hydrate_node)}function index(_,i2){return i2}function each(node,flags,get_collection,get_key,render_fn,fallback_fn=null){var parent_node,fallback2,was_empty,each_array,anchor=node,state2={flags,items:new Map,first:null};if(flags&EACH_IS_CONTROLLED){parent_node=node;anchor=hydrating?set_hydrate_node(get_first_child(parent_node)):parent_node.appendChild(create_text())}hydrating&&hydrate_next();fallback2=null;was_empty=!1;each_array=derived_safe_equal((()=>{var collection=get_collection();return is_array(collection)?collection:null==collection?[]:array_from(collection)}));block((()=>{var prev,item,i2,value,key2,array=get(each_array),length=array.length;if(was_empty&&0===length)return;was_empty=0===length;let mismatch=!1;if(hydrating&&anchor.data===HYDRATION_START_ELSE!=(0===length)){set_hydrate_node(anchor=remove_nodes());set_hydrating(!1);mismatch=!0}if(hydrating){prev=null;for(i2=0;i20&&set_hydrate_node(remove_nodes())}hydrating||function reconcile(array,state2,anchor,render_fn,flags,get_key,get_collection){var _a8,_b4,_c3,_d2,seen,to_animate,value,key2,item,i2,start,j2,a2,b3,to_destroy,destroy_length,controlled_anchor,is_animated=!!(flags&EACH_IS_ANIMATED),should_update=!!(flags&(EACH_ITEM_REACTIVE|EACH_INDEX_REACTIVE)),length=array.length,items=state2.items,current=state2.first,prev=null,matched=[],stashed=[];if(is_animated)for(i2=0;i20){controlled_anchor=flags&EACH_IS_CONTROLLED&&0===length?anchor:null;if(is_animated){for(i2=0;i20&&0===transitions.length&&null!==controlled_anchor){(function clear_text_content(node){node.textContent=""})(parent_node=controlled_anchor.parentNode);parent_node.append(controlled_anchor);items_map.clear();link(state2,items[0].prev,items[length-1].next)}run_out_transitions(transitions,(()=>{var i3,item;for(i3=0;i3{var _a9;if(void 0!==to_animate)for(item of to_animate)null==(_a9=item.a)||_a9.apply()}));active_effect.first=state2.first&&state2.first.e;active_effect.last=prev&&prev.e}(array,state2,anchor,render_fn,flags,get_key,get_collection);null!==fallback_fn&&(0===length?fallback2?resume_effect(fallback2):fallback2=branch((()=>fallback_fn(anchor))):null!==fallback2&&pause_effect(fallback2,(()=>{fallback2=null})));mismatch&&set_hydrating(!0);get(each_array)}));hydrating&&(anchor=hydrate_node)}function update_item(item,value,index6,type){type&EACH_ITEM_REACTIVE&&internal_set(item.v,value);type&EACH_INDEX_REACTIVE?internal_set(item.i,index6):item.i=index6}function create_item(anchor,state2,prev,next2,value,key2,index6,render_fn,flags,get_collection){var item,previous_each_item=current_each_item,reactive2=!!(flags&EACH_ITEM_REACTIVE),v2=reactive2?flags&EACH_ITEM_IMMUTABLE?source(value):mutable_source(value):value,i2=flags&EACH_INDEX_REACTIVE?source(index6):index6;dev_fallback_default&&reactive2&&(v2.debug=()=>{var collection_index="number"==typeof i2?index6:i2.v;get_collection()[collection_index]});current_each_item=item={i:i2,v:v2,k:key2,a:null,e:null,prev,next:next2};try{item.e=branch((()=>render_fn(anchor,v2,i2,get_collection)),hydrating);item.e.prev=prev&&prev.e;item.e.next=next2&&next2.e;if(null===prev)state2.first=item;else{prev.next=item;prev.e.next=item.e}if(null!==next2){next2.prev=item;next2.e.prev=item.e}return item}finally{current_each_item=previous_each_item}}function move(item,next2,anchor){for(var next_node,end=item.next?item.next.e.nodes_start:anchor,dest=next2?next2.e.nodes_start:anchor,node=item.e.nodes_start;node!==end;){next_node=get_next_sibling(node);dest.before(node);node=next_node}}function link(state2,prev,next2){if(null===prev)state2.first=next2;else{prev.next=next2;prev.e.next=next2&&next2.e}if(null!==next2){next2.prev=prev;next2.e.prev=prev&&prev.e}}function append_styles(anchor,css){queue_micro_task((()=>{var _a8,root9=anchor.getRootNode(),target=root9.host?root9:null!=(_a8=root9.head)?_a8:root9.ownerDocument.head;if(!target.querySelector("#"+css.hash)){const style=document.createElement("style");style.id=css.hash;style.textContent=css.code;target.appendChild(style);dev_fallback_default&&function register_style(hash2,style){var styles=all_styles.get(hash2);if(!styles){styles=new Set;all_styles.set(hash2,styles)}styles.add(style)}(css.hash,style)}}))}function r(e3){var t3,f4,o2,n3="";if("string"==typeof e3||"number"==typeof e3)n3+=e3;else if("object"==typeof e3)if(Array.isArray(e3)){o2=e3.length;for(t3=0;t3=0;){b3=a2+len;0!==a2&&!whitespace.includes(classname[a2-1])||b3!==classname.length&&!whitespace.includes(classname[b3])?a2=b3:classname=(0===a2?"":classname.substring(0,a2))+classname.substring(b3+1)}}return""===classname?null:classname}(value,hash2,next_classes);hydrating&&next_class_name===dom.getAttribute("class")||(null==next_class_name?dom.removeAttribute("class"):is_html?dom.className=next_class_name:dom.setAttribute("class",next_class_name));dom.__className=value}else if(next_classes&&prev_classes!==next_classes)for(key2 in next_classes){is_present=!!next_classes[key2];null!=prev_classes&&is_present===!!prev_classes[key2]||dom.classList.toggle(key2,is_present)}return next_classes}function remove_input_defaults(input){var already_removed,remove_defaults;if(hydrating){already_removed=!1;remove_defaults=()=>{var value,checked;if(!already_removed){already_removed=!0;if(input.hasAttribute("value")){value=input.value;set_attribute(input,"value",null);input.value=value}if(input.hasAttribute("checked")){checked=input.checked;set_attribute(input,"checked",null);input.checked=checked}}};input.__on_r=remove_defaults;(function queue_idle_task(fn){0===idle_tasks.length&&request_idle_callback(run_idle_tasks);idle_tasks.push(fn)})(remove_defaults);add_form_reset_listener()}}function set_attribute(element2,attribute,value,skip_warning){var attributes=function get_attributes(element2){var _a8;return null!=(_a8=element2.__attributes)?_a8:element2.__attributes={[IS_CUSTOM_ELEMENT]:element2.nodeName.includes("-"),[IS_HTML]:element2.namespaceURI===NAMESPACE_HTML}}(element2);if(hydrating){attributes[attribute]=element2.getAttribute(attribute);if("src"===attribute||"srcset"===attribute||"href"===attribute&&"LINK"===element2.nodeName){skip_warning||function check_src_in_dev_hydration(element2,attribute,value){var _a8;dev_fallback_default&&("srcset"===attribute&&function srcset_url_equal(element2,srcset){var element_urls=split_srcset(element2.srcset),urls=split_srcset(srcset);return urls.length===element_urls.length&&urls.every((([url,width],i2)=>width===element_urls[i2][1]&&(src_url_equal(element_urls[i2][0],url)||src_url_equal(url,element_urls[i2][0]))))}(element2,value)||src_url_equal(null!=(_a8=element2.getAttribute(attribute))?_a8:"",value)||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")}(attribute,element2.outerHTML.replace(element2.innerHTML,element2.innerHTML&&"..."),String(value)))}(element2,attribute,null!=value?value:"");return}}if(attributes[attribute]!==(attributes[attribute]=value)){"loading"===attribute&&(element2[LOADING_ATTR_SYMBOL]=value);null==value?element2.removeAttribute(attribute):"string"!=typeof value&&function get_setters(element2){var descriptors,proto,element_proto,key2,setters=setters_cache.get(element2.nodeName);if(setters)return setters;setters_cache.set(element2.nodeName,setters=[]);proto=element2;element_proto=Element.prototype;for(;element_proto!==proto;){descriptors=get_descriptors(proto);for(key2 in descriptors)descriptors[key2].set&&setters.push(key2);proto=get_prototype_of(proto)}return setters}(element2).includes(attribute)?element2[attribute]=value:element2.setAttribute(attribute,value)}}function src_url_equal(element_src,url){return element_src===url||new URL(element_src,document.baseURI).href===new URL(url,document.baseURI).href}function split_srcset(srcset){return srcset.split(",").map((src=>src.trim().split(" ").filter(Boolean)))}function bind_value(input,get4,set2=get4){var runes=is_runes();listen_to_event_and_reset_event(input,"input",(is_reset=>{var value,start,end;dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();value=is_reset?input.defaultValue:input.value;value=is_numberlike_input(input)?to_number(value):value;set2(value);if(runes&&value!==(value=get4())){start=input.selectionStart;end=input.selectionEnd;input.value=null!=value?value:"";if(null!==end){input.selectionStart=start;input.selectionEnd=Math.min(end,input.value.length)}}}));(hydrating&&input.defaultValue!==input.value||null==untrack(get4)&&input.value)&&set2(is_numberlike_input(input)?to_number(input.value):input.value);render_effect((()=>{dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();var value=get4();is_numberlike_input(input)&&value===to_number(input.value)||("date"!==input.type||value||input.value)&&value!==input.value&&(input.value=null!=value?value:"")}))}function bind_checked(input,get4,set2=get4){listen_to_event_and_reset_event(input,"change",(is_reset=>{var value=is_reset?input.defaultChecked:input.checked;set2(value)}));(hydrating&&input.defaultChecked!==input.checked||null==untrack(get4))&&set2(input.checked);render_effect((()=>{var value=get4();input.checked=Boolean(value)}))}function get_binding_group_value(group,__value,checked){var i2,value=new Set;for(i2=0;i2{var _a8,value,selected_option,query3=is_reset?"[selected]":":checked";value=select.multiple?[].map.call(select.querySelectorAll(query3),get_option_value):(selected_option=null!=(_a8=select.querySelector(query3))?_a8:select.querySelector("option:not([disabled])"))&&get_option_value(selected_option);set2(value)}));effect((()=>{var selected_option,value=get4();select_option(select,value,mounting);if(mounting&&void 0===value&&null!==(selected_option=select.querySelector(":checked"))){value=get_option_value(selected_option);set2(value)}select.__value=value;mounting=!1}));(function init_select(select,get_value){let mounting=!0;effect((()=>{get_value&&select_option(select,untrack(get_value),mounting);mounting=!1;var observer=new MutationObserver((()=>{var value=select.__value;select_option(select,value)}));observer.observe(select,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]});return()=>{observer.disconnect()}}))})(select)}function get_option_value(option){return"__value"in option?option.__value:option.value}function is_bound_this(bound_value,element_or_component){return bound_value===element_or_component||(null==bound_value?void 0:bound_value[STATE_SYMBOL])===element_or_component}function bind_this(element_or_component={},update2,get_value,get_parts){effect((()=>{var old_parts,parts;render_effect((()=>{old_parts=parts;parts=(null==get_parts?void 0:get_parts())||[];untrack((()=>{if(element_or_component!==get_value(...parts)){update2(element_or_component,...parts);old_parts&&is_bound_this(get_value(...old_parts),element_or_component)&&update2(null,...old_parts)}}))}));return()=>{queue_micro_task((()=>{parts&&is_bound_this(get_value(...parts),element_or_component)&&update2(null,...parts)}))}}));return element_or_component}function bind_property(property,event_name,element2,set2,get4){var handler=()=>{set2(element2[property])};element2.addEventListener(event_name,handler);get4?render_effect((()=>{element2[property]=get4()})):handler();element2!==document.body&&element2!==window&&element2!==document||teardown((()=>{element2.removeEventListener(event_name,handler)}))}function init(immutable=!1){const context2=component_context,callbacks=context2.l.u;if(!callbacks)return;let props=()=>deep_read_state(context2.s);if(immutable){let version2=0,prev={};const d4=derived((()=>{let changed=!1;const props2=context2.s;for(const key2 in props2)if(props2[key2]!==prev[key2]){prev[key2]=props2[key2];changed=!0}changed&&version2++;return version2}));props=()=>get(d4)}callbacks.b.length&&function user_pre_effect(fn){validate_effect("$effect.pre");dev_fallback_default&&define_property(fn,"name",{value:"$effect.pre"});render_effect(fn)}((()=>{observe_all(context2,props);run_all(callbacks.b)}));user_effect((()=>{const fns=untrack((()=>callbacks.m.map(run)));return()=>{for(const fn of fns)"function"==typeof fn&&fn()}}));callbacks.a.length&&user_effect((()=>{observe_all(context2,props);run_all(callbacks.a)}))}function observe_all(context2,props){if(context2.l.s)for(const signal of context2.l.s)get(signal);props()}function onMount(fn){null===component_context&&lifecycle_outside_component("onMount");legacy_mode_flag&&null!==component_context.l?function init_update_callbacks(context2){var _a8,l2=context2.l;return null!=(_a8=l2.u)?_a8:l2.u={a:[],b:[],m:[]}}(component_context).m.push(fn):user_effect((()=>{const cleanup=untrack(fn);if("function"==typeof cleanup)return cleanup}))}function onDestroy(fn){null===component_context&&lifecycle_outside_component("onDestroy");onMount((()=>()=>untrack(fn)))}function subscribe_to_store(store,run3,invalidate){if(null==store){run3(void 0);invalidate&&invalidate(void 0);return noop2}const unsub=untrack((()=>store.subscribe(run3,invalidate)));return unsub.unsubscribe?()=>unsub.unsubscribe():unsub}function writable(value,start=noop2){function set2(new_value){if(safe_not_equal(value,new_value)){value=new_value;if(stop){const run_queue=!subscriber_queue.length;for(const subscriber of subscribers){subscriber[1]();subscriber_queue.push(subscriber,value)}if(run_queue){for(let i2=0;i2{subscribers.delete(subscriber);if(0===subscribers.size&&stop){stop();stop=null}}}}}function store_get(store,store_name,stores){var _a8,is_synchronous_callback;const entry=null!=(_a8=stores[store_name])?_a8:stores[store_name]={store:null,source:mutable_source(void 0),unsubscribe:noop2};if(entry.store!==store&&!(IS_UNMOUNTED in stores)){entry.unsubscribe();entry.store=null!=store?store:null;if(null==store){entry.source.v=void 0;entry.unsubscribe=noop2}else{is_synchronous_callback=!0;entry.unsubscribe=subscribe_to_store(store,(v2=>{is_synchronous_callback?entry.source.v=v2:set(entry.source,v2)}));is_synchronous_callback=!1}}return store&&IS_UNMOUNTED in stores?function get2(store){let value;subscribe_to_store(store,(_=>value=_))();return value}(store):get(entry.source)}function setup_stores(){const stores={};return[stores,function cleanup(){teardown((()=>{for(var store_name in stores)stores[store_name].unsubscribe();define_property(stores,IS_UNMOUNTED,{enumerable:!1,value:!0})}))}]}function spread_props(...props){return new Proxy({props},spread_props_handler)}function has_destroyed_component_ctx(current_value){var _a8,_b4;return null!=(_b4=null==(_a8=current_value.ctx)?void 0:_a8.d)&&_b4}function prop(props,key2,flags,fallback2){var _a8,_b4,prop_value,is_entry_props,setter,fallback_value,fallback_dirty,fallback_used,get_fallback,getter,derived_getter,legacy_parent,from_child,was_from_child,inner_current_value,current_value,immutable=!!(flags&PROPS_IS_IMMUTABLE),runes=!legacy_mode_flag||!!(flags&PROPS_IS_RUNES),bindable=!!(flags&PROPS_IS_BINDABLE),lazy=!!(flags&PROPS_IS_LAZY_INITIAL),is_store_sub=!1;bindable?[prop_value,is_store_sub]=function capture_store_binding(fn){var previous_is_store_binding=is_store_binding;try{is_store_binding=!1;return[fn(),is_store_binding]}finally{is_store_binding=previous_is_store_binding}}((()=>props[key2])):prop_value=props[key2];is_entry_props=STATE_SYMBOL in props||LEGACY_PROPS in props;setter=bindable&&(null!=(_b4=null==(_a8=get_descriptor(props,key2))?void 0:_a8.set)?_b4:is_entry_props&&key2 in props&&(v2=>props[key2]=v2))||void 0;fallback_value=fallback2;fallback_dirty=!0;fallback_used=!1;get_fallback=()=>{fallback_used=!0;if(fallback_dirty){fallback_dirty=!1;fallback_value=lazy?untrack(fallback2):fallback2}return fallback_value};if(void 0===prop_value&&void 0!==fallback2){setter&&runes&&function props_invalid_value(key2){if(dev_fallback_default){const error=new Error(`props_invalid_value\nCannot do \`bind:${key2}={undefined}\` when \`${key2}\` 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")}(key2);prop_value=get_fallback();setter&&setter(prop_value)}if(runes)getter=()=>{var value=props[key2];if(void 0===value)return get_fallback();fallback_dirty=!0;fallback_used=!1;return value};else{(derived_getter=(immutable?derived:derived_safe_equal)((()=>props[key2]))).f|=LEGACY_DERIVED_PROP;getter=()=>{var value=get(derived_getter);void 0!==value&&(fallback_value=void 0);return void 0===value?fallback_value:value}}if(!(flags&PROPS_IS_UPDATED))return getter;if(setter){legacy_parent=props.$$legacy;return function(value,mutation){if(arguments.length>0){runes&&mutation&&!legacy_parent&&!is_store_sub||setter(mutation?getter():value);return value}return getter()}}from_child=!1;was_from_child=!1;inner_current_value=mutable_source(prop_value);current_value=derived((()=>{var parent_value=getter(),child_value=get(inner_current_value);if(from_child){from_child=!1;was_from_child=!0;return child_value}was_from_child=!1;return inner_current_value.v=parent_value}));bindable&&get(current_value);immutable||(current_value.equals=safe_equals);return function(value,mutation){if(null!==captured_signals){from_child=was_from_child;getter();get(inner_current_value)}if(arguments.length>0){const new_value=mutation?get(current_value):runes&&bindable?proxy(value):value;if(!current_value.equals(new_value)){from_child=!0;set(inner_current_value,new_value);fallback_used&&void 0!==fallback_value&&(fallback_value=new_value);if(has_destroyed_component_ctx(current_value))return value;untrack((()=>get(current_value)))}return value}return has_destroyed_component_ctx(current_value)?current_value.v:get(current_value)}}function expandKeywords(message,lang,recurseLimit=10){if(recurseLimit<=0){Logger("ExpandKeywords hit the recursion limit, returning the current state. but this is not expected. May recursive referenced.");return message}const keywords=Object.entries(message).map((([key2,value])=>[key2,value[lang]])).map((([key2,value])=>[`${key2.startsWith("K.")?key2.substring(2):key2}`,value])).map((([key2,value])=>[[`%{${key2}}`,value]])).flat().sort(((a2,b3)=>{var _a8,_b4,_c3,_d2;return(null!=(_b4=null==(_a8=a2[1])?void 0:_a8.length)?_b4:0)-(null!=(_d2=null==(_c3=b3[1])?void 0:_c3.length)?_d2:0)})),ret={...message};let isChanged=!1;for(const key2 of Object.keys(message))if(lang in ret[key2])for(const[keyword,replacement]of keywords)if(ret[key2][lang].includes(keyword)){ret[key2][lang]=ret[key2][lang].split(keyword).join(replacement);isChanged=!0}return isChanged?expandKeywords(ret,lang,recurseLimit--):ret}function __onMissingTranslation(callback){__onMissingTranslations=callback}function setLang(lang){if(lang!==currentLang){currentLang=lang;msgCache.clear()}}function _getMessage(key2,lang){var _a8;if(""==key2.trim())return key2;const msgs=null!=(_a8=allMessages[key2])?_a8:void 0;""==lang&&(lang="def");let msg=null==msgs?void 0:msgs[lang];if(!msg){if(!missingTranslations.contains(key2)){__onMissingTranslations(key2);missingTranslations.push(key2)}msg=null==msgs?void 0:msgs.def}return null!=msg?msg:key2}function $t(message,lang){return void 0!==lang?_getMessage(message,lang):function getMessage(key2){if(msgCache.has(key2))return msgCache.get(key2);const msg=_getMessage(key2,currentLang);msgCache.set(key2,msg);return msg}(message)}function $msg(key2,params={},lang){let msg=$t(key2,lang);for(const[placeholder,value]of Object.entries(params)){const regex=new RegExp(`\\\${${placeholder}}`,"g");msg=msg.replace(regex,value)}return msg}function LogPane($$anchor,$$props){function updateLog(logs){const e3=logs.value;if(!get(suspended)){set(messages,[...e3],!0);setTimeout((()=>{scroll&&(scroll.scrollTop=scroll.scrollHeight)}),10)}}var div,div_1,div_2,label,input,span,text2,label_1,input_1,span_1,text_1,label_2,input_2,span_2,text_2,div_3;push($$props,!0);append_styles($$anchor,$$css);let unsubscribe2,scroll,messages=state(proxy([])),wrapRight=state(!1),autoScroll=state(!0),suspended=state(!1);onMount((async()=>{const _logMessages=reactive((()=>logMessages.value));_logMessages.onChanged(updateLog);Logger($msg("logPane.logWindowOpened",{},currentLang));unsubscribe2=()=>_logMessages.offChanged(updateLog)}));onDestroy((()=>{unsubscribe2&&unsubscribe2()}));div_1=child(div=root());div_2=child(div_1);label=child(div_2);remove_input_defaults(input=child(label));span=sibling(input,2);text2=child(span,!0);reset(span);reset(label);remove_input_defaults(input_1=child(label_1=sibling(label,2)));span_1=sibling(input_1,2);text_1=child(span_1,!0);reset(span_1);reset(label_1);remove_input_defaults(input_2=child(label_2=sibling(label_1,2)));span_2=sibling(input_2,2);text_2=child(span_2,!0);reset(span_2);reset(label_2);sibling(label_2,4).__click=[on_click,function closeDialogue(){$$props.close()}];reset(div_2);reset(div_1);each(div_3=sibling(div_1,2),21,(()=>get(messages)),index,(($$anchor2,line)=>{var text_3,pre=root_1();let classes;text_3=child(pre,!0);reset(pre);template_effect(($0=>{classes=set_class(pre,1,"svelte-47tukr",null,classes,$0);set_text(text_3,get(line))}),[()=>({"wrap-right":get(wrapRight)})]);append($$anchor2,pre)}));reset(div_3);bind_this(div_3,($$value=>scroll=$$value),(()=>scroll));reset(div);template_effect((($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2)}),[()=>$msg("logPane.wrap",{},currentLang),()=>$msg("logPane.autoScroll",{},currentLang),()=>$msg("logPane.pause",{},currentLang)]);bind_checked(input,(()=>get(wrapRight)),($$value=>set(wrapRight,$$value)));bind_checked(input_1,(()=>get(autoScroll)),($$value=>set(autoScroll,$$value)));bind_checked(input_2,(()=>get(suspended)),($$value=>set(suspended,$$value)));append($$anchor,div);pop()}function weierstrass(x2){const{a:a2,b:b3}=CURVE,x22=mod(x2*x2),x3=mod(x22*x2);return mod(x3+a2*x2+b3)}function assertJacPoint(other){if(!(other instanceof JacobianPoint))throw new TypeError("JacobianPoint expected")}function constTimeNegate(condition,item){const neg=item.negate();return condition?neg:item}function sliceDER(s2){return Number.parseInt(s2[0],16)>=8?"00"+s2:s2}function parseDERInt(data){if(data.length<2||2!==data[0])throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);const len=data[1],res2=data.subarray(2,len+2);if(!len||res2.length!==len)throw new Error("Invalid signature integer: wrong length");if(0===res2[0]&&res2[1]<=127)throw new Error("Invalid signature integer: trailing length");return{data:bytesToNumber(res2),left:data.subarray(len+2)}}function isBytes(a2){return a2 instanceof Uint8Array||ArrayBuffer.isView(a2)&&"Uint8Array"===a2.constructor.name}function abytes(item){if(!isBytes(item))throw new Error("Uint8Array expected")}function concatBytes(...arrays){arrays.every(abytes);if(1===arrays.length)return arrays[0];const length=arrays.reduce(((a2,arr)=>a2+arr.length),0),result=new Uint8Array(length);for(let i2=0,pad2=0;i2=asciis._0&&ch4<=asciis._9?ch4-asciis._0:ch4>=asciis.A&&ch4<=asciis.F?ch4-(asciis.A-10):ch4>=asciis.a&&ch4<=asciis.f?ch4-(asciis.a-10):void 0}function hexToBytes(hex){if("string"!=typeof hex)throw new Error("hex string expected, got "+typeof hex);const hl=hex.length,al2=hl/2;if(hl%2)throw new Error("hex string expected, got unpadded hex of length "+hl);const array=new Uint8Array(al2);for(let ai2=0,hi=0;ai20)return BigInt(num);if("bigint"==typeof num&&isWithinCurveOrder(num))return num;throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n")}function mod(a2,b3=CURVE.P){const result=a2%b3;return result>=_0n?result:b3+result}function pow2(x2,power){const{P:P2}=CURVE;let res2=x2;for(;power-- >_0n;){res2*=res2;res2%=P2}return res2}function invert(number,modulo=CURVE.P){if(number===_0n||modulo<=_0n)throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);let a2=mod(number,modulo),b3=modulo,x2=_0n,y2=_1n,u2=_1n,v2=_0n;for(;a2!==_0n;){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}if(b3!==_1n)throw new Error("invert: does not exist");return mod(x2,modulo)}function isWithinCurveOrder(num){return _0n0)num=BigInt(key2);else if("string"==typeof key2){if(key2.length!==2*groupLen)throw new Error("Expected 32 bytes of private key");num=hexToNumber(key2)}else{if(!isBytes(key2))throw new TypeError("Expected valid private key");if(key2.length!==groupLen)throw new Error("Expected 32 bytes of private key");num=bytesToNumber(key2)}if(!isWithinCurveOrder(num))throw new Error("Expected private key: 0 < key < n");return num}function normalizePublicKey(publicKey2){if(publicKey2 instanceof Point){publicKey2.assertValidity();return publicKey2}return Point.fromHex(publicKey2)}function schnorrChallengeFinalize(ch4){return mod(bytesToNumber(ch4),CURVE.n)}function initSchnorrVerify(signature,message,publicKey2){const raw=signature instanceof SchnorrSignature,sig=raw?signature:SchnorrSignature.fromHex(signature);raw&&sig.assertValidity();return{...sig,m:ensureBytes(message),P:normalizePublicKey(publicKey2)}}function finalizeSchnorrVerify(r4,P2,s2,e3){const R2=Point.BASE.multiplyAndAddUnsafe(P2,normalizePrivateKey(s2),mod(-e3,CURVE.n));return!(!R2||!R2.hasEvenY()||R2.x!==r4)}async function schnorrVerify(signature,message,publicKey2){try{const{r:r4,s:s2,m:m3,P:P2}=initSchnorrVerify(signature,message,publicKey2),e3=schnorrChallengeFinalize(await utils.taggedHash(TAGS.challenge,numTo32b(r4),P2.toRawX(),m3));return finalizeSchnorrVerify(r4,P2,s2,e3)}catch(error){return!1}}function schnorrVerifySync(signature,message,publicKey2){try{const{r:r4,s:s2,m:m3,P:P2}=initSchnorrVerify(signature,message,publicKey2),e3=schnorrChallengeFinalize(utils.taggedHashSync(TAGS.challenge,numTo32b(r4),P2.toRawX(),m3));return finalizeSchnorrVerify(r4,P2,s2,e3)}catch(error){if(error instanceof ShaError)throw error;return!1}}function getConfirmInstance(){return instance?Promise.resolve(instance):p.promise}function getReplicatorInstance(){return replicatorInstanceGetter()}function setReplicatorFunc(func){replicatorInstanceGetter=func}async function upsert(db,id,func){try{const updated=func(await db.get(id)),result=await db.put(updated,{});if(result&&result.ok)return updated;throw new Error("Failed to update")}catch(ex){if("not_found"===ex.name){const result=await db.put(func({_id:id}),{});if(result&&result.ok)return func({_id:id});throw new Error("Failed to insert")}throw ex}}async function passphraseToKeyMaterial(passphrase){return await crypto.subtle.importKey("raw",(new TextEncoder).encode(passphrase),{name:"PBKDF2"},!1,["deriveBits"])}async function generateIV(keyMaterial,salt,iterations=1e5){return await crypto.subtle.deriveBits({name:"PBKDF2",salt,iterations,hash:"SHA-256"},keyMaterial,384)}async function generateOpenSSLCompatIvKey(passphrase,salt,iterations=1e5,usage="decrypt"){const keyMaterial=await passphraseToKeyMaterial(passphrase),keyIv=await generateIV(keyMaterial,salt,iterations);return{key:await crypto.subtle.importKey("raw",keyIv.slice(0,KEY_LENGTH),{name:ALGORITHM_NAME},!1,[usage]),iv:keyIv.slice(KEY_LENGTH)}}async function encryptCBC(plaintext,passphrase,iterations=1e5){const salt=crypto.getRandomValues(new Uint8Array(SALT_LENGTH)),{key:key2,iv}=await generateOpenSSLCompatIvKey(passphrase,salt,iterations,"encrypt"),encrypted=await crypto.subtle.encrypt({name:ALGORITHM_NAME,iv},key2,plaintext),result=new Uint8Array(SALT_PREFIX.length+SALT_LENGTH+encrypted.byteLength);result.set(SALT_PREFIX,0);result.set(salt,SALT_PREFIX.length);result.set(new Uint8Array(encrypted),SALT_PREFIX.length+SALT_LENGTH);return result}async function decryptCBC(encryptedData,passphrase,iterations=1e5){if(encryptedData.lengthv2===SALT_PREFIX[i2])))throw new Error("Invalid encrypted data format");const salt=encryptedData.slice(SALT_PREFIX.length,SALT_PREFIX.length+SALT_LENGTH),ciphertext=encryptedData.slice(SALT_PREFIX.length+SALT_LENGTH),{key:key2,iv}=await generateOpenSSLCompatIvKey(passphrase,salt,iterations,"decrypt"),decrypted=await crypto.subtle.decrypt({name:ALGORITHM_NAME,iv},key2,ciphertext);return new Uint8Array(decrypted)}async function getHashedStringWithCurrentTime(source2){const salt=(~~((new Date).getTime()/1e3/180)).toString(36),salt2=await sha1(salt);return await sha1(salt2+source2)}function apply2(__1,docA,docB,mode,callback,docToString,objBA,objAB){if(get(docA)&&get(docB)){if(get(docA)._id==get(docB)._id){if("A"==get(mode))return callback()(get(docA)._rev,void 0);if("B"==get(mode))return callback()(get(docB)._rev,void 0)}else{if("A"==get(mode))return callback()(void 0,docToString(get(docA)));if("B"==get(mode))return callback()(void 0,docToString(get(docB)))}if("BA"==get(mode))return callback()(void 0,JSON.stringify(get(objBA),null,2));if("AB"==get(mode))return callback()(void 0,JSON.stringify(get(objAB),null,2));callback()(void 0,void 0)}}function cancel(__2,callback){callback()(void 0,void 0)}function JsonResolvePane($$anchor,$$props){function parseJson(json){if(!1===json)return!1;try{return JSON.parse(json)}catch(ex){return!1}}function docToString(doc){return"plain"==doc.datatype?getDocData(doc.data):readString(new Uint8Array(decodeBinary(doc.data)))}function revStringToRevNumber(rev3){return rev3?rev3.split("-")[0]:""}var fragment,h22,text2,node,consequent,alternate;push($$props,!0);append_styles($$anchor,$$css2);const binding_group=[];let docs=prop($$props,"docs",27,(()=>proxy([]))),callback=prop($$props,"callback",11,(async(_,__)=>{Promise.resolve()})),filename=prop($$props,"filename",11,""),nameA=prop($$props,"nameA",11,"A"),nameB=prop($$props,"nameB",11,"B"),defaultSelect=prop($$props,"defaultSelect",11,""),keepOrder=prop($$props,"keepOrder",11,!1),hideLocal=prop($$props,"hideLocal",11,!1);const docsArray=user_derived((()=>docs()&&docs().length>=1?keepOrder()||docs()[0].mtimeget(docsArray).a)),docB=user_derived((()=>get(docsArray).b)),docAContent=user_derived((()=>get(docA)&&docToString(get(docA)))),docBContent=user_derived((()=>get(docB)&&docToString(get(docB)))),objA=user_derived((()=>parseJson(get(docAContent))||{})),objB=user_derived((()=>parseJson(get(docBContent))||{})),objAB=user_derived((()=>mergeObject(get(objA),get(objB)))),objBAw=user_derived((()=>mergeObject(get(objB),get(objA)))),objBA=user_derived((()=>!!isObjectDifferent(get(objBAw),get(objAB))&&get(objBAw)));let diffs=user_derived((()=>get(objA)&&get(selectedObj)?function getJsonDiff(a2,b3){return function getDiff(left,right){const dmp=new import_diff_match_patch.diff_match_patch,mapLeft=dmp.diff_linesToChars_(left,right),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);return diffLeftSrc}(JSON.stringify(a2,null,2),JSON.stringify(b3,null,2))}(get(objA),get(selectedObj)):[])),mode=state(proxy(defaultSelect()));const mergedObjs=user_derived((()=>({"":!1,A:get(objA),B:get(objB),AB:get(objAB),BA:get(objBA)})));let selectedObj=user_derived((()=>get(mode)in get(mergedObjs)?get(mergedObjs)[get(mode)]:{}));proxy([]);const modes=user_derived((()=>{let newModes=[];if(!hideLocal()){newModes.push(["","Not now"]);newModes.push(["A",nameA()||"A"])}newModes.push(["B",nameB()||"B"]);newModes.push(["AB",`${nameA()||"A"} + ${nameB()||"B"}`]);newModes.push(["BA",`${nameB()||"B"} + ${nameA()||"A"}`]);return newModes}));h22=first_child(fragment=root2());text2=child(h22,!0);reset(h22);node=sibling(h22,2);consequent=$$anchor2=>{var fragment_1=root_12(),div=sibling(first_child(fragment_1),2);child(div).__click=[apply2,docA,docB,mode,callback,docToString,objBA,objAB];reset(div);append($$anchor2,fragment_1)};alternate=$$anchor2=>{var node_2,consequent_2,alternate_1,div_4,table2,tbody,tr,th,text_4,td3,node_3,consequent_3,text_6,td_1,text_7,tr_1,th_1,text_8,td_2,node_4,consequent_4,text_10,td_3,text_11,div_5,node_5,consequent_5,fragment_2=root_2(),div_1=first_child(fragment_2);each(div_1,21,(()=>get(modes)),index,(($$anchor3,m3)=>{var fragment_3=comment(),node_1=first_child(fragment_3),consequent_1=$$anchor4=>{var input_value,div_2,text_1,label=root_4(),input=child(label);remove_input_defaults(input);div_2=sibling(input,2);text_1=child(div_2,!0);reset(div_2);reset(label);template_effect((()=>{var _a8;set_class(label,1,"sls-setting-label "+(get(m3)[0]==get(mode)?"selected":""),"svelte-dk5958");input_value!==(input_value=get(m3)[0])&&(input.value=null!=(_a8=input.__value=get(m3)[0])?_a8:"");set_text(text_1,get(m3)[1])}));(function bind_group(inputs,group_index,input,get4,set2=get4){var _a8,index6,is_checkbox="checkbox"===input.getAttribute("type"),binding_group=inputs;let hydration_mismatch2=!1;if(null!==group_index)for(index6 of group_index)binding_group=null!=(_a8=binding_group[index6])?_a8:binding_group[index6]=[];binding_group.push(input);listen_to_event_and_reset_event(input,"change",(()=>{var value=input.__value;is_checkbox&&(value=get_binding_group_value(binding_group,value,input.checked));set2(value)}),(()=>set2(is_checkbox?[]:null)));render_effect((()=>{var value=get4();if(hydrating&&input.defaultChecked!==input.checked)hydration_mismatch2=!0;else if(is_checkbox){value=value||[];input.checked=value.includes(input.__value)}else input.checked=is(input.__value,value)}));teardown((()=>{var index7=binding_group.indexOf(input);-1!==index7&&binding_group.splice(index7,1)}));if(!pending.has(binding_group)){pending.add(binding_group);queue_micro_task((()=>{binding_group.sort(((a2,b3)=>4===a2.compareDocumentPosition(b3)?-1:1));pending.delete(binding_group)}))}queue_micro_task((()=>{var value,hydration_input;if(hydration_mismatch2){value=is_checkbox?get_binding_group_value(binding_group,value,input.checked):null==(hydration_input=binding_group.find((input2=>input2.checked)))?void 0:hydration_input.__value;set2(value)}}))})(binding_group,[],input,(()=>{get(m3)[0];return get(mode)}),($$value=>set(mode,$$value)));append($$anchor4,label)};if_block(node_1,($$render=>{""!=get(m3)[0]&&0==get(mergedObjs)[get(m3)[0]]||$$render(consequent_1)}));append($$anchor3,fragment_3)}));reset(div_1);node_2=sibling(div_1,2);consequent_2=$$anchor3=>{var div_3=root_5();each(div_3,21,(()=>get(diffs)),index,(($$anchor4,diff)=>{var span=root_6(),text_2=child(span,!0);reset(span);template_effect((()=>{set_class(span,1,clsx2(get(diff)[0]==import_diff_match_patch.DIFF_DELETE?"deleted":get(diff)[0]==import_diff_match_patch.DIFF_INSERT?"added":"normal"),"svelte-dk5958");set_text(text_2,get(diff)[1])}));append($$anchor4,span)}));reset(div_3);append($$anchor3,div_3)};alternate_1=$$anchor3=>{append($$anchor3,text("NO PREVIEW"))};if_block(node_2,($$render=>{0!=get(selectedObj)?$$render(consequent_2):$$render(alternate_1,!1)}));table2=child(div_4=sibling(node_2,2));tbody=child(table2);tr=child(tbody);th=child(tr);text_4=child(th,!0);reset(th);node_3=child(td3=sibling(th));consequent_3=$$anchor3=>{var text_5=text();template_effect(($0=>set_text(text_5,`Rev:${null!=$0?$0:""}`)),[()=>revStringToRevNumber(get(docA)._rev)]);append($$anchor3,text_5)};if_block(node_3,($$render=>{get(docA)._id==get(docB)._id&&$$render(consequent_3)}));text_6=sibling(node_3);reset(td3);td_1=sibling(td3);text_7=child(td_1);reset(td_1);reset(tr);th_1=child(tr_1=sibling(tr));text_8=child(th_1,!0);reset(th_1);node_4=child(td_2=sibling(th_1));consequent_4=$$anchor3=>{var text_9=text();template_effect(($0=>set_text(text_9,`Rev:${null!=$0?$0:""}`)),[()=>revStringToRevNumber(get(docB)._rev)]);append($$anchor3,text_9)};if_block(node_4,($$render=>{get(docA)._id==get(docB)._id&&$$render(consequent_4)}));text_10=sibling(node_4);reset(td_2);td_3=sibling(td_2);text_11=child(td_3);reset(td_3);reset(tr_1);reset(tbody);reset(table2);reset(div_4);node_5=child(div_5=sibling(div_4,2));consequent_5=$$anchor3=>{var button_1=root_10();button_1.__click=[cancel,callback];append($$anchor3,button_1)};if_block(node_5,($$render=>{hideLocal()&&$$render(consequent_5)}));sibling(node_5,2).__click=[apply2,docA,docB,mode,callback,docToString,objBA,objAB];reset(div_5);template_effect((($0,$1)=>{var _a8,_b4;set_text(text_4,nameA());set_text(text_6,` ${null!=$0?$0:""}`);set_text(text_7,`${null!=(_a8=get(docAContent)&&get(docAContent).length)?_a8:""} letters`);set_text(text_8,nameB());set_text(text_10,` ${null!=$1?$1:""}`);set_text(text_11,`${null!=(_b4=get(docBContent)&&get(docBContent).length)?_b4:""} letters`)}),[()=>new Date(get(docA).mtime).toLocaleString(),()=>new Date(get(docB).mtime).toLocaleString()]);append($$anchor2,fragment_2)};if_block(node,($$render=>{get(docA)&&get(docB)?$$render(alternate,!1):$$render(consequent)}));template_effect((()=>set_text(text2,filename())));append($$anchor,fragment);pop()}function getComparingMTime(doc,includeDeleted=!1){var _a8,_b4,_c3;if(null===doc)return 0;if(!1===doc)return 0;if(void 0===doc)return 0;if(!includeDeleted){if("deleted"in doc&&doc.deleted)return 0;if("_deleted"in doc&&doc._deleted)return 0}return"stat"in doc?null!=(_b4=null==(_a8=doc.stat)?void 0:_a8.mtime)?_b4:0:null!=(_c3=doc.mtime)?_c3:0}function PluginCombo($$anchor,$$props){async function comparePlugin(local,remote){var _a8,_b4;let freshness2="",version3="",contentCheck=!1,canApply2=!1;if(local||remote)if(local&&!remote)freshness2="Local only";else if(remote&&!local){freshness2="Remote only";canApply2=!0}else{const dtDiff=(null!==(_a8=null==local?void 0:local.mtime)&&void 0!==_a8?_a8:0)-(null!==(_b4=null==remote?void 0:remote.mtime)&&void 0!==_b4?_b4:0),diff=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`}(Math.abs(dtDiff));if(dtDiff/1e3<-10){freshness2=`Newer (${diff})`;canApply2=!0;contentCheck=!0}else if(dtDiff/1e3>10){freshness2=`Older (${diff})`;canApply2=!0;contentCheck=!0}else{freshness2="Same";canApply2=!1;contentCheck=!0}}else freshness2="";const localVersionStr=(null==local?void 0:local.version)||"0.0.0",remoteVersionStr=(null==remote?void 0:remote.version)||"0.0.0";if((null==local?void 0:local.version)||(null==remote?void 0:remote.version)){const compare3=`${localVersionStr}`.localeCompare(remoteVersionStr,void 0,{numeric:!0});0==compare3?version3="Same":compare3<0?version3=`Lower (${localVersionStr} < ${remoteVersionStr})`:compare3>0&&(version3=`Higher (${localVersionStr} > ${remoteVersionStr})`)}if(contentCheck&&local&&remote){const{canApply:canApply3,equivalency:equivalency3,canCompare:canCompare3}=await async function checkEquivalency(local,remote){let equivalency2="",canApply2=!1,canCompare2=!1;const matchingStatus=[...new Set([...local.files.map((e3=>e3.filename)),...remote.files.map((e3=>e3.filename))])].map((filename=>{const localFile=local.files.find((e3=>e3.filename==filename)),remoteFile=remote.files.find((e3=>e3.filename==filename));return localFile||remoteFile?localFile&&!remoteFile?2:!localFile&&remoteFile?8:localFile&&remoteFile&&getDocData(localFile.data)==getDocData(remoteFile.data)?4:16:0})).reduce(((p4,c3)=>p4|c3),0);if(4==matchingStatus){equivalency2="Same";canApply2=!1}else if(matchingStatus<=4){equivalency2="Same or local only";canApply2=!1}else if(16==matchingStatus){canApply2=!0;canCompare2=!0;equivalency2="Different"}else{canApply2=!0;canCompare2=!0;equivalency2="Mixed"}return{equivalency:equivalency2,canApply:canApply2,canCompare:canCompare2}}(local,remote);return{canApply:canApply3,freshness:freshness2,equivalency:equivalency3,version:version3,canCompare:canCompare3}}return{canApply:canApply2,freshness:freshness2,equivalency:"",version:version3,canCompare:!1}}async function applySelected(){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));selectedItem&&await applyData()(selectedItem)&&addOn.updatePluginList(!0,null==local?void 0:local.documentPath)}async function compareSelected(){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));await compareItems(local,selectedItem)}async function compareItems(local,remote,filename){if(local&&remote){if(!filename){await compareData()(local,remote)&&addOn.updatePluginList(!0,local.documentPath);return}{const localCopy=local instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(local):{...local},remoteCopy=remote instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(remote):{...remote};localCopy.files=localCopy.files.filter((e3=>e3.filename==filename));remoteCopy.files=remoteCopy.files.filter((e3=>e3.filename==filename));await compareData()(localCopy,remoteCopy,!0)&&addOn.updatePluginList(!0,local.documentPath)}}else remote||local?remote?local||Logger("Could not locally item",LOG_LEVEL_INFO):Logger("Could not find remote item",LOG_LEVEL_INFO):Logger("Could not find both remote and local item",LOG_LEVEL_INFO)}async function pickCompareItem(evt){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));if(!local)return;if(!selectedItem)return;const menu=new import_obsidian5.Menu;menu.addItem((item=>item.setTitle("Compare file").setIsLabel(!0)));menu.addSeparator();const files=unique(local.files.map((e3=>e3.filename)).concat(selectedItem.files.map((e3=>e3.filename)))),convDate=dt=>dt?new Date(dt.mtime).toLocaleString():"(Missing)";for(const filename of files)menu.addItem((item=>{const localFile=local.files.find((e3=>e3.filename==filename)),remoteFile=selectedItem.files.find((e3=>e3.filename==filename)),title=`${filename} (${convDate(localFile)} <--\x3e ${convDate(remoteFile)})`;item.setTitle(title).onClick((e3=>compareItems(local,selectedItem,filename)))}));menu.showAtMouseEvent(evt)}async function deleteSelected(){const selectedItem=list().find((e3=>e3.term==selected()));selectedItem&&await deleteData()(selectedItem)&&addOn.reloadPluginList(!0)}async function duplicateItem(){const local=list().find((e3=>e3.term==thisTerm()));if(!local){Logger("Could not find local item",LOG_LEVEL_VERBOSE);return}const duplicateTermName=await plugin3().confirm.askString("Duplicate","device name","");if(duplicateTermName){if(duplicateTermName.contains("/")){Logger('We can not use "/" to the device name',LOG_LEVEL_NOTICE);return}const key2=`${plugin3().app.vault.configDir}/${local.files[0].filename}`;await addOn.storeCustomizationFiles(key2,duplicateTermName);await addOn.updatePluginList(!1,addOn.filenameToUnifiedKey(key2,duplicateTermName))}}var fragment,node,consequent_6,alternate_4;push($$props,!1);append_styles($$anchor,$$css3);let list=prop($$props,"list",24,(()=>[])),thisTerm=prop($$props,"thisTerm",8,""),hideNotApplicable=prop($$props,"hideNotApplicable",8,!1),selectNewest=prop($$props,"selectNewest",8,0),selectNewestStyle=prop($$props,"selectNewestStyle",8,0),applyAllPluse=prop($$props,"applyAllPluse",8,0),applyData=prop($$props,"applyData",8),compareData=prop($$props,"compareData",8),deleteData=prop($$props,"deleteData",8),hidden=prop($$props,"hidden",8),plugin3=prop($$props,"plugin",8),isMaintenanceMode=prop($$props,"isMaintenanceMode",8,!1),isFlagged=prop($$props,"isFlagged",8,!1);const addOn=plugin3().getAddOn(ConfigSync.name);if(!addOn){Logger(`Could not load the add-on ${ConfigSync.name}`,LOG_LEVEL_INFO);throw new Error(`Could not load the add-on ${ConfigSync.name}`)}let selected=prop($$props,"selected",12,""),freshness=mutable_source(""),equivalency=mutable_source(""),version2=mutable_source(""),canApply=mutable_source(!1),canCompare=mutable_source(!1),pickToCompare=mutable_source(!1),currentSelectNewest=mutable_source(0),currentApplyAll=mutable_source(0),terms=mutable_source([]);legacy_pre_effect((()=>(deep_read_state(selectNewest()),get(currentSelectNewest),deep_read_state(selectNewestStyle()),deep_read_state(isFlagged()),deep_read_state(list()),deep_read_state(isMaintenanceMode()))),(()=>{let doSelectNewest=!1;selectNewest()!=get(currentSelectNewest)&&(1==selectNewestStyle()?doSelectNewest=!0:2==selectNewestStyle()?doSelectNewest=isFlagged():3==selectNewestStyle()&&selected(""));(async function updateTerms(list2,selectNewest2,isMaintenanceMode2){const local=list2.find((e3=>e3.term==thisTerm()));if(isMaintenanceMode2)set(terms,[...new Set(list2.map((e3=>e3.term)))]);else if(hideNotApplicable()){const termsTmp=[],wk2=[...new Set(list2.map((e3=>e3.term)))];for(const termName of wk2){const remote=list2.find((e3=>e3.term==termName));(await comparePlugin(local,remote)).canApply&&termsTmp.push(termName)}set(terms,[...termsTmp])}else set(terms,[...new Set(list2.map((e3=>e3.term)))].filter((e3=>e3!=thisTerm())));let newest=local;if(selectNewest2){for(const term of get(terms)){const remote=list2.find((e3=>e3.term==term));remote&&remote.mtime&&((null==newest?void 0:newest.mtime)||0)(deep_read_state(applyAllPluse()),get(currentApplyAll),deep_read_state(selected()),deep_read_state(hidden()))),(()=>{const doApply=applyAllPluse()!=get(currentApplyAll);set(currentApplyAll,applyAllPluse());doApply&&selected()&&(hidden()||applySelected())}));legacy_pre_effect((()=>(deep_read_state(selected()),deep_read_state(thisTerm()),deep_read_state(list()))),(()=>{set(freshness,"");set(equivalency,"");set(version2,"");set(canApply,!1);if(""==selected());else if(selected()==thisTerm()){set(freshness,"This device");set(canApply,!1)}else(async function performCompare(local,remote){const result=await comparePlugin(local,remote);set(canApply,result.canApply);set(freshness,result.freshness);set(equivalency,result.equivalency);set(version2,result.version);set(canCompare,result.canCompare);set(pickToCompare,!1);get(canCompare)&&((null==local?void 0:local.files.length)==(null==remote?void 0:remote.files.length)&&1==(null==local?void 0:local.files.length)&&(null==local?void 0:local.files[0].filename)==(null==remote?void 0:remote.files[0].filename)?set(pickToCompare,!1):set(pickToCompare,!0))})(list().find((e3=>e3.term==thisTerm())),list().find((e3=>e3.term==selected())))}));legacy_pre_effect_reset();init();node=first_child(fragment=comment());consequent_6=$$anchor2=>{var fragment_1=root_13(),node_1=sibling(first_child(fragment_1),2),consequent_5=$$anchor3=>{var span_2,text_1,span_3,text_2,select,option,node_3,consequent_2,alternate_2,node_6,consequent_4,fragment_2=root_22(),span=first_child(fragment_2),span_1=child(span),text2=child(span_1,!0);reset(span_1);span_2=sibling(span_1,2);text_1=child(span_2,!0);reset(span_2);span_3=sibling(span_2,2);text_2=child(span_3,!0);reset(span_3);reset(span);select=sibling(span,2);template_effect((()=>{selected();invalidate_inner_signals((()=>{get(terms)}))}));(option=child(select)).value=option.__value="";each(sibling(option),1,(()=>get(terms)),index,(($$anchor4,term)=>{var option_1=root_3(),option_1_value={},text_3=child(option_1,!0);reset(option_1);template_effect((()=>{var _a8;option_1_value!==(option_1_value=get(term))&&(option_1.value=null!=(_a8=option_1.__value=get(term))?_a8:"");set_text(text_3,get(term))}));append($$anchor4,option_1)}));reset(select);node_3=sibling(select,2);consequent_2=$$anchor4=>{var fragment_3=root_42(),node_4=first_child(fragment_3),consequent_1=$$anchor5=>{var fragment_4=comment(),node_5=first_child(fragment_4),consequent=$$anchor6=>{var button=root_62();event("click",button,pickCompareItem);append($$anchor6,button)},alternate=$$anchor6=>{var button_1=root_7();event("click",button_1,compareSelected);append($$anchor6,button_1)};if_block(node_5,($$render=>{get(pickToCompare)?$$render(consequent):$$render(alternate,!1)}));append($$anchor5,fragment_4)},alternate_1=$$anchor5=>{append($$anchor5,root_8())};if_block(node_4,($$render=>{get(canCompare)?$$render(consequent_1):$$render(alternate_1,!1)}));event("click",sibling(node_4,2),applySelected);append($$anchor4,fragment_3)};alternate_2=$$anchor4=>{var fragment_5=root_9();next(2);append($$anchor4,fragment_5)};if_block(node_3,($$render=>{get(canApply)||isMaintenanceMode()&&""!=selected()?$$render(consequent_2):$$render(alternate_2,!1)}));node_6=sibling(node_3,2);consequent_4=$$anchor4=>{var fragment_6=comment(),node_7=first_child(fragment_6),consequent_3=$$anchor5=>{var button_4=root_11();event("click",button_4,deleteSelected);append($$anchor5,button_4)},alternate_3=$$anchor5=>{var button_5=root_122();event("click",button_5,duplicateItem);append($$anchor5,button_5)};if_block(node_7,($$render=>{""!=selected()?$$render(consequent_3):$$render(alternate_3,!1)}));append($$anchor4,fragment_6)};if_block(node_6,($$render=>{isMaintenanceMode()&&$$render(consequent_4)}));template_effect((()=>{set_text(text2,get(freshness));set_text(text_1,get(equivalency));set_text(text_2,get(version2))}));bind_select_value(select,selected);append($$anchor3,fragment_2)};if_block(node_1,($$render=>{hidden()||$$render(consequent_5)}));append($$anchor2,fragment_1)};alternate_4=$$anchor2=>{var fragment_7=root_132();next(6);append($$anchor2,fragment_7)};if_block(node,($$render=>{get(terms).length>0?$$render(consequent_6):$$render(alternate_4,!1)}));append($$anchor,fragment);pop()}function PluginPane($$anchor,$$props){async function requestUpdate(){await addOn.updatePluginList(!0)}function filterList(list2,categories){return list2.filter((e3=>-1!==categories.indexOf(e3.category))).sort(((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`)))}function selectAllNewest(selectMode){update(selectNewestPulse);set(selectNewestStyle,selectMode?1:2)}async function applyData(data){return await addOn.applyData(data)}async function compareData(docA,docB,compareEach=!1){return await addOn.compareUsingDisplayData(docA,docB,compareEach)}async function deleteData(data){return await addOn.deleteData(data)}function askMode(evt,title,key2){var _a8;const menu=new import_obsidian6.Menu;menu.addItem((item=>item.setTitle(title).setIsLabel(!0)));menu.addSeparator();const prevMode=null!==(_a8=automaticList.get(key2))&&void 0!==_a8?_a8:MODE_SELECTIVE;for(const mode of[MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY])menu.addItem((item=>{item.setTitle(`${getIcon(mode)}:${TITLES[mode]}`).onClick((e3=>{mode===MODE_AUTOMATIC?askOverwriteModeForAutomatic(evt,key2):setMode(key2,mode)})).setChecked(prevMode==mode).setDisabled(prevMode==mode)}));menu.showAtMouseEvent(evt)}function applyAutomaticSync(key2,direction){var _a8,_b4;setMode(key2,MODE_AUTOMATIC);const configDir=normalizePath(plugin3().app.vault.configDir),files=(null!==(_b4=null===(_a8=plugin3().settings.pluginSyncExtendedSetting[key2])||void 0===_a8?void 0:_a8.files)&&void 0!==_b4?_b4:[]).map((e3=>`${configDir}/${e3}`));addOnHiddenFileSync.initialiseInternalFileSync(direction,!0,files)}function askOverwriteModeForAutomatic(evt,key2){const menu=new import_obsidian6.Menu;menu.addItem((item=>item.setTitle("Initial Action").setIsLabel(!0)));menu.addSeparator();menu.addItem((item=>{item.setTitle("↑: Overwrite Remote").onClick((e3=>{applyAutomaticSync(key2,"pushForce")}))})).addItem((item=>{item.setTitle("↓: Overwrite Local").onClick((e3=>{applyAutomaticSync(key2,"pullForce")}))})).addItem((item=>{item.setTitle("⇅: Use newer").onClick((e3=>{applyAutomaticSync(key2,"safe")}))}));menu.showAtMouseEvent(evt)}function setMode(key2,mode){if(key2.startsWith(PREFIX_PLUGIN_ALL+"/")){setMode(PREFIX_PLUGIN_DATA+key2.substring(PREFIX_PLUGIN_ALL.length),mode);setMode(PREFIX_PLUGIN_MAIN+key2.substring(PREFIX_PLUGIN_ALL.length),mode);return}const files=unique(get(list).filter((e3=>`${e3.category}/${e3.name}`==key2)).map((e3=>e3.files)).flat().map((e3=>e3.filename)));if(mode==MODE_SELECTIVE){automaticList.delete(key2);delete plugin3().settings.pluginSyncExtendedSetting[key2];set(automaticListDisp,automaticList)}else{automaticList.set(key2,mode);set(automaticListDisp,automaticList);key2 in plugin3().settings.pluginSyncExtendedSetting||plugin3(plugin3().settings.pluginSyncExtendedSetting[key2]={key:key2,mode,files:[]},!0);plugin3(plugin3().settings.pluginSyncExtendedSetting[key2].files=files,!0);plugin3(plugin3().settings.pluginSyncExtendedSetting[key2].mode=mode,!0)}plugin3().$$saveSettingData()}function getIcon(mode){if(mode in ICONS)return ICONS[mode]}var fragment,div,div_1,button,button_1,button_2,node,consequent,div_2,button_4,button_5,button_6,button_7,div_3,node_1,consequent_1,div_4,node_2,consequent_2,alternate,node_13,consequent_10,div_32,label_1,input,div_33,label_2,input_1;push($$props,!1);append_styles($$anchor,$$css4);const[$$stores,$$cleanup]=setup_stores(),$pluginManifestStore=()=>store_get(pluginManifestStore,"$pluginManifestStore",$$stores),$pluginV2Progress=()=>store_get(pluginV2Progress,"$pluginV2Progress",$$stores),hideNotApplicable=mutable_source(),thisTerm=mutable_source(),options=mutable_source();let plugin3=prop($$props,"plugin",12);const addOn=plugin3().getAddOn(ConfigSync.name);if(!addOn){const msg="AddOn Module (ConfigSync) has not been loaded. This is very unexpected situation. Please report this issue.";Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}const addOnHiddenFileSync=plugin3().getAddOn(HiddenFileSync.name);if(!addOnHiddenFileSync){const msg="AddOn Module (HiddenFileSync) has not been loaded. This is very unexpected situation. Please report this issue.";Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}let list=mutable_source([]),selectNewestPulse=mutable_source(0),selectNewestStyle=mutable_source(0),hideEven=mutable_source(!1),loading=mutable_source(!1),applyAllPluse=mutable_source(0),isMaintenanceMode=mutable_source(!1),allTerms=mutable_source([]);pluginList.subscribe((e3=>{set(list,e3);set(allTerms,unique(get(list).map((e4=>e4.term))))}));pluginIsEnumerating.subscribe((e3=>{set(loading,e3)}));onMount((async()=>{requestUpdate()}));const displays={CONFIG:"Configuration",THEME:"Themes",SNIPPET:"Snippets"},ICONS={[MODE_SELECTIVE]:"🔀",[MODE_PAUSED]:"⛔",[MODE_AUTOMATIC]:"✨",[MODE_SHINY]:"🚩"},TITLES={[MODE_SELECTIVE]:"Selective",[MODE_PAUSED]:"Ignore",[MODE_AUTOMATIC]:"Automatic",[MODE_SHINY]:"Flagged Selective"},PREFIX_PLUGIN_ALL="PLUGIN_ALL",PREFIX_PLUGIN_DATA="PLUGIN_DATA",PREFIX_PLUGIN_MAIN="PLUGIN_MAIN";let automaticList=new Map,automaticListDisp=mutable_source(new Map);for(const{key:key2,mode}of Object.values(plugin3().settings.pluginSyncExtendedSetting))automaticList.set(key2,mode);set(automaticListDisp,automaticList);let displayKeys=mutable_source({}),deleteTerm=mutable_source(""),nameMap=mutable_source(new Map),displayEntries=mutable_source([]),pluginEntries=mutable_source([]),useSyncPluginEtc=plugin3().settings.usePluginEtc;legacy_pre_effect((()=>{}),(()=>{set(hideNotApplicable,!1)}));legacy_pre_effect((()=>deep_read_state(plugin3())),(()=>{set(thisTerm,plugin3().$$getDeviceAndVaultName())}));legacy_pre_effect((()=>(get(thisTerm),get(hideNotApplicable),get(selectNewestPulse),get(selectNewestStyle),get(applyAllPluse),deep_read_state(plugin3()),get(isMaintenanceMode))),(()=>{set(options,{thisTerm:get(thisTerm),hideNotApplicable:get(hideNotApplicable),selectNewest:get(selectNewestPulse),selectNewestStyle:get(selectNewestStyle),applyAllPluse:get(applyAllPluse),applyData,compareData,deleteData,plugin:plugin3(),isMaintenanceMode:get(isMaintenanceMode)})}));legacy_pre_effect((()=>get(list)),(()=>{set(displayKeys,function computeDisplayKeys(list2){return[...list2,...Object.keys(plugin3().settings.pluginSyncExtendedSetting).map((e3=>`${e3}///`.split("/"))).filter((e3=>e3[0]&&e3[1])).map((e3=>({category:e3[0],name:e3[1],displayName:e3[1]})))].sort(((a2,b3)=>{var _a8,_b4;return(null!==(_a8=a2.displayName)&&void 0!==_a8?_a8:a2.name).localeCompare(null!==(_b4=b3.displayName)&&void 0!==_b4?_b4:b3.name)})).reduce(((p4,c3)=>{var _a8,_b4;return{...p4,[c3.category]:unique(c3.category in p4?[...p4[c3.category],null!==(_a8=c3.displayName)&&void 0!==_a8?_a8:c3.name]:[null!==(_b4=c3.displayName)&&void 0!==_b4?_b4:c3.name])}}),{})}(get(list)))}));legacy_pre_effect((()=>$pluginManifestStore()),(()=>{(function updateNameMap(e3){const items=[...e3.entries()].map((([k2,v2])=>[k2.split("/").slice(-2).join("/"),v2.name])),newMap=new Map(items);if(newMap.size==get(nameMap).size){let diff=!1;for(const[k2,v2]of newMap)if(get(nameMap).get(k2)!=v2){diff=!0;break}if(!diff)return}set(nameMap,newMap)})($pluginManifestStore())}));legacy_pre_effect((()=>get(displayKeys)),(()=>{set(displayEntries,Object.entries(displays).filter((([key2,_])=>key2 in get(displayKeys))))}));legacy_pre_effect((()=>get(list)),(()=>{set(pluginEntries,function groupBy(items,key2){let ret={};for(const v2 of items){const k2=key2 in v2?v2[key2]:"";ret[k2]=ret[k2]||[];ret[k2].push(v2)}for(const k2 in ret)ret[k2]=ret[k2].sort(((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`)));return Object.entries(ret).sort((([a2],[b3])=>`${a2}`.localeCompare(`${b3}`)))}(filterList(get(list),["PLUGIN_MAIN","PLUGIN_DATA","PLUGIN_ETC"]),"name"))}));legacy_pre_effect_reset();init();div_1=child(div=first_child(fragment=root3()));button_1=sibling(button=child(div_1),2);button_2=sibling(button_1,2);node=sibling(button_2,2);consequent=$$anchor2=>{var button_3=root_14();event("click",button_3,(()=>async function requestReload(){await addOn.reloadPluginList(!0)}()));append($$anchor2,button_3)};if_block(node,($$render=>{get(isMaintenanceMode)&&$$render(consequent)}));reset(div_1);div_2=sibling(div_1,2);(button_5=sibling(button_4=child(div_2),2)).textContent="🚩 Select Flagged Shiny";button_6=sibling(button_5,2);button_7=sibling(button_6,2);reset(div_2);reset(div);node_1=child(div_3=sibling(div,2));consequent_1=$$anchor2=>{var span=root_23(),text2=child(span);reset(span);template_effect((()=>set_text(text2,"Updating list..."+(0==$pluginV2Progress()?"":` (${$pluginV2Progress()})`))));append($$anchor2,span)};if_block(node_1,($$render=>{(get(loading)||0!==$pluginV2Progress())&&$$render(consequent_1)}));reset(div_3);node_2=child(div_4=sibling(div_3,2));consequent_2=$$anchor2=>{append($$anchor2,root_32())};alternate=$$anchor2=>{var div_11,fragment_1=root_43(),node_3=first_child(fragment_1);each(node_3,1,(()=>get(displayEntries)),index,(($$anchor3,$$item)=>{var div_6,h3,text_1;let key2=()=>get($$item)[0];h3=child(div_6=root_52());text_1=child(h3,!0);reset(h3);each(sibling(h3,2),1,(()=>get(displayKeys)[key2()]),index,(($$anchor4,name)=>{var div_8,button_8,text_2,span_1,text_3,div_9,node_5,consequent_3,alternate_1,div_7=root_63();const bindKey=derived_safe_equal((()=>`${key2()}/${get(name)}`)),mode=derived_safe_equal((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKey)))?_a8:MODE_SELECTIVE}));div_8=child(div_7);button_8=child(div_8);text_2=child(button_8,!0);reset(button_8);span_1=sibling(button_8,2);text_3=child(span_1,!0);reset(span_1);reset(div_8);node_5=child(div_9=sibling(div_8,2));consequent_3=$$anchor5=>{const expression=derived_safe_equal((()=>get(mode)==MODE_SHINY)),expression_1=derived_safe_equal((()=>get(list).filter((e3=>e3.category==key2()&&e3.name==get(name)))));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get(expression)},get list(){return get(expression_1)},hidden:!1}))};alternate_1=$$anchor5=>{var div_10=root_82(),text_4=child(div_10,!0);reset(div_10);template_effect((()=>set_text(text_4,TITLES[get(mode)])));append($$anchor5,div_10)};if_block(node_5,($$render=>{get(mode)==MODE_SELECTIVE||get(mode)==MODE_SHINY?$$render(consequent_3):$$render(alternate_1,!1)}));reset(div_9);reset(div_7);template_effect((($0,$1)=>{set_class(div_7,1,"labelrow "+(get(hideEven)?"hideeven":""),"svelte-1pucu7f");set_text(text_2,$0);set_text(text_3,$1)}),[()=>getIcon(get(mode)),()=>"THEME"==key2()&&get(nameMap).get(`themes/${get(name)}`)||get(name)],derived_safe_equal);event("click",button_8,(evt=>askMode(evt,`${key2()}/${get(name)}`,get(bindKey))));append($$anchor4,div_7)}));reset(div_6);template_effect((()=>set_text(text_1,get($$item)[1])));append($$anchor3,div_6)}));div_11=sibling(node_3,2);each(sibling(child(div_11),2),1,(()=>get(pluginEntries)),index,(($$anchor3,$$item)=>{var fragment_3,div_12,div_13,button_9,text_5,span_2,text_6,div_14,node_7,consequent_4,node_8,consequent_9,alternate_5;let name=()=>get($$item)[0],listX=()=>get($$item)[1];fragment_3=root_92();const bindKeyAll=derived_safe_equal((()=>`${PREFIX_PLUGIN_ALL}/${name()}`)),modeAll=derived_safe_equal((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyAll)))?_a8:MODE_SELECTIVE})),bindKeyMain=derived_safe_equal((()=>`${PREFIX_PLUGIN_MAIN}/${name()}`)),modeMain=derived_safe_equal((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyMain)))?_a8:MODE_SELECTIVE})),bindKeyData=derived_safe_equal((()=>`${PREFIX_PLUGIN_DATA}/${name()}`)),modeData=derived_safe_equal((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyData)))?_a8:MODE_SELECTIVE})),bindKeyETC=derived_safe_equal((()=>`PLUGIN_ETC/${name()}`)),modeEtc=derived_safe_equal((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyETC)))?_a8:MODE_SELECTIVE}));div_13=child(div_12=first_child(fragment_3));button_9=child(div_13);text_5=child(button_9,!0);reset(button_9);span_2=sibling(button_9,2);text_6=child(span_2,!0);reset(span_2);reset(div_13);node_7=child(div_14=sibling(div_13,2));consequent_4=$$anchor4=>{const expression_2=derived_safe_equal((()=>get(modeAll)==MODE_SHINY));PluginCombo($$anchor4,spread_props((()=>get(options)),{get isFlagged(){return get(expression_2)},get list(){return listX()},hidden:!0}))};if_block(node_7,($$render=>{get(modeAll)!=MODE_SELECTIVE&&get(modeAll)!=MODE_SHINY||$$render(consequent_4)}));reset(div_14);reset(div_12);node_8=sibling(div_12,2);consequent_9=$$anchor4=>{var div_17,node_9,consequent_5,alternate_2,div_19,div_20,button_11,text_9,div_21,node_10,consequent_6,alternate_3,node_11,consequent_8,fragment_5=root_112(),div_15=first_child(fragment_5),div_16=child(div_15),button_10=child(div_16),text_7=child(button_10,!0);reset(button_10);next(2);reset(div_16);node_9=child(div_17=sibling(div_16,2));consequent_5=$$anchor5=>{const expression_3=derived_safe_equal((()=>get(modeMain)==MODE_SHINY)),expression_4=derived_safe_equal((()=>filterList(listX(),["PLUGIN_MAIN"])));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get(expression_3)},get list(){return get(expression_4)},hidden:!1}))};alternate_2=$$anchor5=>{var div_18=root_133(),text_8=child(div_18,!0);reset(div_18);template_effect((()=>set_text(text_8,TITLES[get(modeMain)])));append($$anchor5,div_18)};if_block(node_9,($$render=>{get(modeMain)==MODE_SELECTIVE||get(modeMain)==MODE_SHINY?$$render(consequent_5):$$render(alternate_2,!1)}));reset(div_17);reset(div_15);div_20=child(div_19=sibling(div_15,2));button_11=child(div_20);text_9=child(button_11,!0);reset(button_11);next(2);reset(div_20);node_10=child(div_21=sibling(div_20,2));consequent_6=$$anchor5=>{const expression_5=derived_safe_equal((()=>get(modeData)==MODE_SHINY)),expression_6=derived_safe_equal((()=>filterList(listX(),["PLUGIN_DATA"])));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get(expression_5)},get list(){return get(expression_6)},hidden:!1}))};alternate_3=$$anchor5=>{var div_22=root_15(),text_10=child(div_22,!0);reset(div_22);template_effect((()=>set_text(text_10,TITLES[get(modeData)])));append($$anchor5,div_22)};if_block(node_10,($$render=>{get(modeData)==MODE_SELECTIVE||get(modeData)==MODE_SHINY?$$render(consequent_6):$$render(alternate_3,!1)}));reset(div_21);reset(div_19);node_11=sibling(div_19,2);consequent_8=$$anchor5=>{var div_25,node_12,consequent_7,alternate_4,div_23=root_16(),div_24=child(div_23),button_12=child(div_24),text_11=child(button_12,!0);reset(button_12);next(2);reset(div_24);node_12=child(div_25=sibling(div_24,2));consequent_7=$$anchor6=>{const expression_7=derived_safe_equal((()=>get(modeEtc)==MODE_SHINY)),expression_8=derived_safe_equal((()=>filterList(listX(),["PLUGIN_ETC"])));PluginCombo($$anchor6,spread_props((()=>get(options)),{get isFlagged(){return get(expression_7)},get list(){return get(expression_8)},hidden:!1}))};alternate_4=$$anchor6=>{var div_26=root_18(),text_12=child(div_26,!0);reset(div_26);template_effect((()=>set_text(text_12,TITLES[get(modeEtc)])));append($$anchor6,div_26)};if_block(node_12,($$render=>{get(modeEtc)==MODE_SELECTIVE||get(modeEtc)==MODE_SHINY?$$render(consequent_7):$$render(alternate_4,!1)}));reset(div_25);reset(div_23);template_effect(($0=>{set_class(div_23,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-1pucu7f");set_text(text_11,$0)}),[()=>getIcon(get(modeEtc))],derived_safe_equal);event("click",button_12,(evt=>askMode(evt,`PLUGIN_ETC/${name()}`,get(bindKeyETC))));append($$anchor5,div_23)};if_block(node_11,($$render=>{useSyncPluginEtc&&$$render(consequent_8)}));template_effect((($0,$1)=>{set_class(div_15,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-1pucu7f");set_text(text_7,$0);set_class(div_19,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-1pucu7f");set_text(text_9,$1)}),[()=>getIcon(get(modeMain)),()=>getIcon(get(modeData))],derived_safe_equal);event("click",button_10,(evt=>askMode(evt,`${PREFIX_PLUGIN_MAIN}/${name()}/MAIN`,get(bindKeyMain))));event("click",button_11,(evt=>askMode(evt,`${PREFIX_PLUGIN_DATA}/${name()}`,get(bindKeyData))));append($$anchor4,fragment_5)};alternate_5=$$anchor4=>{var div_27=root_19(),div_28=child(div_27),text_13=child(div_28,!0);reset(div_28);reset(div_27);template_effect((()=>set_text(text_13,TITLES[get(modeAll)])));append($$anchor4,div_27)};if_block(node_8,($$render=>{get(modeAll)==MODE_SELECTIVE||get(modeAll)==MODE_SHINY?$$render(consequent_9):$$render(alternate_5,!1)}));template_effect((($0,$1)=>{set_class(div_12,1,"labelrow "+(get(hideEven)?"hideeven":""),"svelte-1pucu7f");set_text(text_5,$0);set_text(text_6,$1)}),[()=>getIcon(get(modeAll)),()=>get(nameMap).get(`plugins/${name()}`)||name()],derived_safe_equal);event("click",button_9,(evt=>askMode(evt,`${PREFIX_PLUGIN_ALL}/${name()}`,get(bindKeyAll))));append($$anchor3,fragment_3)}));reset(div_11);append($$anchor2,fragment_1)};if_block(node_2,($$render=>{0==get(list).length?$$render(consequent_2):$$render(alternate,!1)}));reset(div_4);node_13=sibling(div_4,2);consequent_10=$$anchor2=>{var button_13,div_29=root_20(),div_30=child(div_29),div_31=sibling(child(div_30),2),select=sibling(child(div_31),2);template_effect((()=>{get(deleteTerm);invalidate_inner_signals((()=>{get(allTerms)}))}));each(select,5,(()=>get(allTerms)),index,(($$anchor3,term)=>{var option=root_21(),option_value={},text_14=child(option,!0);reset(option);template_effect((()=>{var _a8;option_value!==(option_value=get(term))&&(option.value=null!=(_a8=option.__value=get(term))?_a8:"");set_text(text_14,get(term))}));append($$anchor3,option)}));reset(select);button_13=sibling(select,2);reset(div_31);reset(div_30);reset(div_29);bind_select_value(select,(()=>get(deleteTerm)),($$value=>set(deleteTerm,$$value)));event("click",button_13,(evt=>{(async function deleteAllItems(term){const deleteItems=get(list).filter((e3=>e3.term==term));for(const item of deleteItems)await deleteData(item);addOn.reloadPluginList(!0)})(get(deleteTerm))}));append($$anchor2,div_29)};if_block(node_13,($$render=>{get(isMaintenanceMode)&&$$render(consequent_10)}));label_1=child(div_32=sibling(node_13,2));remove_input_defaults(input=sibling(child(label_1)));reset(label_1);reset(div_32);label_2=child(div_33=sibling(div_32,2));remove_input_defaults(input_1=sibling(child(label_2)));reset(label_2);reset(div_33);event("click",button,(()=>async function scanAgain(){await addOn.scanAllConfigFiles(!0);await requestUpdate()}()));event("click",button_1,(()=>async function replicate2(){await plugin3().$$replicate(!0)}()));event("click",button_2,(()=>requestUpdate()));event("click",button_4,(()=>selectAllNewest(!0)));event("click",button_5,(()=>selectAllNewest(!1)));event("click",button_6,(()=>function resetSelectNewest(){update(selectNewestPulse);set(selectNewestStyle,3)}()));event("click",button_7,(()=>function applyAll(){update(applyAllPluse)}()));bind_checked(input,(()=>get(hideEven)),($$value=>set(hideEven,$$value)));bind_checked(input_1,(()=>get(isMaintenanceMode)),($$value=>set(isMaintenanceMode,$$value)));append($$anchor,fragment);pop();$$cleanup()}function serialize(data){var _a8,_b4,_c3,_d2,_e2;let ret="";ret+=":";ret+=data.category+d+data.name+d+data.term+d2;ret+=(null!=(_a8=data.version)?_a8:"")+d2;ret+=data.mtime+d2;for(const file of data.files){ret+=file.filename+d+(null!=(_b4=file.displayName)?_b4:"")+d+(null!=(_c3=file.version)?_c3:"")+d2;const hash2=digestHash(null!=(_d2=file.data)?_d2:[]);ret+=file.mtime+d+file.size+d+hash2+d2;for(const data2 of null!=(_e2=file.data)?_e2:[])ret+=data2+d;ret+=d2}return ret}function deserialize(str,def){try{if(":"==str[0][0]){const o2=function deserialize2(str){const tokens=function getTokenizer(source2){const sources=function splitWithDelimiters(sources){const result=[];for(const str of sources){let startIndex=0;const maxLen=str.length;let i1,i22,i2=-1;do{i1=str.indexOf(d,startIndex);i22=str.indexOf(d2,startIndex);if(-1==i1&&-1==i22)break;i2=-1==i1?i22:-1==i22||i1=sources.length)return"";const item=sources[pos];item.endsWith(d2)?lineRunOut=!0:pos++;return item.endsWith(d)||item.endsWith(d2)?item.substring(0,item.length-1):item+this.next()},nextLine(){if(lineRunOut)pos++;else{for(;!sources[pos].endsWith(d2);){pos++;if(pos>=sources.length)break}pos++}lineRunOut=!1}}}(str),category=tokens.next(),name=tokens.next(),term=tokens.next();tokens.nextLine();const version2=tokens.next();tokens.nextLine();const mtime=Number(tokens.next());tokens.nextLine();const result=Object.assign({},{category,name,term,version:version2,mtime,files:[]});let filename="";do{filename=tokens.next();if(!filename)break;const displayName=tokens.next(),version3=tokens.next();tokens.nextLine();const mtime2=Number(tokens.next()),size=Number(tokens.next()),hash2=tokens.next();tokens.nextLine();const data=[];let piece="";do{piece=tokens.next();if(""==piece)break;data.push(piece)}while(""!=piece);result.files.push({filename,displayName,version:version3,mtime:mtime2,size,data,hash:hash2});tokens.nextLine()}while(filename);return result}(str);return o2}return JSON.parse(str.join(""))}catch(e3){try{return(0,import_obsidian.parseYaml)(str.join(""))}catch(e4){return def}}}function categoryToFolder(category,configDir=""){switch(category){case"CONFIG":return`${configDir}/`;case"THEME":return`${configDir}/themes/`;case"SNIPPET":return`${configDir}/snippets/`;case"PLUGIN_MAIN":return`${configDir}/plugins/`;case"PLUGIN_DATA":return`${configDir}/plugins/`;case"PLUGIN_ETC":return`${configDir}/plugins/`;default:return""}}function setFeature(context2,feature,value){context2.__aws_sdk_context?context2.__aws_sdk_context.features||(context2.__aws_sdk_context.features={}):context2.__aws_sdk_context={features:{}};context2.__aws_sdk_context.features[feature]=value}function getSerdePlugin(config,serializer,deserializer){return{applyToStack:commandStack=>{commandStack.add(deserializerMiddleware(config,deserializer),deserializerMiddlewareOption);commandStack.add(serializerMiddleware(config,serializer),serializerMiddlewareOption)}}}function toBase64(_input){let input;input="string"==typeof _input?fromUtf8(_input):_input;const isArrayLike="object"==typeof input&&"number"==typeof input.length,isUint8Array="object"==typeof input&&"number"==typeof input.byteOffset&&"number"==typeof input.byteLength;if(!isArrayLike&&!isUint8Array)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let str="";for(let i2=0;i2>offset]}str+="==".slice(0,4-bitClusterCount)}return str}function flush(buffers,mode){switch(mode){case 0:const s2=buffers[0];buffers[0]="";return s2;case 1:case 2:return buffers[mode].flush()}throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`)}function sizeOf(chunk){var _a8,_b4;return null!=(_b4=null!=(_a8=null==chunk?void 0:chunk.byteLength)?_a8:null==chunk?void 0:chunk.length)?_b4:0}function buildQueryString(query3){const parts=[];for(let key2 of Object.keys(query3).sort()){const value=query3[key2];key2=escapeUri(key2);if(Array.isArray(value))for(let i2=0,iLen=value.length;i2{timeoutInMs&&setTimeout((()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)}),timeoutInMs)}))}function fromHex(encoded){if(encoded.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const out=new Uint8Array(encoded.length/2);for(let i2=0;i2-1;i2--){bytes[i2]++;if(0!==bytes[i2])break}}function dateToUtcString(date){const year=date.getUTCFullYear(),month=date.getUTCMonth(),dayOfWeek=date.getUTCDay(),dayOfMonthInt=date.getUTCDate(),hoursInt=date.getUTCHours(),minutesInt=date.getUTCMinutes(),secondsInt=date.getUTCSeconds(),dayOfMonthString=dayOfMonthInt<10?`0${dayOfMonthInt}`:`${dayOfMonthInt}`,hoursString=hoursInt<10?`0${hoursInt}`:`${hoursInt}`,minutesString=minutesInt<10?`0${minutesInt}`:`${minutesInt}`,secondsString=secondsInt<10?`0${secondsInt}`:`${secondsInt}`;return`${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`}function map2(arg0,arg1,arg2){let target,filter4,instructions;if(void 0===arg1&&void 0===arg2){target={};instructions=arg0}else{target=arg0;if("function"==typeof arg1){filter4=arg1;instructions=arg2;return mapWithFilter(target,filter4,instructions)}instructions=arg1}for(const key2 of Object.keys(instructions))Array.isArray(instructions[key2])?applyInstruction(target,null,instructions,key2):target[key2]=instructions[key2];return target}function quoteHeader(part){(part.includes(",")||part.includes('"'))&&(part=`"${part.replace(/"/g,'\\"')}"`);return part}function __awaiter(thisArg,_arguments,P2,generator){return new(P2||(P2=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e3){reject(e3)}}function rejected(value){try{step(generator.throw(value))}catch(e3){reject(e3)}}function step(result){result.done?resolve(result.value):function adopt(value){return value instanceof P2?value:new P2((function(resolve){resolve(value)}))}(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))}function __generator(thisArg,body){function verb(n3){return function(v2){return function step(op){if(f4)throw new TypeError("Generator is already executing.");for(;g2&&(g2=0,op[0]&&(_=0)),_;)try{if(f4=1,y2&&(t3=2&op[0]?y2.return:op[0]?y2.throw||((t3=y2.return)&&t3.call(y2),0):y2.next)&&!(t3=t3.call(y2,op[1])).done)return t3;(y2=0,t3)&&(op=[2&op[0],t3.value]);switch(op[0]){case 0:case 1:t3=op;break;case 4:_.label++;return{value:op[1],done:!1};case 5:_.label++;y2=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t3=_.trys,t3=t3.length>0&&t3[t3.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t3||op[1]>t3[0]&&op[1]=o2.length&&(o2=void 0);return{value:o2&&o2[i2++],done:!o2}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}function convertToBuffer(data){return data instanceof Uint8Array?data:"string"==typeof data?fromUtf83(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function isEmptyData(data){return"string"==typeof data?0===data.length:0===data.byteLength}function numToUint8(num){return new Uint8Array([(4278190080&num)>>24,(16711680&num)>>16,(65280&num)>>8,255&num])}function uint32ArrayFrom(a_lookUpTable2){var return_array,a_index;if(!Uint32Array.from){return_array=new Uint32Array(a_lookUpTable2.length);a_index=0;for(;a_index{throw new Error("SignatureV4S3Express credential override was created but not called.")}),10),currentCredentialProvider=privateAccess.credentialProvider;privateAccess.credentialProvider=()=>{clearTimeout(id);privateAccess.credentialProvider=currentCredentialProvider;return Promise.resolve(credentialsWithoutSessionToken)}}function toDebugString(input){return"object"!=typeof input||null==input?input:"ref"in input?`$${toDebugString(input.ref)}`:"fn"in input?`${input.fn}(${(input.argv||[]).map(toDebugString).join(", ")})`:JSON.stringify(input,null,2)}function rng(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}function createAwsAuthSigv4HttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function createAwsAuthSigv4aHttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function isEmptyData2(data){return"string"==typeof data?0===data.length:0===data.byteLength}function locateWindow(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:fallbackWindow}function convertToBuffer2(data){return"string"==typeof data?fromUtf84(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function supportsWebCrypto(window2){return!(!function supportsSecureRandom(window2){return"object"==typeof window2&&"object"==typeof window2.crypto&&"function"==typeof window2.crypto.getRandomValues}(window2)||"object"!=typeof window2.crypto.subtle)&&function supportsSubtleCrypto(subtle){return subtle&&subtleCryptoMethods.every((function(methodName){return"function"==typeof subtle[methodName]}))}(window2.crypto.subtle)}function negate2(bytes){for(let i2=0;i2<8;i2++)bytes[i2]^=255;for(let i2=7;i2>-1;i2--){bytes[i2]++;if(0!==bytes[i2])break}}function getMessageUnmarshaller(deserializer,toUtf82){return async function(message){const{value:messageType}=message.headers[":message-type"];if("error"===messageType){const unmodeledError=new Error(message.headers[":error-message"].value||"UnknownError");unmodeledError.name=message.headers[":error-code"].value;throw unmodeledError}if("exception"===messageType){const code=message.headers[":exception-type"].value,exception={[code]:message},deserializedException=await deserializer(exception);if(deserializedException.$unknown){const error=new Error(toUtf82(message.body));error.name=code;throw error}throw deserializedException[code]}if("event"===messageType){const event2={[message.headers[":event-type"].value]:message},deserialized=await deserializer(event2);if(deserialized.$unknown)return;return deserialized}throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`)}}function cmn(q2,a2,b3,x2,s2,t3){return((a2=(a2+q2&4294967295)+(x2+t3&4294967295)&4294967295)<>>32-s2)+b3&4294967295}function ff(a2,b3,c3,d4,x2,s2,t3){return cmn(b3&c3|~b3&d4,a2,b3,x2,s2,t3)}function gg(a2,b3,c3,d4,x2,s2,t3){return cmn(b3&d4|c3&~d4,a2,b3,x2,s2,t3)}function hh(a2,b3,c3,d4,x2,s2,t3){return cmn(b3^c3^d4,a2,b3,x2,s2,t3)}function ii(a2,b3,c3,d4,x2,s2,t3){return cmn(c3^(b3|~d4),a2,b3,x2,s2,t3)}function isValidBase64EncodedSSECustomerKey(str,options){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str))return!1;try{return 32===options.base64Decoder(str).length}catch(e3){return!1}}function generateId(prefix){if(++idx>1e4){series=`${Date.now()}`;idx=0}return`${PREFIX_TRENCH}-${prefix}-${series}-${idx+1e7}`}function createRange(prefix,series2){return[`${PREFIX_TRENCH}-${prefix}-${series2}-`,`${PREFIX_TRENCH}-${prefix}-${series2}.`]}function serializeDoc(doc){if(doc._id.startsWith("h:")){const writeData=function escapeNewLineFromString(str){return-1===str.indexOf("\n")&&-1===str.indexOf("\r")?str:"\\f"+str.replace(/(\n|\r|\\)/g,(m3=>`${map[m3]}`))}(doc.data);return te4.encode(`~${doc._id}${UNIT_SPLIT}${writeData}${RECORD_SPLIT}`)}return te4.encode(JSON.stringify(doc)+RECORD_SPLIT)}async function ensureRemoteIsCompatible(infoSrc,setting,deviceNodeID,currentVersionRange3,updateCallback){var _a8,_b4,_c3,_d2;const baseMilestone={_id:MILESTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked:!1,accepted_nodes:[deviceNodeID],node_chunk_info:{[deviceNodeID]:currentVersionRange3},tweak_values:{}};let remoteMilestone=infoSrc;remoteMilestone||(remoteMilestone=baseMilestone);const currentTweakValues=extractObject(TweakValuesTemplate,setting);remoteMilestone.node_chunk_info={...baseMilestone.node_chunk_info,...remoteMilestone.node_chunk_info};if(remoteMilestone.node_chunk_info[deviceNodeID].min!=currentVersionRange3.min||remoteMilestone.node_chunk_info[deviceNodeID].max!=currentVersionRange3.max||isObjectDifferent(null==(_a8=remoteMilestone.tweak_values)?void 0:_a8[deviceNodeID],currentTweakValues)||void 0===remoteMilestone._rev||!(DEVICE_ID_PREFERRED in remoteMilestone.tweak_values)){remoteMilestone.node_chunk_info[deviceNodeID].min=currentVersionRange3.min;remoteMilestone.node_chunk_info[deviceNodeID].max=currentVersionRange3.max;remoteMilestone.tweak_values={...null!=(_b4=remoteMilestone.tweak_values)?_b4:{},[deviceNodeID]:currentTweakValues};DEVICE_ID_PREFERRED in remoteMilestone.tweak_values||(remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=currentTweakValues);await updateCallback(remoteMilestone)}let globalMin=currentVersionRange3.min,globalMax=currentVersionRange3.max;for(const nodeId of remoteMilestone.accepted_nodes)if(nodeId!=deviceNodeID)if(nodeId in remoteMilestone.node_chunk_info){const nodeInfo=remoteMilestone.node_chunk_info[nodeId];globalMin=Math.max(nodeInfo.min,globalMin);globalMax=Math.min(nodeInfo.max,globalMax)}else{globalMin=0;globalMax=0}if(globalMax0&&Date.now()-fromstore_get(results,"$results",$$stores),resultLines=mutable_source();let plugin3=prop($$props,"plugin",8),moduleDev=prop($$props,"moduleDev",8),performanceTestResult=mutable_source(""),testRunning=mutable_source(!1),prefTestResultEl=mutable_source(),isReady=mutable_source(!1);onMount((async()=>{set(isReady,!0);eventHub.onceEvent(EVENT_LAYOUT_READY,(async()=>{if(await plugin3().storageAccess.isExistsIncludeHidden("_AUTO_TEST.md")){new import_obsidian.Notice("Auto test file found, running tests...");fireAndForget((async()=>{await allTest()}))}}))}));let moduleTesting=mutable_source(!1);const results=moduleDev().testResults;let syncStatus=mutable_source([]);eventHub.onEvent("debug-sync-status",(status=>{set(syncStatus,[...status])}));legacy_pre_effect((()=>(get(performanceTestResult),get(isReady),import_obsidian.MarkdownRenderer,deep_read_state(plugin3()),get(prefTestResultEl))),(()=>{""!=get(performanceTestResult)&&get(isReady)&&import_obsidian.MarkdownRenderer.render(plugin3().app,get(performanceTestResult),get(prefTestResultEl),"/",plugin3())}));legacy_pre_effect((()=>$results()),(()=>{set(resultLines,$results())}));legacy_pre_effect_reset();init();fragment=root4();button=sibling(first_child(fragment),4);button_1=sibling(button,2);button_2=sibling(button_1,2);button_3=sibling(button_2,2);each(node=sibling(button_3,2),1,(()=>get(resultLines)),index,(($$anchor2,$$item)=>{var details,summary,text2,pre,text_1;let result=()=>get($$item)[0];summary=child(details=root_17());text2=child(summary);reset(summary);pre=sibling(summary,2);text_1=child(pre,!0);reset(pre);reset(details);template_effect((()=>{var _a8;details.open=!result();set_text(text2,`[${result()?"PASS":"FAILED"}] ${null!=(_a8=get($$item)[1])?_a8:""}`);set_text(text_1,get($$item)[2])}));append($$anchor2,details)}));pre_1=sibling(node,4);text_2=child(pre_1,!0);reset(pre_1);button_4=sibling(pre_1,4);button_5=sibling(button_4,2);bind_this(sibling(button_5,2),($$value=>set(prefTestResultEl,$$value)),(()=>get(prefTestResultEl)));template_effect(($0=>{button.disabled=get(moduleTesting);button_1.disabled=get(moduleTesting);button_2.disabled=get(moduleTesting);set_text(text_2,$0);button_4.disabled=get(testRunning)}),[()=>get(syncStatus).join("\n")],derived_safe_equal);event("click",button,(()=>function moduleMultiDeviceTest(){if(!get(moduleTesting)){set(moduleTesting,!0);plugin3().$everyModuleTestMultiDevice().finally((()=>{set(moduleTesting,!1)}))}}()));event("click",button_1,(()=>function moduleSingleDeviceTest(){if(!get(moduleTesting)){set(moduleTesting,!0);plugin3().$everyModuleTest().finally((()=>{set(moduleTesting,!1)}))}}()));event("click",button_2,(()=>allTest()));event("click",button_3,(()=>function clearResult2(){moduleDev().testResults.update((v2=>[]))}()));event("click",button_4,(()=>async function performTest(){try{set(testRunning,!0);set(performanceTestResult,await async function perf_trench(plugin3){clearResult("trench");const trench=new Trench(plugin3.simpleStore),result=[];result.push(await measure("trench-short-string",(async()=>{const p4=trench.evacuate("string");await p4()})));{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/10kb.png"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-10kb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/100kb.jpeg"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-100kb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/1mb.png"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-1mb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}return async function formatPerfResults(items){return"| Name | Runs | Each | Total |\n| --- | --- | --- | --- | \n"+items.map((e3=>`| ${e3[0]} | ${e3[1][0]} | ${0!=e3[1][0]?formatNumber(e3[1][1]/e3[1][0]):"-"} | ${formatNumber(e3[1][0])} |`)).join("\n")}(result)}(plugin3()))}finally{set(testRunning,!1)}}()));event("click",button_5,(()=>function clearPerfTestResult(){get(prefTestResultEl).empty()}()));append($$anchor,fragment);pop();$$cleanup()}function getFileLockKey(file){return`fl:${"string"==typeof file?file:file.path}`}function toArrayBuffer(arr){return arr instanceof Uint8Array||arr instanceof DataView?arr.buffer:arr}async function processReadFile(file,proc){return await serialized(getFileLockKey(file),(()=>proc()))}async function processWriteFile(file,proc){return await serialized(getFileLockKey(file),(()=>proc()))}function TFileToUXFileInfoStub(file,deleted){if(!(file instanceof import_obsidian.TFile))throw new Error("Invalid file type");return{name:file.name,path:file.path,isFolder:!1,stat:{size:file.stat.size,mtime:file.stat.mtime,ctime:file.stat.ctime,type:"file"},deleted}}function confirmWithMessage(plugin3,title,contentMd,buttons,defaultAction,timeout){return new Promise((res2=>{new MessageBox(plugin3,title,contentMd,buttons,defaultAction,timeout,!1,(result=>res2(result))).open()}))}function confirmWithMessageWithWideButton(plugin3,title,contentMd,buttons,defaultAction,timeout){return new Promise((res2=>{new MessageBox(plugin3,title,contentMd,buttons,defaultAction,timeout,!0,(result=>res2(result))).open()}))}function getConfig(key2){return function translateInfo(infoSrc){if(!infoSrc)return!1;const info3={...infoSrc};info3.name=$t(info3.name);info3.desc&&(info3.desc=$t(info3.desc));return info3}(function _getConfig(key2){return key2 in configurationNames?configurationNames[key2]:key2 in SettingInformation&&SettingInformation[key2]}(key2))}function getConfName(key2){const conf=getConfig(key2);return conf?conf.name:`${key2} (No info)`}function createError(error,reason){function CustomPouchError(reason2){var i2,len,names=Object.getOwnPropertyNames(error);for(i2=0,len=names.length;i2=allRequests.length)){upTo=Math.min(i2+MAX_NUM_CONCURRENT_REQUESTS,allRequests.length);(function processBatch(batch,offset){batch.forEach((function(docId,j2){var formatResult,docIdx=offset+j2,docRequests=requestsById.get(docId),docOpts=pick(docRequests[0],["atts_since","attachments"]);docOpts.open_revs=docRequests.map((function(request2){return request2.rev}));docOpts.open_revs=docOpts.open_revs.filter(identityFunction);formatResult=identityFunction;if(0===docOpts.open_revs.length){delete docOpts.open_revs;formatResult=formatResultForOpenRevsGet}["revs","attachments","binary","ajax","latest"].forEach((function(param){param in opts&&(docOpts[param]=opts[param])}));db.get(docId,docOpts,(function(err2,res2){var result;result=err2?[{error:err2}]:formatResult(res2);(function gotResult(docIndex,id,docs){perDocResults[docIndex]={id,docs};(function checkDone(){++numDone===numDocs&&function collapseResultsAndFinish(){var results=[];perDocResults.forEach((function(res2){res2.docs.forEach((function(info3){results.push({id:res2.id,docs:[info3]})}))}));callback(null,{results})}()})()})(docIdx,docId,result);nextBatch()}))}))})(batch=allRequests.slice(i2,upTo),i2);i2+=batch.length}})()}function hasLocalStorage(){return hasLocal}function guardedConsole(method){if("undefined"!=typeof console&&"function"==typeof console[method]){var args=Array.prototype.slice.call(arguments,1);console[method].apply(console,args)}}function defaultBackOff(min){var max3=0;min||(max3=2e3);return function randomNumber(min,max3){min=parseInt(min,10)||0;(max3=parseInt(max3,10))!=max3||max3<=min?max3=(min||1)<<1:max3+=1;if(max3>6e5){min=3e5;max3=6e5}return~~((max3-min)*Math.random()+min)}(min,max3)}function explainError(status,str){guardedConsole("info","The above "+status+" is totally normal. "+str)}function filterChange(opts){var req={},hasFilter=opts.filter&&"function"==typeof opts.filter;req.query=opts.query_params;return function filter4(change){var filterReturn,att;change.doc||(change.doc={});filterReturn=hasFilter&&function tryFilter(filter4,doc,req){try{return!filter4(doc,req)}catch(err2){var msg="Filter function threw: "+err2.toString();return createError(BAD_REQUEST,msg)}}(opts.filter,change.doc,req);if("object"==typeof filterReturn)return filterReturn;if(filterReturn)return!1;if(opts.include_docs){if(!opts.attachments)for(att in change.doc._attachments)Object.prototype.hasOwnProperty.call(change.doc._attachments,att)&&(change.doc._attachments[att].stub=!0)}else delete change.doc;return!0}}function invalidIdError(id){var err2;id?"string"!=typeof id?err2=createError(INVALID_ID):/^_/.test(id)&&!/^_(design|local)/.test(id)&&(err2=createError(RESERVED_ID)):err2=createError(MISSING_ID);if(err2)throw err2}function isRemote(db){if("boolean"==typeof db._remote)return db._remote;if("function"==typeof db.type){guardedConsole("warn","db.type() is deprecated and will be removed in a future version of PouchDB");return"http"===db.type()}return!1}function parseDesignDocFunctionName(s2){if(!s2)return null;var parts=s2.split("/");return 2===parts.length?parts:1===parts.length?[s2,s2]:null}function normalizeDesignDocFunctionName(s2){var normalized=parseDesignDocFunctionName(s2);return normalized?normalized.join("/"):null}function parseUri(str){for(var key2,value,encoded,m3=parser.exec(str),uri={},i2=14;i2--;){key2=keys2[i2];value=m3[i2]||"";encoded=-1!==["user","password"].indexOf(key2);uri[key2]=encoded?decodeURIComponent(value):value}uri[qName]={};uri[keys2[12]].replace(qParser,(function($0,$1,$2){$1&&(uri[qName][$1]=$2)}));return uri}function scopeEval(source2,scope){var key2,keys3=[],values=[];for(key2 in scope)if(Object.prototype.hasOwnProperty.call(scope,key2)){keys3.push(key2);values.push(scope[key2])}keys3.push(source2);return Function.apply(null,keys3).apply(null,values)}function upsert2(db,docId,diffFun){return db.get(docId).catch((function(err2){if(404!==err2.status)throw err2;return{}})).then((function(doc){var docRev=doc._rev,newDoc=diffFun(doc);if(!newDoc)return{updated:!1,rev:docRev};newDoc._id=docId;newDoc._rev=docRev;return function tryAndPut(db,doc,diffFun){return db.put(doc).then((function(res2){return{updated:!0,rev:res2.rev}}),(function(err2){if(409!==err2.status)throw err2;return upsert2(db,doc._id,diffFun)}))}(db,newDoc,diffFun)}))}function rev2(doc,deterministic_revs){if(!deterministic_revs)return v4_default2().replace(/-/g,"").toLowerCase();var mutateableDoc=Object.assign({},doc);delete mutateableDoc._rev_tree;return function stringMd5(string){return import_spark_md5.default.hash(string)}(JSON.stringify(mutateableDoc))}function winningRev(metadata){for(var winningId,winningPos,winningDeleted,node,tree,branches,pos,i2,len,deleted,id,toVisit=metadata.rev_tree.slice();node=toVisit.pop();){branches=(tree=node.ids)[2];pos=node.pos;if(branches.length)for(i2=0,len=branches.length;i21)&&(path2=[]);for(let i2=0,len=branches.length;i2>>1],item)<0?low=mid+1:high=mid;return low}(arr,item,comparator);arr.splice(idx2,0,item)}function pathToTree(path2,numStemmed){var root9,leaf,i2,len,node,currentLeaf;for(i2=numStemmed,len=path2.length;i20;){tree1=(item=queue2.pop()).tree1;tree2=item.tree2;(tree1[1].status||tree2[1].status)&&(tree1[1].status="available"===tree1[1].status||"available"===tree2[1].status?"available":"missing");for(i2=0;i20;)if(0!==(item=trees.pop()).diff)for(j2=0,elementsLen=(elements=item.ids[2]).length;j2depth){stemmedRevs||(stemmedRevs={});numStemmed=stemmed.length-depth;node={pos:path2.pos+numStemmed,ids:pathToTree(stemmed,numStemmed)};for(s2=0;s2{path2=function removeLeafFromPath(path2,leafRev){const tree=clone2(path2),toVisit=[tree];let node;for(;node=toVisit.pop();){const{pos,ids:[id,,branches],parent}=node;if(0===branches.length&&`${pos}-${id}`===leafRev){if(!parent)return null;parent.ids[2]=parent.ids[2].filter((function(branchNode){return branchNode[0]!==id}));return tree}for(let i2=0,len=branches.length;i2b3?1:-1}(a2,b3)}return Array.isArray(a2)?function arrayCollate(a2,b3){var len,i2,sort;for(len=Math.min(a2.length,b3.length),i2=0;i2b3.length?1:-1}(a2,b3):function objectCollate(a2,b3){var ak2,bk2,len,i2,sort;for(ak2=Object.keys(a2),bk2=Object.keys(b3),len=Math.min(ak2.length,bk2.length),i2=0;i2bk2.length?1:-1}(a2,b3)}function normalizeKey(key2){var origKey,len,i2,k2,val2;switch(typeof key2){case"undefined":return null;case"number":return key2===1/0||key2===-1/0||isNaN(key2)?null:key2;case"object":origKey=key2;if(Array.isArray(key2)){len=key2.length;key2=new Array(len);for(i2=0;i2right?1:0}function parseField(fieldName){var i2,len,ch4,fields=[],current="";for(i2=0,len=fieldName.length;i20&&"\\"===fieldName[i2-1]&&("$"===ch4||"."===ch4))current=current.substring(0,current.length-1)+ch4;else if("."===ch4){fields.push(current);current=""}else current+=ch4}fields.push(current);return fields}function isCombinationalField(field){return combinationFields.indexOf(field)>-1}function getKey2(obj){return Object.keys(obj)[0]}function getValue(obj){return obj[getKey2(obj)]}function mergeAndedSelectors(selectors){var res2={},first={$or:!0,$nor:!0};selectors.forEach((function(selector){Object.keys(selector).forEach((function(field){var entries2,fieldMatchers,matcher=selector[field];"object"!=typeof matcher&&(matcher={$eq:matcher});if(isCombinationalField(field))if(matcher instanceof Array){if(first[field]){first[field]=!1;res2[field]=matcher;return}entries2=[];res2[field].forEach((function(existing){Object.keys(matcher).forEach((function(key2){var m3=matcher[key2],longest=Math.max(Object.keys(existing).length,Object.keys(m3).length),merged=mergeAndedSelectors([existing,m3]);Object.keys(merged).length<=longest||entries2.push(merged)}))}));res2[field]=entries2}else res2[field]=mergeAndedSelectors([matcher]);else{fieldMatchers=res2[field]=res2[field]||{};Object.keys(matcher).forEach((function(operator){var value=matcher[operator];if("$gt"===operator||"$gte"===operator)return function mergeGtGte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$gte){if("$gte"===operator)value>fieldMatchers.$gte&&(fieldMatchers.$gte=value);else if(value>=fieldMatchers.$gte){delete fieldMatchers.$gte;fieldMatchers.$gt=value}}else if(void 0!==fieldMatchers.$gt)if("$gte"===operator){if(value>fieldMatchers.$gt){delete fieldMatchers.$gt;fieldMatchers.$gte=value}}else value>fieldMatchers.$gt&&(fieldMatchers.$gt=value);else fieldMatchers[operator]=value}(operator,value,fieldMatchers);if("$lt"===operator||"$lte"===operator)return function mergeLtLte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$lte){if("$lte"===operator)value0)return!1;subDocFieldValue=getFieldFromDoc(docFieldValue,subParsedField);return"object"==typeof userValue?matchSelector(userValue,doc,parsedField,subDocFieldValue):match2("$eq",doc,userValue,subParsedField,subDocFieldValue)})):matcher===docFieldValue)}function match2(userOperator,doc,userValue,parsedField,docFieldValue){if(!matchers[userOperator])throw new Error('unknown operator "'+userOperator+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return matchers[userOperator](doc,userValue,parsedField,docFieldValue)}function fieldExists(docFieldValue){return null!=docFieldValue}function fieldIsNotUndefined(docFieldValue){return void 0!==docFieldValue}function arrayContainsValue(docFieldValue,userValue){return userValue.some((function(val2){return docFieldValue instanceof Array?docFieldValue.some((function(docFieldValueItem){return 0===collate(val2,docFieldValueItem)})):0===collate(val2,docFieldValue)}))}function matchesSelector(doc,selector){var rowsMatched;if("object"!=typeof selector)throw new Error("Selector error: expected a JSON object");return(rowsMatched=filterInMemoryFields([{doc}],{selector:selector=massageSelector(selector)},Object.keys(selector)))&&1===rowsMatched.length}function validate4(opts,callback){if(opts.selector&&opts.filter&&"_selector"!==opts.filter){var filterName="string"==typeof opts.filter?opts.filter:"function";return callback(new Error('selector invalid for filter "'+filterName+'"'))}callback()}function normalize(opts){opts.view&&!opts.filter&&(opts.filter="_view");opts.selector&&!opts.filter&&(opts.filter="_selector");opts.filter&&"string"==typeof opts.filter&&("_view"===opts.filter?opts.view=normalizeDesignDocFunctionName(opts.view):opts.filter=normalizeDesignDocFunctionName(opts.filter))}function shouldFilter(changesHandler,opts){return opts.filter&&"string"==typeof opts.filter&&!opts.doc_ids&&!isRemote(changesHandler.db)}function filter2(changesHandler,opts){var err2,viewName,filterName,callback=opts.complete;if("_view"===opts.filter){if(!opts.view||"string"!=typeof opts.view){err2=createError(BAD_REQUEST,"`view` filter parameter not found or invalid.");return callback(err2)}viewName=parseDesignDocFunctionName(opts.view);changesHandler.db.get("_design/"+viewName[0],(function(err3,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err3)return callback(generateErrorFromResponse(err3));var mapFun=ddoc&&ddoc.views&&ddoc.views[viewName[1]]&&ddoc.views[viewName[1]].map;if(!mapFun)return callback(createError(MISSING_DOC,ddoc.views?"missing json key: "+viewName[1]:"missing json key: views"));opts.filter=function evalView(input){return scopeEval(["return function(doc) {",' "use strict";'," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+input+";"," view(doc);"," if (emitted) {"," return true;"," }","};"].join("\n"),{})}(mapFun);changesHandler.doChanges(opts)}))}else if(opts.selector){opts.filter=function(doc){return matchesSelector(doc,opts.selector)};changesHandler.doChanges(opts)}else{filterName=parseDesignDocFunctionName(opts.filter);changesHandler.db.get("_design/"+filterName[0],(function(err3,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err3)return callback(generateErrorFromResponse(err3));var filterFun=ddoc&&ddoc.filters&&ddoc.filters[filterName[1]];if(!filterFun)return callback(createError(MISSING_DOC,ddoc&&ddoc.filters?"missing json key: "+filterName[1]:"missing json key: filters"));opts.filter=function evalFilter(input){return scopeEval('"use strict";\nreturn '+input+";",{})}(filterFun);changesHandler.doChanges(opts)}))}}function processChange(doc,metadata,opts){var change,changeList=[{rev:doc._rev}];"all_docs"===opts.style&&(changeList=collectLeaves(metadata.rev_tree).map((function(x2){return{rev:x2.rev}})));change={id:metadata.id,changes:changeList,doc};isDeleted(metadata,doc._rev)&&(change.deleted=!0);if(opts.conflicts){change.doc._conflicts=collectConflicts(metadata);change.doc._conflicts.length||delete change.doc._conflicts}return change}function yankError(callback,docId){return function(err2,results){if(err2||results[0]&&results[0].error){(err2=err2||results[0]).docId=docId;callback(err2)}else callback(null,results.length?results[0]:results)}}function compareByIdThenRev(a2,b3){return a2._id===b3._id?(a2._revisions?a2._revisions.start:0)-(b3._revisions?b3._revisions.start:0):a2._id0||end0||end=43)};req.onerror=txn.onabort=function(e3){e3.preventDefault();e3.stopPropagation();resolve(!1)}})).catch((function(){return!1}))}function toObject(array){return array.reduce((function(obj,item){obj[item]=!0;return obj}),{})}function parseRevisionInfo(rev$$1){var idx2,left,right;if(!/^\d+-/.test(rev$$1))return createError(INVALID_REV);idx2=rev$$1.indexOf("-");left=rev$$1.substring(0,idx2);right=rev$$1.substring(idx2+1);return{prefix:parseInt(left,10),id:right}}function parseDoc(doc,newEdits,dbOpts){var nRevNum,newRevId,revInfo,opts,result,key2,specialKey,error;dbOpts||(dbOpts={deterministic_revs:!0});opts={status:"available"};doc._deleted&&(opts.deleted=!0);if(newEdits){doc._id||(doc._id=uuid());newRevId=rev2(doc,dbOpts.deterministic_revs);if(doc._rev){if((revInfo=parseRevisionInfo(doc._rev)).error)return revInfo;doc._rev_tree=[{pos:revInfo.prefix,ids:[revInfo.id,{status:"missing"},[[newRevId,opts,[]]]]}];nRevNum=revInfo.prefix+1}else{doc._rev_tree=[{pos:1,ids:[newRevId,opts,[]]}];nRevNum=1}}else{if(doc._revisions){doc._rev_tree=function makeRevTreeFromRevisions(revisions,opts){var i2,len,pos=revisions.start-revisions.ids.length+1,revisionIds=revisions.ids,ids=[revisionIds[0],opts,[]];for(i2=1,len=revisionIds.length;i21&&!descending){pseudoCursor={continue:function continuePseudoCursor(){var lastKey,newKeyRange;if(!keysBatch.length)return onBatch();lastKey=keysBatch[keysBatch.length-1];if(keyRange&&keyRange.upper)try{newKeyRange=IDBKeyRange.bound(lastKey,keyRange.upper,!0,keyRange.upperOpen)}catch(e3){if("DataError"===e3.name&&0===e3.code)return onBatch()}else newKeyRange=IDBKeyRange.lowerBound(lastKey,!0);keyRange=newKeyRange;keysBatch=null;valuesBatch=null;objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}};objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}else descending?objectStore.openCursor(keyRange,"prev").onsuccess=onCursor:objectStore.openCursor(keyRange).onsuccess=onCursor}function applyNext(){if(!running&&queue.length){running=!0;queue.shift()()}}function IdbPouch(opts,callback){var api=this;(function enqueueTask(action2,callback,PouchDB2){queue.push((function runAction(){action2((function runCallback(err2,res2){(function tryCode(fun,err2,res2,PouchDB2){try{fun(err2,res2)}catch(err3){PouchDB2.emit("error",err3)}})(callback,err2,res2,PouchDB2);running=!1;nextTick((function runNext(){applyNext()}))}))}));applyNext()})((function(thisCallback){(function init2(api,opts,callback){function enrichCallbackError(callback2){return function(error,result){error&&error instanceof Error&&!error.reason&&idbGlobalFailureError&&(error.reason=idbGlobalFailureError);callback2(error,result)}}function addDeletedOrLocalIndex(txn,callback2){var docStore=txn.objectStore(DOC_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1});docStore.openCursor().onsuccess=function(event2){var metadata,deleted,cursor=event2.target.result;if(cursor){deleted=isDeleted(metadata=cursor.value);metadata.deletedOrLocal=deleted?"1":"0";docStore.put(metadata);cursor.continue()}else callback2()}}function migrateLocalStore(txn,cb2){var localStore=txn.objectStore(LOCAL_STORE),docStore=txn.objectStore(DOC_STORE),seqStore=txn.objectStore(BY_SEQ_STORE);docStore.openCursor().onsuccess=function(event2){var metadata,docId,local,rev3,docIdRev,start,end,index6,range3,seqCursor,cursor2=event2.target.result;if(cursor2){local=isLocalId(docId=(metadata=cursor2.value).id);rev3=winningRev(metadata);if(local){docIdRev=docId+"::"+rev3;start=docId+"::";end=docId+"::~";index6=seqStore.index("_doc_id_rev");range3=IDBKeyRange.bound(start,end,!1,!1);(seqCursor=index6.openCursor(range3)).onsuccess=function(e3){if(seqCursor=e3.target.result){var data=seqCursor.value;data._doc_id_rev===docIdRev&&localStore.put(data);seqStore.delete(seqCursor.primaryKey);seqCursor.continue()}else{docStore.delete(cursor2.primaryKey);cursor2.continue()}}}else cursor2.continue()}else cb2&&cb2()}}function migrateAttsAndSeqs(txn,callback2){var seqStore=txn.objectStore(BY_SEQ_STORE),attStore=txn.objectStore(ATTACH_STORE),attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);attStore.count().onsuccess=function(e3){if(!e3.target.result)return callback2();seqStore.openCursor().onsuccess=function(e4){var doc,seq,atts,digestMap,j2,digests,digest,cursor=e4.target.result;if(!cursor)return callback2();doc=cursor.value;seq=cursor.primaryKey;atts=Object.keys(doc._attachments||{});digestMap={};for(j2=0;j2metadataSeq&&(metadataSeq=seq);cursor3.continue()}})()}}}var cached,req,dbName=opts.name,idb=null,idbGlobalFailureError=null;api._meta=null;api._remote=!1;api.type=function(){return"idb"};api._id=toPromise((function(callback2){callback2(null,api._meta.instanceId)}));api._bulkDocs=function idb_bulkDocs(req2,reqOpts,callback2){idbBulkDocs(opts,req2,reqOpts,api,idb,enrichCallbackError(callback2))};api._get=function idb_get(id,opts2,callback2){function finish(){callback2(err2,{doc,metadata,ctx:txn})}var doc,metadata,err2,txnResult,txn=opts2.ctx;if(!txn){if((txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")).error)return callback2(txnResult.error);txn=txnResult.txn}txn.objectStore(DOC_STORE).get(id).onsuccess=function(e3){var rev3,objectStore,key2;if(!(metadata=decodeMetadata(e3.target.result))){err2=createError(MISSING_DOC,"missing");return finish()}if(opts2.rev)rev3=opts2.latest?latest(opts2.rev,metadata):opts2.rev;else{rev3=metadata.winningRev;if(isDeleted(metadata)){err2=createError(MISSING_DOC,"deleted");return finish()}}objectStore=txn.objectStore(BY_SEQ_STORE);key2=metadata.id+"::"+rev3;objectStore.index("_doc_id_rev").get(key2).onsuccess=function(e4){(doc=e4.target.result)&&(doc=decodeDoc(doc));if(!doc){err2=createError(MISSING_DOC,"missing");return finish()}finish()}}};api._getAttachment=function(docId,attachId,attachment,opts2,callback2){var txn,txnResult,digest,type;if(opts2.ctx)txn=opts2.ctx;else{if((txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")).error)return callback2(txnResult.error);txn=txnResult.txn}digest=attachment.digest;type=attachment.content_type;txn.objectStore(ATTACH_STORE).get(digest).onsuccess=function(e3){readBlobData(e3.target.result.body,type,opts2.binary,(function(blobData){callback2(null,blobData)}))}};api._info=function idb_info(callback2){var updateSeq,docCount,txn,txnResult=openTransactionSafely(idb,[META_STORE,BY_SEQ_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);(txn=txnResult.txn).objectStore(META_STORE).get(META_STORE).onsuccess=function(e3){docCount=e3.target.result.docCount};txn.objectStore(BY_SEQ_STORE).openKeyCursor(null,"prev").onsuccess=function(e3){var cursor=e3.target.result;updateSeq=cursor?cursor.key:0};txn.oncomplete=function(){callback2(null,{doc_count:docCount,update_seq:updateSeq,idb_attachment_format:api._meta.blobSupport?"binary":"base64"})}};api._allDocs=function idb_allDocs(opts2,callback2){(function idbAllDocs(opts,idb,callback){function allDocsInner(winningRev$$1,metadata){var row={id:metadata.id,key:metadata.id,value:{rev:winningRev$$1}};if(metadata.deleted){if(keys3){results.push(row);row.value.deleted=!0;row.doc=null}}else if(skip--<=0){results.push(row);opts.include_docs&&function fetchDocAsynchronously(metadata,row,winningRev$$1){var key3=metadata.id+"::"+winningRev$$1;docIdRevIndex.get(key3).onsuccess=function onGetDoc(e3){row.doc=decodeDoc(e3.target.result)||{};if(opts.conflicts){var conflicts=collectConflicts(metadata);conflicts.length&&(row.doc._conflicts=conflicts)}fetchAttachmentsIfNecessary(row.doc,opts,txn)}}(metadata,row,winningRev$$1)}}function processBatch(batchValues){var i2,len,batchValue,metadata;for(i2=0,len=batchValues.length;i2{var cursor=e3.target.result;cursor&&cursor.key&&(updateSeq=cursor.key)});if(!keyRangeError&&0!==limit){if(keys3)return function allDocsKeys(keys3,docStore,onBatch){var valuesBatch=new Array(keys3.length),count=0;keys3.forEach((function(key2,index6){docStore.get(key2).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key2,error:"not_found"};++count===keys3.length&&onBatch(keys3,valuesBatch,{})}}))}(keys3,docStore,onBatch);if(-1===limit)return function getAll(objectStore,keyRange,onSuccess){if("function"!=typeof objectStore.getAll){var values=[];objectStore.openCursor(keyRange).onsuccess=function onCursor(e3){var cursor=e3.target.result;if(cursor){values.push(cursor.value);cursor.continue()}else onSuccess({target:{result:values}})}}else objectStore.getAll(keyRange).onsuccess=onSuccess}(docStore,keyRange,(function onGetAll(e3){var values=e3.target.result;opts.descending&&(values=values.reverse());processBatch(values)}));runBatchedCursor(docStore,keyRange,opts.descending,limit+skip,onBatch)}})(opts2,idb,enrichCallbackError(callback2))};api._changes=function idbChanges2(opts2){return function changes(opts,api,dbName,idb){function onGetMetadata(doc,seq,metadata,cb2){var docIdRev;if(metadata.seq!==seq)return cb2();if(metadata.winningRev===doc._rev)return cb2(metadata,doc);docIdRev=doc._id+"::"+metadata.winningRev;docIdRevIndex.get(docIdRev).onsuccess=function(e3){cb2(metadata,decodeDoc(e3.target.result))}}function finish(){opts.complete(null,{results,last_seq:lastSeq})}var id,docIds,lastSeq,limit,results,numResults,filter4,docIdsToMetadata,txn,bySeqStore,docStore,docIdRevIndex,objectStores,txnResult;if((opts=clone2(opts)).continuous){id=dbName+":"+uuid();changesHandler$1.addListener(dbName,id,api,opts);changesHandler$1.notify(dbName);return{cancel:function(){changesHandler$1.removeListener(dbName,id)}}}docIds=opts.doc_ids&&new Set(opts.doc_ids);opts.since=opts.since||0;lastSeq=opts.since;0===(limit="limit"in opts?opts.limit:-1)&&(limit=1);results=[];numResults=0;filter4=filterChange(opts);docIdsToMetadata=new Map;objectStores=[DOC_STORE,BY_SEQ_STORE];opts.attachments&&objectStores.push(ATTACH_STORE);if((txnResult=openTransactionSafely(idb,objectStores,"readonly")).error)return opts.complete(txnResult.error);(txn=txnResult.txn).onabort=idbError(opts.complete);txn.oncomplete=function onTxnComplete(){!opts.continuous&&opts.attachments?postProcessAttachments(results).then(finish):finish()};bySeqStore=txn.objectStore(BY_SEQ_STORE);docStore=txn.objectStore(DOC_STORE);docIdRevIndex=bySeqStore.index("_doc_id_rev");runBatchedCursor(bySeqStore,opts.since&&!opts.descending?IDBKeyRange.lowerBound(opts.since,!0):null,opts.descending,limit,(function onBatch(batchKeys,batchValues,cursor){function processMetadataAndWinningDoc(metadata,winningDoc){var filtered,change=opts.processChange(winningDoc,metadata,opts);lastSeq=change.seq=metadata.seq;if("object"==typeof(filtered=filter4(change)))return Promise.reject(filtered);if(!filtered)return Promise.resolve();numResults++;opts.return_docs&&results.push(change);return opts.attachments&&opts.include_docs?new Promise((function(resolve){fetchAttachmentsIfNecessary(winningDoc,opts,txn,(function(){postProcessAttachments([change],opts.binary).then((function(){resolve(change)}))}))})):Promise.resolve(change)}var winningDocs,metadatas,numDone;if(cursor&&batchKeys.length){winningDocs=new Array(batchKeys.length);metadatas=new Array(batchKeys.length);numDone=0;batchValues.forEach((function(value,i2){(function fetchWinningDocAndMetadata(doc,seq,cb2){if(docIds&&!docIds.has(doc._id))return cb2();var metadata=docIdsToMetadata.get(doc._id);if(metadata)return onGetMetadata(doc,seq,metadata,cb2);docStore.get(doc._id).onsuccess=function(e3){metadata=decodeMetadata(e3.target.result);docIdsToMetadata.set(doc._id,metadata);onGetMetadata(doc,seq,metadata,cb2)}})(decodeDoc(value),batchKeys[i2],(function(metadata,winningDoc){metadatas[i2]=metadata;winningDocs[i2]=winningDoc;++numDone===batchKeys.length&&function onBatchDone(){var i2,len,winningDoc,metadata,promises=[];for(i2=0,len=winningDocs.length;i20||end0||end0&&e3.oldVersion0&&(acc[naturalIndexName(fields)]=function correctIndexFields(fields){return["deleted"].concat(fields.map((function(field){return["_id","_rev","_deleted","_attachments"].includes(field)?field.substr(1):"data."+sanitise(field,!0)})))}(fields));return acc}),indexes2)}),{}),expectedIndexNames=Object.keys(expectedIndexes),systemIndexNames=["seq","deleted,id"];existingIndexNames.forEach((function(index6){-1===systemIndexNames.indexOf(index6)&&-1===expectedIndexNames.indexOf(index6)&&docStore.deleteIndex(index6)}));const newIndexNames=expectedIndexNames.filter((function(ei){return-1===existingIndexNames.indexOf(ei)}));try{newIndexNames.forEach((function(indexName){docStore.createIndex(indexName,expectedIndexes[indexName])}))}catch(err2){reject(err2)}}})(openReq,reject);if(pouchdbVersion<2){const docStore=openReq.transaction.objectStore(DOC_STORE2),metaStore=openReq.transaction.objectStore(META_LOCAL_STORE);docStore.openCursor().onsuccess=event2=>{const cursor=event2.target.result;if(!cursor)return;const doc=cursor.value;if(!isLocalId(doc.id))return cursor.continue();metaStore.put(doc).onsuccess=()=>{cursor.delete(doc).onsuccess=()=>{cursor.continue()}}}}};openReq.onblocked=function(e3){console.error("onblocked, this should never happen",e3)};openReq.onsuccess=function(e3){const idb=e3.target.result;idb.onabort=function(e4){console.error("Database has a global failure",e4.target.error);delete openDatabases2[opts.name];idb.close()};idb.onversionchange=function(){console.log("Database was made stale, closing handle");openDatabases2[opts.name].versionChangedWhileOpen=!0;idb.close()};idb.onclose=function(){console.log("Database was made stale, closing handle");opts.name in openDatabases2&&(openDatabases2[opts.name].versionChangedWhileOpen=!0)};let metadata={id:META_LOCAL_STORE};const txn=idb.transaction([META_LOCAL_STORE],"readwrite");txn.oncomplete=function(){resolve({idb,metadata})};const metaStore=txn.objectStore(META_LOCAL_STORE);metaStore.get(META_LOCAL_STORE).onsuccess=function(e4){metadata=e4.target.result||metadata;let changed=!1;if(!("doc_count"in metadata)){changed=!0;metadata.doc_count=0}if(!("seq"in metadata)){changed=!0;metadata.seq=0}if(!("db_uuid"in metadata)){changed=!0;metadata.db_uuid=uuid()}if("idb_attachment_format"in metadata){if(changed){api.blobSupport=metadata.idb_attachment_format;metaStore.put(metadata)}}else checkBlobSupport(txn,META_LOCAL_STORE,(blob=>({id:"blob-support",blob}))).then((blobSupport=>{api.blobSupport=metadata.idb_attachment_format=blobSupport?"binary":"base64";metaStore.put(metadata)}))}};openReq.onerror=function(e3){reject(e3.target.error)}})(openDatabases2,api,opts,resolve,reject)}))}return openDatabases2[opts.name]}function get3(txn,id,opts,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(DOC_STORE2).get(id).onsuccess=function(e3){const doc=e3.target.result;let rev3;rev3=opts.rev?opts.latest?latest(opts.rev,doc):opts.rev:doc&&doc.rev;if(!doc||doc.deleted&&!opts.rev||!(rev3 in doc.revs)){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[rev3].data;result._id=doc.id;result._rev=rev3;callback(null,{doc:result,metadata:doc,ctx:txn})}}function getAttachment(docId,attachId,attachment,opts,cb2){if(isLocalId(docId)){cb2(createError(MISSING_DOC,"missing"));return}const data=opts.metadata.attachments[attachment.digest].data;if("string"!=typeof data){if(opts.binary)return cb2(null,data);readAsBinaryString(data,(function(binString){cb2(null,thisBtoa(binString))}))}else opts.binary?cb2(null,b64ToBluffer(data,attachment.content_type)):cb2(null,data)}function createKeyRange2(start,end,inclusiveStart,inclusiveEnd,key2,descending){try{return key2?IDBKeyRange.only([0,key2]):descending?IDBKeyRange.bound(end,start,!inclusiveEnd,!inclusiveStart):IDBKeyRange.bound(start,end,!inclusiveStart,!inclusiveEnd)}catch(e3){return{error:e3}}}function handleKeyRangeError(opts,metadata,err2,callback){if("DataError"===err2.name&&0===err2.code){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}callback(createError(IDB_ERROR,err2.name,err2.message))}function getRevisionTree(txn,id,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(DOC_STORE2).get(id).onsuccess=function(e3){e3.target.result?callback(null,e3.target.result.rev_tree):callback(createError(MISSING_DOC))}}function doCompaction(txn,id,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2);docStore.get(id).onsuccess=function(e3){const doc=e3.target.result;traverseRevTree(doc.rev_tree,(function(isLeaf,pos,revHash,ctx,opts){const rev3=pos+"-"+revHash;-1!==revs.indexOf(rev3)&&(opts.status="missing")}));const attachments=[];revs.forEach((function(rev3){if(rev3 in doc.revs){if(doc.revs[rev3].data._attachments)for(const k2 in doc.revs[rev3].data._attachments)attachments.push(doc.revs[rev3].data._attachments[k2].digest);delete doc.revs[rev3]}}));attachments.forEach((function(digest){revs.forEach((function(rev3){delete doc.attachments[digest].revs[rev3]}));Object.keys(doc.attachments[digest].revs).length||delete doc.attachments[digest]}));docStore.put(doc)};txn.txn.oncomplete=function(){callback()}}function externaliseRecord(idbDoc){const doc=idbDoc.revs[idbDoc.rev].data;doc._id=idbDoc.id;doc._rev=idbDoc.rev;idbDoc.deleted&&(doc._deleted=!0);return doc}function getIndexHandle(pdb,fields,reject){const indexName=naturalIndexName(fields);return new Promise((function(resolve){pdb._openTransactionSafely([DOC_STORE2],"readonly",(function(err2,txn){if(err2)return idbError2(reject)(err2);txn.onabort=idbError2(reject);txn.ontimeout=idbError2(reject);-1===Array.from(txn.objectStore(DOC_STORE2).indexNames).indexOf(indexName)?pdb._freshen().then((function(){return getIndexHandle(pdb,fields,reject)})).then(resolve):resolve(txn.objectStore(DOC_STORE2).index(indexName))}))}))}function query(idb,signature,opts,fallback2){const pdb=this,parts=signature.split("/");return new Promise((function(resolve,reject){pdb.get("_design/"+parts[0]).then((function(ddoc){if(function isPartialFilterView(ddoc,viewName){return viewName in ddoc.views&&ddoc.views[viewName].options&&ddoc.views[viewName].options.def&&ddoc.views[viewName].options.def.partial_filter_selector}(ddoc,parts[1]))return fallback2(signature,opts).then(resolve,reject);const fields=rawIndexFields(ddoc,parts[1]);if(!fields)throw new Error("ddoc "+ddoc._id+" with view "+parts[1]+" does not have map.options.def.fields defined.");let skip=opts.skip,limit=Number.isInteger(opts.limit)&&opts.limit;return getIndexHandle(pdb,fields,reject).then((function(indexHandle){const keyRange=function generateKeyRange(opts){function defined(obj,k2){return void 0!==obj[k2]}function convert(key2,exact){return[0].concat(key2).map((function(k2){if(null===k2&&exact)return IDB_NULL;if(!0===k2)return IDB_TRUE;if(!1===k2)return IDB_FALSE;if(!exact){if(k2===COUCH_COLLATE_LO)return IDB_COLLATE_LO;if(Object.prototype.hasOwnProperty.call(k2,COUCH_COLLATE_HI))return IDB_COLLATE_HI}return k2}))}defined(opts,"inclusive_end")||(opts.inclusive_end=!0);defined(opts,"inclusive_start")||(opts.inclusive_start=!0);if(opts.descending){const realEndkey=opts.startkey,realInclusiveEnd=opts.inclusive_start;opts.startkey=opts.endkey;opts.endkey=realEndkey;opts.inclusive_start=opts.inclusive_end;opts.inclusive_end=realInclusiveEnd}try{return defined(opts,"key")?IDBKeyRange.only(convert(opts.key,!0)):defined(opts,"startkey")&&!defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),[1],!opts.inclusive_start,!0):!defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.upperBound(convert(opts.endkey),!opts.inclusive_end):defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),convert(opts.endkey),!opts.inclusive_start,!opts.inclusive_end):IDBKeyRange.only([0])}catch(err2){console.error("Could not generate keyRange",err2,opts);throw Error("Could not generate key range with "+JSON.stringify(opts))}}(opts),req=indexHandle.openCursor(keyRange,opts.descending?"prev":"next"),rows=[];req.onerror=idbError2(reject);req.onsuccess=function(e3){const cursor=e3.target.result;if(!cursor||0===limit)return resolve({rows});if(skip){cursor.advance(skip);skip=!1}else{limit&&(limit-=1);rows.push({doc:externaliseRecord(cursor.value)});cursor.continue()}}}))})).catch(reject)}))}function viewCleanup(idb,fallback2){return fallback2()}function purge(txn,docId,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2),deletedRevs=[];let documentWasRemovedCompletely=!1;docStore.get(docId).onsuccess=e3=>{const doc=e3.target.result;for(const rev3 of revs){doc.rev_tree=removeLeafFromRevTree(doc.rev_tree,rev3);delete doc.revs[rev3];deletedRevs.push(rev3)}if(0!==doc.rev_tree.length){doc.rev=winningRev(doc);doc.data=doc.revs[doc.rev].data;doc.attachments=function purgeAttachments(doc,revs){if(!doc.attachments)return{};for(let key2 in doc.attachments){const attachment=doc.attachments[key2];for(let rev3 of revs)attachment.revs[rev3]&&delete attachment.revs[rev3];0===Object.keys(attachment.revs).length&&delete doc.attachments[key2]}return doc.attachments}(doc,revs);docStore.put(doc)}else{docStore.delete(doc.id);documentWasRemovedCompletely=!0}};txn.txn.oncomplete=function(){callback(null,{ok:!0,deletedRevs,documentWasRemovedCompletely})}}function IndexeddbPouch(dbOpts,callback){dbOpts.view_adapter&&console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");const api=this;let metadata={};const $=function(fun){return function(){const args=Array.prototype.slice.call(arguments);setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;args.unshift(res2.idb);fun.apply(api,args)})).catch((function(err2){const last=args.pop();"function"==typeof last?last(err2):console.error(err2)}))}},$p=function(fun){return function(){const args=Array.prototype.slice.call(arguments);return setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;args.unshift(res2.idb);return fun.apply(api,args)}))}},$t2=function(fun,stores,mode){mode=mode||"readonly";return function(){const args=Array.prototype.slice.call(arguments),txn={};setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;txn.txn=res2.idb.transaction(stores,mode)})).catch((function(err2){console.error("Failed to establish transaction safely");console.error(err2);txn.error=err2})).then((function(){args.unshift(txn);fun.apply(api,args)}))}};api._openTransactionSafely=function(stores,mode,callback2){$t2((function(txn,callback3){callback3(txn.error,txn.txn)}),stores,mode)(callback2)};api._remote=!1;api.type=function(){return ADAPTER_NAME};api._id=$((function(_,cb2){cb2(null,metadata.db_uuid)}));api._info=$((function(_,cb2){return function info2(metadata,callback){callback(null,{doc_count:metadata.doc_count,update_seq:metadata.seq})}(metadata,cb2)}));api._get=$t2(get3,[DOC_STORE2]);api._getLocal=$t2((function(txn,id,callback2){return function getLocal(txn,id,api,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(META_LOCAL_STORE).get(id).onsuccess=function(e3){const doc=e3.target.result;if(!doc){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[doc.rev].data;result._id=doc.id;result._rev=doc.rev;if(result._attachments){const processing=[];for(const name in result._attachments)processing.push(processAttachment(name,doc,result,BINARY_ATTACHMENTS,api.blobSupport));Promise.all(processing).then((()=>callback(null,result))).catch(callback)}else callback(null,result)}}(txn,id,api,callback2)}),[META_LOCAL_STORE]);api._bulkDocs=$((function(_,req,opts,callback2){(function bulkDocs(api,req,opts,metadata,dbOpts,idbChanges2,callback){function docsRevsLimit(doc){return isLocalId(doc.id)?1:revsLimit}function revHasAttachment(doc,rev3,digest){return doc.revs[rev3]&&doc.revs[rev3].data._attachments&&Object.values(doc.revs[rev3].data._attachments).find((function(att){return att.digest===digest}))}function convertDocFormat(doc){const newDoc={id:doc.metadata.id,rev:doc.metadata.rev,rev_tree:doc.metadata.rev_tree,revs:doc.metadata.revs||{}};newDoc.revs[newDoc.rev]={data:doc.data,deleted:doc.metadata.deleted};return newDoc}function updateSeq(i2){i2===lastWriteIndex&&txn.objectStore(META_LOCAL_STORE).put(metadata)}let txn,error;const results=[],docs=[];let lastWriteIndex;const revsLimit=dbOpts.revs_limit||1e3,rewriteEnabled=-1===dbOpts.name.indexOf("-mrview-"),autoCompaction=dbOpts.auto_compaction;for(let i2=0,len=req.docs.length;i2{blobToBase64(attachment.data,(function(b64){attachment.data=b64;binaryMd53(binData,(function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)}))}))}))}return new Promise((function(resolve){binaryMd53(binData,(function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)}))}))}(data._attachments[k2])}));return Promise.all(attachments).then((function(newAttachments){const processed={};newAttachments.forEach((function(attachment){processed[attachment.name]=attachment;delete attachment.name}));data._attachments=processed;return data}))}));return Promise.all(promises)})().then((function(){api._openTransactionSafely([DOC_STORE2,META_LOCAL_STORE],"readwrite",(function(err2,_txn){if(err2)return callback(err2);txn=_txn;txn.onabort=function(){callback(error||createError(UNKNOWN_ERROR,"transaction was aborted"))};txn.ontimeout=idbError2(callback);txn.oncomplete=function(){idbChanges2.notify(dbOpts.name);callback(null,results)};(function fetchExistingDocs(txn2,docs2){function readDone(e3){e3.target.result&&(oldDocs[e3.target.result.id]=e3.target.result);++fetched===docs2.length&&function processDocs2(txn2,docs2,oldDocs){docs2.forEach((function(doc,i2){let newDoc;if("was_delete"in opts&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id))newDoc=createError(MISSING_DOC,"deleted");else if(opts.new_edits&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id)&&function rootIsMissing2(doc){return"missing"===doc.rev_tree[0].ids[1].status}(doc))newDoc=createError(REV_CONFLICT);else if(Object.prototype.hasOwnProperty.call(oldDocs,doc.id)){newDoc=function update2(txn2,doc,oldDoc){if(doc.rev in oldDoc.revs&&!opts.new_edits)return!1;const isRoot=/^1-/.test(doc.rev);if(oldDoc.deleted&&!doc.deleted&&opts.new_edits&&isRoot){const tmp=doc.revs[doc.rev].data;tmp._rev=oldDoc.rev;tmp._id=oldDoc.id;doc=convertDocFormat(parseDoc(tmp,opts.new_edits,dbOpts))}const merged=merge2(oldDoc.rev_tree,doc.rev_tree[0],docsRevsLimit(doc));doc.stemmedRevs=merged.stemmedRevs;doc.rev_tree=merged.tree;const revs=oldDoc.revs;revs[doc.rev]=doc.revs[doc.rev];doc.revs=revs;doc.attachments=oldDoc.attachments;if(opts.new_edits&&(oldDoc.deleted&&doc.deleted||!oldDoc.deleted&&"new_leaf"!==merged.conflicts||oldDoc.deleted&&!doc.deleted&&"new_branch"===merged.conflicts||oldDoc.rev===doc.rev))return createError(REV_CONFLICT);doc.wasDeleted=oldDoc.deleted;return doc}(0,doc,oldDocs[doc.id]);if(0==newDoc)return}else{const merged=merge2([],doc.rev_tree[0],docsRevsLimit(doc));doc.rev_tree=merged.tree;doc.stemmedRevs=merged.stemmedRevs;newDoc=doc;newDoc.isNewDoc=!0;newDoc.wasDeleted=doc.revs[doc.rev].deleted?1:0}if(newDoc.error)results[i2]=newDoc;else{oldDocs[newDoc.id]=newDoc;lastWriteIndex=i2;(function write(txn2,doc,i2){const winningRev$$1=winningRev(doc),writtenRev=doc.rev,isLocal=isLocalId(doc.id),theDoc=doc.revs[winningRev$$1].data,isNewDoc=doc.isNewDoc;if(rewriteEnabled){const result=rewrite(theDoc);if(result){doc.data=result;delete doc.data._attachments}else doc.data=theDoc}else doc.data=theDoc;doc.rev=winningRev$$1;doc.deleted=doc.revs[winningRev$$1].deleted?1:0;if(!isLocal){doc.seq=++metadata.seq;let delta=0;doc.isNewDoc?delta=doc.deleted?0:1:doc.wasDeleted!==doc.deleted&&(delta=doc.deleted?-1:1);metadata.doc_count+=delta}delete doc.isNewDoc;delete doc.wasDeleted;let revsToDelete=doc.stemmedRevs||[];if(autoCompaction&&!isNewDoc){const result=compactTree(doc);result.length&&(revsToDelete=revsToDelete.concat(result))}revsToDelete.length&&revsToDelete.forEach((function(rev3){delete doc.revs[rev3]}));delete doc.stemmedRevs;"attachments"in doc||(doc.attachments={});if(theDoc._attachments)for(const k2 in theDoc._attachments){const attachment=theDoc._attachments[k2];if(attachment.stub){if(!(attachment.digest in doc.attachments)){error=createError(MISSING_STUB);txn2.abort();return}revHasAttachment(doc,writtenRev,attachment.digest)&&(doc.attachments[attachment.digest].revs[writtenRev]=!0)}else{doc.attachments[attachment.digest]=attachment;doc.attachments[attachment.digest].revs={};doc.attachments[attachment.digest].revs[writtenRev]=!0;theDoc._attachments[k2]={stub:!0,digest:attachment.digest,content_type:attachment.content_type,length:attachment.length,revpos:parseInt(writtenRev,10)}}}if(isLocal&&doc.deleted){txn2.objectStore(META_LOCAL_STORE).delete(doc.id).onsuccess=function(){results[i2]={ok:!0,id:doc.id,rev:"0-0"}};updateSeq(i2);return}const docStore=isLocal?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).put(doc).onsuccess=function(){results[i2]={ok:!0,id:doc.id,rev:writtenRev};updateSeq(i2)}})(txn2,newDoc,i2)}}))}(txn2,docs2,oldDocs)}let fetched=0;const oldDocs={};docs2.forEach((function(doc){const docStore=isLocalId(doc.id)?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).get(doc.id).onsuccess=readDone}))})(txn,docs)}))})).catch((function(err2){callback(err2)}))})(api,req,opts,metadata,dbOpts,idbChanges,callback2)}));api._allDocs=$t2((function(txn,opts,cb2){(function allDocs(txn,metadata,opts,callback){function include_doc(row,doc){const docData=doc.revs[doc.rev].data;row.doc=docData;row.doc._id=doc.id;row.doc._rev=doc.rev;if(opts.conflicts){const conflicts=collectConflicts(doc);conflicts.length&&(row.doc._conflicts=conflicts)}if(opts.attachments&&docData._attachments)for(const name in docData._attachments)processing.push(processAttachment(name,doc,row.doc,opts.binary,metadata.idb_attachment_format))}function onTxnComplete(){const returnVal={total_rows:metadata.doc_count,offset:0,rows:results};opts.update_seq&&(returnVal.update_seq=metadata.seq);processing.length?Promise.all(processing).then((function(){callback(null,returnVal)})):callback(null,returnVal)}async function fetchResults(){function fetchNextBatch(kr2){return new Promise((resolve=>{dbIndex.getAll(kr2,100).onsuccess=e3=>{const batch=e3.target.result;for(let i2=0;i2=100){const lastSeenKey=[0,batch[batch.length-1].id],startKey=descending?kr2.upper:lastSeenKey,endKey=descending?lastSeenKey:kr2.upper;if(startKey[1]!==endKey[1])return resolve(createKeyRange2(startKey,endKey,!!descending,!descending&&inclusiveEnd,key2,descending))}return resolve()}}))}let kr=keyRange;do{kr=await fetchNextBatch(kr)}while(kr);descending&&results.reverse();return txn.txn.commit()}if(txn.error)return callback(txn.error);if(0===opts.limit){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}const results=[],processing=[],key2="key"in opts&&opts.key,keys3="keys"in opts&&opts.keys;let skip=opts.skip||0,limit="number"==typeof opts.limit?opts.limit:void 0;const inclusiveEnd=!1!==opts.inclusive_end,descending="descending"in opts&&opts.descending?"prev":null,start="startkey"in opts?opts.startkey:descending?"￿":"",end="endkey"in opts?opts.endkey:descending?"":"￿",docStore=txn.txn.objectStore(DOC_STORE2);if(keys3){txn.txn.oncomplete=onTxnComplete;return function allDocsKeys2(keys3,docStore,allDocsInner){const valuesBatch=new Array(keys3.length);let count=0;keys3.forEach((function(key2,index6){docStore.get(key2).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key2,error:"not_found"};count++;count===keys3.length&&valuesBatch.forEach((function(doc){allDocsInner(doc)}))}}))}(keys3,docStore,(doc=>{if(doc.error)return results.push(doc);const row={id:doc.id,key:doc.id,value:{rev:doc.rev}};if(doc.deleted){row.value.deleted=!0;row.doc=null}else opts.include_docs&&include_doc(row,doc);results.push(row)}))}let keyRange=createKeyRange2([0,start],[0,end],!0,inclusiveEnd,key2,descending);if(keyRange.error)return handleKeyRangeError(opts,metadata,keyRange.error,callback);txn.txn.oncomplete=onTxnComplete;const dbIndex=docStore.index("deleted,id");if(skip||limit){let firstKey,limitKey=limit>0;dbIndex.openKeyCursor(keyRange,descending||"next").onsuccess=e3=>{const cursor=e3.target.result;if(skip){if(!cursor)return txn.txn.commit();cursor.advance(skip);skip=0}else{if(void 0===firstKey){firstKey=cursor&&cursor.key;if(!firstKey)return txn.txn.commit()}if(limit){if(limit>1&&cursor){cursor.advance(limit-1);limit=void 0;return}limit=void 0}limitKey&&(limitKey=cursor&&cursor.key);limitKey||(limitKey=descending?keyRange.lower:keyRange.upper);keyRange=createKeyRange2(firstKey,limitKey,!0,inclusiveEnd,key2,descending);if(keyRange.error){txn.txn.abort();return handleKeyRangeError(opts,metadata,keyRange.error,callback)}fetchResults()}}}else fetchResults()})(txn,metadata,opts,cb2)}),[DOC_STORE2]);api._getAttachment=getAttachment;api._changes=$t2((function(txn,opts){(function changes2(txn,idbChanges2,api,dbOpts,opts){if(txn.error)return opts.complete(txn.error);if(opts.continuous){const id=dbOpts.name+":"+uuid();idbChanges2.addListener(dbOpts.name,id,api,opts);idbChanges2.notify(dbOpts.name);return{cancel:function(){idbChanges2.removeListener(dbOpts.name,id)}}}let limit="limit"in opts?opts.limit:-1;0===limit&&(limit=1);const store=txn.txn.objectStore(DOC_STORE2).index("seq"),filter4=filterChange(opts);let received=0,lastSeq=opts.since||0;const results=[],processing=[];let req;req=opts.descending?store.openCursor(null,"prev"):store.openCursor(IDBKeyRange.lowerBound(opts.since,!0));txn.txn.oncomplete=function onTxnComplete(){Promise.all(processing).then((function(){opts.complete(null,{results,last_seq:lastSeq})}))};req.onsuccess=function onReqSuccess(e3){if(!e3.target.result)return;const cursor=e3.target.result,doc=cursor.value;doc.data=doc.revs[doc.rev].data;doc.data._id=doc.id;doc.data._rev=doc.rev;doc.deleted&&(doc.data._deleted=!0);if(opts.doc_ids&&-1===opts.doc_ids.indexOf(doc.id))return cursor.continue();const change=opts.processChange(doc.data,doc,opts);change.seq=doc.seq;lastSeq=doc.seq;const filtered=filter4(change);if("object"==typeof filtered)return opts.complete(filtered);if(filtered){received++;opts.return_docs&&results.push(change);if(opts.include_docs&&opts.attachments&&doc.data._attachments){const promises=[];for(const name in doc.data._attachments){const p4=processAttachment(name,doc,change.doc,opts.binary,api.blobSupport);promises.push(p4);processing.push(p4)}Promise.all(promises).then((function(){opts.onChange(change)}))}else opts.onChange(change)}received!==limit&&cursor.continue()}})(txn,idbChanges,api,dbOpts,opts)}),[DOC_STORE2]);api._getRevisionTree=$t2(getRevisionTree,[DOC_STORE2]);api._doCompaction=$t2(doCompaction,[DOC_STORE2],"readwrite");api._customFindAbstractMapper={query:$p(query),viewCleanup:$p(viewCleanup)};api._destroy=function(opts,callback2){return function destroy(dbOpts,openDatabases2,idbChanges2,callback){function doDestroy(){indexedDB.deleteDatabase(dbOpts.name).onsuccess=function(){delete openDatabases2[dbOpts.name];callback(null,{ok:!0})}}idbChanges2.removeAllListeners(dbOpts.name);dbOpts.name in openDatabases2?openDatabases2[dbOpts.name].then((function(res2){res2.idb.close();doDestroy()})):doDestroy()}(dbOpts,openDatabases,idbChanges,callback2)};api._close=$((function(db,cb2){delete openDatabases[dbOpts.name];db.close();cb2()}));api._freshen=function(){return new Promise((function(resolve){api._close((function(){$(resolve)()}))}))};api._purge=$t2(purge,[DOC_STORE2],"readwrite");setTimeout((function(){callback(null,api)}))}function readAttachmentsAsBlobOrBuffer(row){const doc=row.doc||row.ok,atts=doc&&doc._attachments;atts&&Object.keys(atts).forEach((function(filename){const att=atts[filename];att.data=b64ToBluffer(att.data,att.content_type)}))}function encodeDocId(id){return/^_design/.test(id)?"_design/"+encodeURIComponent(id.slice(8)):id.startsWith("_local/")?"_local/"+encodeURIComponent(id.slice(7)):encodeURIComponent(id)}function preprocessAttachments2(doc){return doc._attachments&&Object.keys(doc._attachments)?Promise.all(Object.keys(doc._attachments).map((function(key2){const attachment=doc._attachments[key2];if(attachment.data&&"string"!=typeof attachment.data)return new Promise((function(resolve){blobToBase64(attachment.data,resolve)})).then((function(b64){attachment.data=b64}))}))):Promise.resolve()}function genDBUrl(opts,path2){return genUrl(opts,opts.db+"/"+path2)}function genUrl(opts,path2){const pathDel=opts.path?"/":"";return opts.protocol+"://"+opts.host+(opts.port?":"+opts.port:"")+"/"+opts.path+pathDel+path2}function paramsToStr(params){const paramKeys=Object.keys(params);return 0===paramKeys.length?"":"?"+paramKeys.map((key2=>key2+"="+encodeURIComponent(params[key2]))).join("&")}function HttpPouch(opts,callback){function adapterFun$$1(name,fun){return adapterFun(name,(function(...args){setup2().then((function(){return fun.apply(this,args)})).catch((function(e3){args.pop()(e3)}))})).bind(api)}async function fetchJSON(url,options){const result={};(options=options||{}).headers=options.headers||new h2;options.headers.get("Content-Type")||options.headers.set("Content-Type","application/json");options.headers.get("Accept")||options.headers.set("Accept","application/json");const response=await ourFetch(url,options);result.ok=response.ok;result.status=response.status;const json=await response.json();result.data=json;if(!result.ok){result.data.status=result.status;throw generateErrorFromResponse(result.data)}Array.isArray(result.data)&&(result.data=result.data.map((function(v2){return v2.error||v2.missing?generateErrorFromResponse(v2):v2})));return result}async function setup2(){if(opts.skip_setup)return Promise.resolve();if(setupPromise)return setupPromise;setupPromise=fetchJSON(dbUrl).catch((function(err2){if(err2&&err2.status&&404===err2.status){explainError(404,"PouchDB is just detecting if the remote exists.");return fetchJSON(dbUrl,{method:"PUT"})}return Promise.reject(err2)})).catch((function(err2){return!(!err2||!err2.status||412!==err2.status)||Promise.reject(err2)}));setupPromise.catch((function(){setupPromise=null}));return setupPromise}function encodeAttachmentId(attachmentId){return attachmentId.split("/").map(encodeURIComponent).join("/")}const api=this,host=function getHost(name,opts){if(function hasUrlPrefix(opts){if(!opts.prefix)return!1;const protocol=parseUri(opts.prefix).protocol;return"http"===protocol||"https"===protocol}(opts)){const dbName=opts.name.substr(opts.prefix.length);name=opts.prefix.replace(/\/?$/,"/")+encodeURIComponent(dbName)}const uri=parseUri(name);(uri.user||uri.password)&&(uri.auth={username:uri.user,password:uri.password});const parts=uri.path.replace(/(^\/|\/$)/g,"").split("/");uri.db=parts.pop();-1===uri.db.indexOf("%")&&(uri.db=encodeURIComponent(uri.db));uri.path=parts.join("/");return uri}(opts.name,opts),dbUrl=genDBUrl(host,"");opts=clone2(opts);const ourFetch=async function(url,options){(options=options||{}).headers=options.headers||new h2;options.credentials="include";if(opts.auth||host.auth){const nAuth=opts.auth||host.auth,str=nAuth.username+":"+nAuth.password,token=thisBtoa(unescape(encodeURIComponent(str)));options.headers.set("Authorization","Basic "+token)}const headers=opts.headers||{};Object.keys(headers).forEach((function(key2){options.headers.append(key2,headers[key2])}));(function shouldCacheBust(opts){const ua="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",isIE=-1!==ua.indexOf("msie"),isTrident=-1!==ua.indexOf("trident"),isEdge=-1!==ua.indexOf("edge"),isGET=!("method"in opts)||"GET"===opts.method;return(isIE||isTrident||isEdge)&&isGET})(options)&&(url+=(-1===url.indexOf("?")?"?":"&")+"_nonce="+Date.now());const fetchFun=opts.fetch||f3;return await fetchFun(url,options)};let setupPromise;nextTick((function(){callback(null,api)}));api._remote=!0;api.type=function(){return"http"};api.id=adapterFun$$1("id",(async function(callback2){let result;try{const response=await ourFetch(genUrl(host,""));result=await response.json()}catch(err2){result={}}callback2(null,result&&result.uuid?result.uuid+host.db:genDBUrl(host,""))}));api.compact=adapterFun$$1("compact",(async function(opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}opts2=clone2(opts2);await fetchJSON(genDBUrl(host,"_compact"),{method:"POST"});(function ping(){api.info((function(err2,res2){res2&&!res2.compact_running?callback2(null,{ok:!0}):setTimeout(ping,opts2.interval||200)}))})()}));api.bulkGet=adapterFun("bulkGet",(function(opts2,callback2){async function doBulkGet(cb2){const params={};opts2.revs&&(params.revs=!0);opts2.attachments&&(params.attachments=!0);opts2.latest&&(params.latest=!0);try{const result=await fetchJSON(genDBUrl(host,"_bulk_get"+paramsToStr(params)),{method:"POST",body:JSON.stringify({docs:opts2.docs})});opts2.attachments&&opts2.binary&&result.data.results.forEach((function(res2){res2.docs.forEach(readAttachmentsAsBlobOrBuffer)}));cb2(null,result.data)}catch(error){cb2(error)}}function doBulkGetShim(){function onResult(batchNum){return function(err2,res2){results[batchNum]=res2.results;++numDone===numBatches&&callback2(null,{results:results.flat()})}}const batchSize=MAX_SIMULTANEOUS_REVS,numBatches=Math.ceil(opts2.docs.length/batchSize);let numDone=0;const results=new Array(numBatches);for(let i2=0;i2batchSize?batchSize:leftToFetch;const url=genDBUrl(host,"_changes"+paramsToStr(params)),fetchOpts={signal:controller.signal,method,body:JSON.stringify(body)};lastFetchedSeq=since;if(!opts2.aborted)try{await setup2();callback2(null,(await fetchJSON(url,fetchOpts)).data)}catch(error){callback2(error)}},results={results:[]},fetched=function(err2,res2){if(opts2.aborted)return;let raw_results_length=0;if(res2&&res2.results){raw_results_length=res2.results.length;results.last_seq=res2.last_seq;let pending2=null,lastSeq=null;"number"==typeof res2.pending&&(pending2=res2.pending);"string"!=typeof results.last_seq&&"number"!=typeof results.last_seq||(lastSeq=results.last_seq);({}).query=opts2.query_params;res2.results=res2.results.filter((function(c3){leftToFetch--;const ret=filterChange(opts2)(c3);if(ret){opts2.include_docs&&opts2.attachments&&opts2.binary&&readAttachmentsAsBlobOrBuffer(c3);opts2.return_docs&&results.results.push(c3);opts2.onChange(c3,pending2,lastSeq)}return ret}))}else if(err2){opts2.aborted=!0;opts2.complete(err2);return}res2&&res2.last_seq&&(lastFetchedSeq=res2.last_seq);const finished=limit&&leftToFetch<=0||res2&&raw_results_length0||end0||end{var filenames=Object.keys(remoteDoc._attachments);attachments.forEach((function(attachment,i2){var att=remoteDoc._attachments[filenames[i2]];delete att.stub;delete att.length;att.data=attachment}));return remoteDoc})):remoteDoc})))}))).then((function(results){resultDocs=resultDocs.concat(results.flat().filter(Boolean))}))}))})).then((function returnResult(){return{ok,docs:resultDocs}}))}(src,target,currentBatch.diffs,returnValue).then((function(got){currentBatch.error=!got.ok;got.docs.forEach((function(doc){delete currentBatch.diffs[doc._id];result.docs_read++;currentBatch.docs.push(doc)}))}))}function startNextBatch(){if(!returnValue.cancelled&&!currentBatch)if(0!==batches.length){currentBatch=batches.shift();returnValue.emit("checkpoint",{start_next_batch:currentBatch.seq});(function getDiffs(){var diff={};currentBatch.changes.forEach((function(change){returnValue.emit("checkpoint",{revs_diff:change});"_user/"!==change.id&&(diff[change.id]=change.changes.map((function(x2){return x2.rev})))}));return target.revsDiff(diff).then((function(diffs){if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}currentBatch.diffs=diffs}))})().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch((function(err2){abortReplication("batch processing terminated with error",err2)}))}else processPendingBatch(!0)}function processPendingBatch(immediate){if(0!==pendingBatch.changes.length){if(immediate||changesCompleted||pendingBatch.changes.length>=batch_size){batches.push(pendingBatch);pendingBatch={seq:0,changes:[],docs:[]};if("pending"===returnValue.state||"stopped"===returnValue.state){returnValue.state="active";returnValue.emit("active")}startNextBatch()}}else if(0===batches.length&&!currentBatch){if(continuous&&changesOpts.live||changesCompleted){returnValue.state="pending";returnValue.emit("paused")}changesCompleted&&completeReplication()}}function abortReplication(reason,err2){if(!replicationCompleted){err2.message||(err2.message=reason);result.ok=!1;result.status="aborting";batches=[];pendingBatch={seq:0,changes:[],docs:[]};completeReplication(err2)}}function completeReplication(fatalError){if(!replicationCompleted){if(returnValue.cancelled){result.status="cancelled";if(writingCheckpoint)return}result.status=result.status||"complete";result.end_time=(new Date).toISOString();result.last_seq=last_seq;replicationCompleted=!0;src.activeTasks.remove(taskId,fatalError);if(fatalError){(fatalError=createError(fatalError)).result=result;var errorName=(fatalError.name||"").toLowerCase();if("unauthorized"===errorName||"forbidden"===errorName){returnValue.emit("error",fatalError);returnValue.removeAllListeners()}else(function backOff(opts,returnValue,error,callback){var backOffSet,removeBackOffSetter;if(!1!==opts.retry){"function"!=typeof opts.back_off_function&&(opts.back_off_function=defaultBackOff);returnValue.emit("requestError",error);if("active"===returnValue.state||"pending"===returnValue.state){returnValue.emit("paused",error);returnValue.state="stopped";backOffSet=function backoffTimeSet(){opts.current_back_off=STARTING_BACK_OFF};removeBackOffSetter=function removeBackOffTimeSet(){returnValue.removeListener("active",backOffSet)};returnValue.once("paused",removeBackOffSetter);returnValue.once("active",backOffSet)}opts.current_back_off=opts.current_back_off||STARTING_BACK_OFF;opts.current_back_off=opts.back_off_function(opts.current_back_off);setTimeout(callback,opts.current_back_off)}else{returnValue.emit("error",error);returnValue.removeAllListeners()}})(opts,returnValue,fatalError,(function(){replicate(src,target,opts,returnValue)}))}else{returnValue.emit("complete",result);returnValue.removeAllListeners()}}}function onChange(change,pending2,lastSeq){var task,completed;if(returnValue.cancelled)return completeReplication();"number"==typeof pending2&&(pendingBatch.pending=pending2);if(filterChange(opts)(change)){pendingBatch.seq=change.seq||lastSeq;pendingBatch.changes.push(change);returnValue.emit("checkpoint",{pending_batch:pendingBatch.seq});nextTick((function(){processPendingBatch(0===batches.length&&changesOpts.live)}))}else if(task=src.activeTasks.get(taskId)){completed=task.completed_items||0;src.activeTasks.update(taskId,{completed_items:++completed})}}function onChangesComplete(changes3){changesPending=!1;if(returnValue.cancelled)return completeReplication();if(changes3.results.length>0){changesOpts.since=changes3.results[changes3.results.length-1].seq;getChanges();processPendingBatch(!0)}else{var complete=function(){if(continuous){changesOpts.live=!0;getChanges()}else changesCompleted=!0;processPendingBatch(!0)};if(currentBatch||0!==changes3.results.length)complete();else{writingCheckpoint=!0;checkpointer.writeCheckpoint(changes3.last_seq,session).then((function(){writingCheckpoint=!1;result.last_seq=last_seq=changes3.last_seq;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}complete()})).catch(onCheckpointError)}}}function onChangesError(err2){changesPending=!1;if(returnValue.cancelled)return completeReplication();abortReplication("changes rejected",err2)}function getChanges(){function abortChanges(){changes3.cancel()}function removeListener(){returnValue.removeListener("cancel",abortChanges)}if(!changesPending&&!changesCompleted&&batches.length{const field=getKey2(obj);return getFieldFromDoc(doc,parseField(field))}))}async function createIndex$1(db,requestDef){function getMd5(){return md5||(md5=function stringMd56(string){return import_spark_md56.default.hash(string)}(JSON.stringify(requestDef)))}const originalIndexDef=clone2((requestDef=massageCreateIndexRequest(requestDef)).index);requestDef.index=massageIndexDef(requestDef.index);(function validateIndex(index6){const ascFields=index6.fields.filter((function(field){return"asc"===getValue(field)}));if(0!==ascFields.length&&ascFields.length!==index6.fields.length)throw new Error("unsupported mixed sorting")})(requestDef.index);let md5;const viewName=requestDef.name||"idx-"+getMd5(),ddocName=requestDef.ddoc||"idx-"+getMd5(),ddocId="_design/"+ddocName;let hasInvalidLanguage=!1,viewExists=!1;db.constructor.emit("debug",["find","creating index",ddocId]);await upsert2(db,ddocId,(function updateDdoc(doc){doc._rev&&"query"!==doc.language&&(hasInvalidLanguage=!0);doc.language="query";doc.views=doc.views||{};viewExists=!!doc.views[viewName];if(viewExists)return!1;doc.views[viewName]={map:{fields:mergeObjects(requestDef.index.fields),partial_filter_selector:requestDef.index.partial_filter_selector},reduce:"_count",options:{def:originalIndexDef}};return doc}));if(hasInvalidLanguage)throw new Error('invalid language for ddoc with id "'+ddocId+'" (should be "query")');const signature=ddocName+"/"+viewName;await abstractMapper$1(db).query.call(db,signature,{limit:0,reduce:!1});return{id:ddocId,name:viewName,result:viewExists?"exists":"created"}}async function getIndexes$1(db){const allDocsRes=await db.allDocs({startkey:"_design/",endkey:"_design/￿",include_docs:!0}),res2={indexes:[{ddoc:null,name:"_all_docs",type:"special",def:{fields:[{_id:"asc"}]}}]};res2.indexes=flatten(res2.indexes,allDocsRes.rows.filter((function(row){return"query"===row.doc.language})).map((function(row){return(void 0!==row.doc.views?Object.keys(row.doc.views):[]).map((function(viewName){const view=row.doc.views[viewName];return{ddoc:row.id,name:viewName,type:"json",def:massageIndexDef(view.options.def)}}))})));res2.indexes.sort((function(left,right){return compare2(left.name,right.name)}));res2.total_rows=res2.indexes.length;return res2}function checkFieldInIndex(index6,field){return index6.def.fields.some((key2=>getKey2(key2)===field))}function userOperatorLosesPrecision(selector,field){return"$eq"!==getKey2(selector[field])}function sortFieldsByIndex(userFields,index6){const indexFields=index6.def.fields.map(getKey2);return userFields.slice().sort((function(a2,b3){let aIdx=indexFields.indexOf(a2),bIdx=indexFields.indexOf(b3);-1===aIdx&&(aIdx=Number.MAX_VALUE);-1===bIdx&&(bIdx=Number.MAX_VALUE);return compare2(aIdx,bIdx)}))}function getInMemoryFields(coreInMemoryFields,index6,selector,userFields){const result=flatten(coreInMemoryFields,function getBasicInMemoryFields(index6,selector,userFields){let needToFilterInMemory=!1;for(let i2=0,len=(userFields=sortFieldsByIndex(userFields,index6)).length;i2=sortFields.length?selectorFields:sortFields;if(0===sortFields.length)return{fields:userFields};userFields=userFields.sort((function(left,right){let leftIdx=sortFields.indexOf(left);-1===leftIdx&&(leftIdx=Number.MAX_VALUE);let rightIdx=sortFields.indexOf(right);-1===rightIdx&&(rightIdx=Number.MAX_VALUE);return leftIdxrightIdx?1:0}));return{fields:userFields,sortOrder:sort.map(getKey2)}}(selector,sort),userFields=userFieldsRes.fields,index6=function findBestMatchingIndex(selector,userFields,sortOrder,indexes2,useIndex){const matchingIndexes=function findMatchingIndexes(selector,userFields,sortOrder,indexes2){return indexes2.filter((function(index6){return function checkIndexMatches(index6,sortOrder,fields,selector){const indexFields=index6.def.fields.map(getKey2);return!!function checkIndexFieldsMatch(indexFields,sortOrder,fields){if(sortOrder){const sortMatches=function oneArrayIsStrictSubArrayOfOther(left,right){return!(left.length>right.length)&&oneArrayIsSubArrayOfOther(left,right)}(sortOrder,indexFields),selectorMatches=oneArrayIsSubArrayOfOther(fields,indexFields);return sortMatches&&selectorMatches}return function oneSetIsSubArrayOfOther(left,right){left=left.slice();for(const field of right){if(!left.length)break;const leftIdx=left.indexOf(field);if(-1===leftIdx)return!1;left.splice(leftIdx,1)}return!0}(fields,indexFields)}(indexFields,sortOrder,fields)&&function checkFieldsLogicallySound(indexFields,selector){const matcher=selector[indexFields[0]];return void 0===matcher||!(1===Object.keys(matcher).length&&"$ne"===getKey2(matcher))}(indexFields,selector)}(index6,sortOrder,userFields,selector)}))}(selector,userFields,sortOrder,indexes2);if(0===matchingIndexes.length){if(useIndex)throw{error:"no_usable_index",message:"There is no index available for this selector."};const defaultIndex=indexes2[0];defaultIndex.defaultUsed=!0;return defaultIndex}if(1===matchingIndexes.length&&!useIndex)return matchingIndexes[0];const userFieldsMap=function arrayToObject(arr){const res2={};for(const field of arr)res2[field]=!0;return res2}(userFields);if(useIndex){const useIndexDdoc="_design/"+useIndex[0],useIndexName=2===useIndex.length&&useIndex[1],index6=matchingIndexes.find((function(index7){return!(!useIndexName||index7.ddoc!==useIndexDdoc||useIndexName!==index7.name)||index7.ddoc===useIndexDdoc}));if(!index6)throw{error:"unknown_error",message:"Could not find that index or could not use that index for the query"};return index6}return function max2(arr,fun){let max3=null,maxScore=-1;for(const element2 of arr){const score=fun(element2);if(score>maxScore){maxScore=score;max3=element2}}return max3}(matchingIndexes,(function scoreIndex(index6){const indexFields=index6.def.fields.map(getKey2);let score=0;for(const indexField of indexFields)userFieldsMap[indexField]&&score++;return score}))}(selector,userFields,userFieldsRes.sortOrder,indexes2,request2.use_index),coreQueryPlan=function getCoreQueryPlan(selector,index6){return index6.defaultUsed?function getDefaultQueryPlan(selector){return{queryOpts:{startkey:null},inMemoryFields:[Object.keys(selector)]}}(selector):1===index6.def.fields.length?function getSingleFieldCoreQueryPlan(selector,index6){const field=getKey2(index6.def.fields[0]),matcher=selector[field]||{},inMemoryFields=[],userOperators=Object.keys(matcher);let combinedOpts;for(const userOperator of userOperators){isNonLogicalMatcher(userOperator)&&inMemoryFields.push(field);const newQueryOpts=getSingleFieldQueryOptsFor(userOperator,matcher[userOperator]);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newQueryOpts]):newQueryOpts}return{queryOpts:combinedOpts,inMemoryFields}}(selector,index6):function getMultiFieldQueryOpts(selector,index6){function finish(i2){!1!==inclusiveStart&&startkey.push(COLLATE_LO);!1!==inclusiveEnd&&endkey.push(COLLATE_HI);inMemoryFields=indexFields.slice(i2)}const indexFields=index6.def.fields.map(getKey2);let inMemoryFields=[];const startkey=[],endkey=[];let inclusiveStart,inclusiveEnd;for(let i2=0,len=indexFields.length;i20){const usingGtlt="$gt"in matcher||"$gte"in matcher||"$lt"in matcher||"$lte"in matcher,previousKeys=Object.keys(selector[indexFields[i2-1]]),previousWasEq=arrayEquals(previousKeys,["$eq"]),previousWasSame=arrayEquals(previousKeys,Object.keys(matcher));if(usingGtlt&&!previousWasEq&&!previousWasSame){finish(i2);break}}const userOperators=Object.keys(matcher);let combinedOpts=null;for(const userOperator of userOperators){const newOpts=getMultiFieldCoreQueryPlan(userOperator,matcher[userOperator]);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newOpts]):newOpts}startkey.push("startkey"in combinedOpts?combinedOpts.startkey:COLLATE_LO);endkey.push("endkey"in combinedOpts?combinedOpts.endkey:COLLATE_HI);"inclusive_start"in combinedOpts&&(inclusiveStart=combinedOpts.inclusive_start);"inclusive_end"in combinedOpts&&(inclusiveEnd=combinedOpts.inclusive_end)}const res2={startkey,endkey};void 0!==inclusiveStart&&(res2.inclusive_start=inclusiveStart);void 0!==inclusiveEnd&&(res2.inclusive_end=inclusiveEnd);return{queryOpts:res2,inMemoryFields}}(selector,index6)}(selector,index6);return{queryOpts:coreQueryPlan.queryOpts,index:index6,inMemoryFields:getInMemoryFields(coreQueryPlan.inMemoryFields,index6,selector,userFields)}}(requestDef,getIndexesRes.indexes);db.constructor.emit("debug",["find","query plan",queryPlan]);const indexToUse=queryPlan.index;(function validateSort(requestDef,index6){if(index6.defaultUsed&&requestDef.sort){const noneIdSorts=requestDef.sort.filter((function(sortItem){return"_id"!==Object.keys(sortItem)[0]})).map((function(sortItem){return Object.keys(sortItem)[0]}));if(noneIdSorts.length>0)throw new Error('Cannot sort on field(s) "'+noneIdSorts.join(",")+'" when using the default index')}index6.defaultUsed})(requestDef,indexToUse);let opts=Object.assign({include_docs:!0,reduce:!1,indexes_count:getIndexesRes.total_rows},queryPlan.queryOpts);if("startkey"in opts&&"endkey"in opts&&collate(opts.startkey,opts.endkey)>0)return{docs:[]};if(requestDef.sort&&"string"!=typeof requestDef.sort[0]&&"desc"===getValue(requestDef.sort[0])){opts.descending=!0;opts=function reverseOptions(opts){const newOpts=clone2(opts);delete newOpts.startkey;delete newOpts.endkey;delete newOpts.inclusive_start;delete newOpts.inclusive_end;"endkey"in opts&&(newOpts.startkey=opts.endkey);"startkey"in opts&&(newOpts.endkey=opts.startkey);"inclusive_start"in opts&&(newOpts.inclusive_end=opts.inclusive_start);"inclusive_end"in opts&&(newOpts.inclusive_start=opts.inclusive_end);return newOpts}(opts)}if(!queryPlan.inMemoryFields.length){opts.limit=requestDef.limit;"skip"in requestDef&&(opts.skip=requestDef.skip)}if(explain2)return Promise.resolve(queryPlan,opts);const res2=await async function queryAllOrIndex(db,opts,indexToUse){return"_all_docs"===indexToUse.name?async function doAllDocs(db,originalOpts){const opts=clone2(originalOpts);if(opts.descending){"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.endkey="");"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.limit=0)}else{"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.startkey="");"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.limit=0)}"key"in opts&&"string"!=typeof opts.key&&(opts.limit=0);if(opts.limit>0&&opts.indexes_count){opts.original_limit=opts.limit;opts.limit+=opts.indexes_count}const res2=await db.allDocs(opts);res2.rows=res2.rows.filter((function(row){return!/^_design\//.test(row.id)}));opts.original_limit&&(opts.limit=opts.original_limit);res2.rows=res2.rows.slice(0,opts.limit);return res2}(db,opts):abstractMapper$1(db).query.call(db,function indexToSignature(index6){return index6.ddoc.substring(8)+"/"+index6.name}(indexToUse),opts)}(db,opts,indexToUse);!1===opts.inclusive_start&&(res2.rows=function filterInclusiveStart(rows,targetValue,index6){const indexFields=index6.def.fields;let startAt=0;for(const row of rows){let docKey=getKeyFromDoc(row.doc,index6);if(1===indexFields.length)docKey=docKey[0];else for(;docKey.length>targetValue.length;)docKey.pop();if(Math.abs(collate(docKey,targetValue))>0)break;++startAt}return startAt>0?rows.slice(startAt):rows}(res2.rows,opts.startkey,indexToUse));queryPlan.inMemoryFields.length&&(res2.rows=filterInMemoryFields(res2.rows,requestDef,queryPlan.inMemoryFields));const resp={docs:res2.rows.map((function(row){const doc=row.doc;return requestDef.fields?function pick2(obj,arr){const res2={};for(const field of arr){const parsedField=parseField(field),value=getFieldFromDoc(obj,parsedField);void 0!==value&&setFieldInDoc(res2,parsedField,value)}return res2}(doc,requestDef.fields):doc}))};indexToUse.defaultUsed&&(resp.warning="No matching index found, create an index to optimize query time.");return resp}async function explain$1(db,requestDef){const queryPlan=await find$1(db,requestDef,!0);return{dbname:db.name,index:queryPlan.index,selector:requestDef.selector,range:{start_key:queryPlan.queryOpts.startkey,end_key:queryPlan.queryOpts.endkey},opts:{use_index:requestDef.use_index||[],bookmark:"nil",limit:requestDef.limit,skip:requestDef.skip,sort:requestDef.sort||{},fields:requestDef.fields,conflicts:!1,r:[49]},limit:requestDef.limit,skip:requestDef.skip||0,fields:requestDef.fields}}async function deleteIndex$1(db,index6){if(!index6.ddoc)throw new Error("you must supply an index.ddoc when deleting");if(!index6.name)throw new Error("you must supply an index.name when deleting");const docId=index6.ddoc,viewName=index6.name;await upsert2(db,docId,(function deltaFun(doc){if(1===Object.keys(doc.views).length&&doc.views[viewName])return{_id:docId,_deleted:!0};delete doc.views[viewName];return doc}));await abstractMapper$1(db).viewCleanup.apply(db);return{ok:!0}}function setStyle(el,styleHead,condition){if(condition()){el.addClass(`${styleHead}-enabled`);el.removeClass(`${styleHead}-disabled`)}else{el.addClass(`${styleHead}-disabled`);el.removeClass(`${styleHead}-enabled`)}}function visibleOnly(cond){return()=>({visibility:cond()})}function enableOnly(cond){return()=>({disabled:!cond()})}function getLevelStr(level){return level==LEVEL_POWER_USER?$msg("obsidianLiveSyncSettingTab.levelPowerUser"):level==LEVEL_ADVANCED?$msg("obsidianLiveSyncSettingTab.levelAdvanced"):level==LEVEL_EDGE_CASE?$msg("obsidianLiveSyncSettingTab.levelEdgeCase"):""}function findAttrFromParent(el,attr2){let current=el;for(;current;){const value=current.getAttribute(attr2);if(value)return value;current=current.parentElement}return""}function wrapMemo(func){let buf;return arg=>{if(buf!==arg){func(arg);buf=arg}}}function paneChangeLog(paneEl){var _a8,_b4;const informationDivEl=this.createEl(paneEl,"div",{text:""}),tmpDiv=createDiv();tmpDiv.addClass("op-warn-info");tmpDiv.innerHTML=`

${$msg("obsidianLiveSyncSettingTab.msgNewVersionNote")}

`;if(lastVersion>((null==(_a8=this.editingSettings)?void 0:_a8.lastReadUpdates)||0)){const informationButtonDiv=informationDivEl.appendChild(tmpDiv);null==(_b4=informationButtonDiv.querySelector("button"))||_b4.addEventListener("click",(()=>{fireAndForget((async()=>{this.editingSettings.lastReadUpdates=lastVersion;await this.saveAllDirtySettings();informationButtonDiv.remove()}))}))}fireAndForget((()=>import_obsidian.MarkdownRenderer.render(this.plugin.app,updateInformation,informationDivEl,"/",this.plugin)))}function paneSetup(paneEl,{addPanel,addPane}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleQuickSetup")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameConnectSetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descConnectSetupURI")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnUse")).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI2)}))}));new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameManualSetup")).setDesc($msg("obsidianLiveSyncSettingTab.descManualSetup")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnStart")).onClick((async()=>{await this.enableMinimalSetup()}))}));new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameEnableLiveSync")).setDesc($msg("obsidianLiveSyncSettingTab.descEnableLiveSync")).addOnUpdate(visibleOnly((()=>!this.isConfiguredAs("isConfigured",!0)))).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnEnable")).onClick((async()=>{this.editingSettings.isConfigured=!0;await this.saveAllDirtySettings();this.plugin.$$askReload()}))}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSetupOtherDevices"),void 0,visibleOnly((()=>this.isConfiguredAs("isConfigured",!0)))).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameCopySetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descCopySetupURI")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnCopy")).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI2)}))}));new LiveSyncSetting(paneEl2).setName($msg("Setup.ShowQRCode")).setDesc($msg("Setup.ShowQRCode.Desc")).addButton((text2=>{text2.setButtonText($msg("Setup.ShowQRCode")).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_SHOW_SETUP_QR)}))}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleReset")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDiscardSettings")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnDiscard")).onClick((async()=>{if("yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgDiscardConfirmation"),{defaultOption:"No"})){this.editingSettings={...this.editingSettings,...DEFAULT_SETTINGS};await this.saveAllDirtySettings();this.plugin.settings={...DEFAULT_SETTINGS};await this.plugin.$$saveSettingData();await this.plugin.$$resetLocalDatabase();this.plugin.$$askReload()}})).setWarning()})).addOnUpdate(visibleOnly((()=>this.isConfiguredAs("isConfigured",!0))))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleExtraFeatures")).then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("useAdvancedMode");new LiveSyncSetting(paneEl2).autoWireToggle("usePowerUserMode");new LiveSyncSetting(paneEl2).autoWireToggle("useEdgeCaseMode");this.addOnSaved("useAdvancedMode",(()=>this.display()));this.addOnSaved("usePowerUserMode",(()=>this.display()));this.addOnSaved("useEdgeCaseMode",(()=>this.display()))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleOnlineTips")).then((paneEl2=>{const repo="vrtmrz/obsidian-livesync",topPath=$msg("obsidianLiveSyncSettingTab.linkTroubleshooting"),rawRepoURI=`https://raw.githubusercontent.com/${repo}/main`;this.createEl(paneEl2,"div","",(el=>el.innerHTML=`${$msg("obsidianLiveSyncSettingTab.linkOpenInBrowser")}`));const troubleShootEl=this.createEl(paneEl2,"div",{text:"",cls:"sls-troubleshoot-preview"}),loadMarkdownPage=async(pathAll,basePathParam="")=>{var _a8,_b4;troubleShootEl.style.minHeight=troubleShootEl.clientHeight+"px";troubleShootEl.empty();const directoryArr=(pathAll.startsWith("/")?pathAll:`${basePathParam}/${pathAll}`).split("/"),filename=directoryArr.pop(),basePath=directoryArr.join("/");let remoteTroubleShootMDSrc="";try{remoteTroubleShootMDSrc=await(0,import_obsidian12.request)(`${rawRepoURI}${basePath}/${filename}`)}catch(ex){remoteTroubleShootMDSrc=`${$msg("obsidianLiveSyncSettingTab.logErrorOccurred")}\n${ex.toString()}`}const remoteTroubleShootMD=remoteTroubleShootMDSrc.replace(/\((.*?(.png)|(.jpg))\)/g,`(${rawRepoURI}${basePath}/$1)`);await import_obsidian.MarkdownRenderer.render(this.plugin.app,` [${$msg("obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting")}](${topPath}) [${$msg("obsidianLiveSyncSettingTab.linkPageTop")}](${filename})\n\n${remoteTroubleShootMD}`,troubleShootEl,`${rawRepoURI}`,this.plugin);null==(_b4=null==(_a8=troubleShootEl.querySelector(".sls-troubleshoot-anchor"))?void 0:_a8.parentElement)||_b4.setCssStyles({position:"sticky",top:"-1em",backgroundColor:"var(--modal-background)"});troubleShootEl.querySelectorAll("a.internal-link").forEach((anchorEl=>{anchorEl.addEventListener("click",(evt=>{fireAndForget((async()=>{const uri=anchorEl.getAttr("data-href");if(uri)if(uri.startsWith("#")){evt.preventDefault();const p4=Array.from(troubleShootEl.querySelectorAll("[data-heading]")).find((e3=>{var _a9;return(null==(_a9=e3.getAttr("data-heading"))?void 0:_a9.toLowerCase().split(" ").join("-"))==uri.substring(1).toLowerCase()}));if(p4){p4.setCssStyles({scrollMargin:"3em"});p4.scrollIntoView({behavior:"instant",block:"start"})}}else{evt.preventDefault();await loadMarkdownPage(uri,basePath);troubleShootEl.setCssStyles({scrollMargin:"1em"});troubleShootEl.scrollIntoView({behavior:"instant",block:"start"})}}))}))}));troubleShootEl.style.minHeight=""};loadMarkdownPage(topPath)}))}function paneGeneral(paneEl,{addPanel,addPane}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleAppearance")).then((paneEl2=>{const languages=Object.fromEntries([...SUPPORTED_I18N_LANGS.map((e3=>[e3,$t(`lang-${e3}`)]))]);new LiveSyncSetting(paneEl2).autoWireDropDown("displayLanguage",{options:languages});this.addOnSaved("displayLanguage",(()=>this.display()));new LiveSyncSetting(paneEl2).autoWireToggle("showStatusOnEditor");new LiveSyncSetting(paneEl2).autoWireToggle("showOnlyIconsOnEditor",{onUpdate:visibleOnly((()=>this.isConfiguredAs("showStatusOnEditor",!0)))});new LiveSyncSetting(paneEl2).autoWireToggle("showStatusOnStatusbar");new LiveSyncSetting(paneEl2).autoWireToggle("hideFileWarningNotice")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleLogging")).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireToggle("lessInformationInLog");new LiveSyncSetting(paneEl2).autoWireToggle("showVerboseLog",{onUpdate:visibleOnly((()=>this.isConfiguredAs("lessInformationInLog",!1)))})}));new LiveSyncSetting(paneEl).setClass("wizardOnly").addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.btnNext")).setCta().onClick((()=>{this.changeDisplay("0")}))))}function paneRemoteConfig(paneEl,{addPanel,addPane}){let checkResultDiv;const checkConfig=async checkResultDiv2=>{var _a8,_b4,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k;Logger($msg("obsidianLiveSyncSettingTab.logCheckingDbConfig"),LOG_LEVEL_INFO);let isSuccessful=!0;const emptyDiv=createDiv();emptyDiv.innerHTML="";null==checkResultDiv2||checkResultDiv2.replaceChildren(emptyDiv);const addResult=(msg,classes)=>{const tmpDiv=createDiv();tmpDiv.addClass("ob-btn-config-fix");classes&&tmpDiv.addClasses(classes);tmpDiv.innerHTML=`${msg}`;null==checkResultDiv2||checkResultDiv2.appendChild(tmpDiv)};try{if(isCloudantURI(this.editingSettings.couchDB_URI)){Logger($msg("obsidianLiveSyncSettingTab.logCannotUseCloudant"),LOG_LEVEL_NOTICE);return}const customHeaders=parseHeaderValues(this.editingSettings.couchDB_CustomHeaders),credential=generateCredentialObject(this.editingSettings),responseConfig=(await requestToCouchDBWithCredentials(this.editingSettings.couchDB_URI,credential,window.origin,void 0,void 0,void 0,customHeaders)).json,addConfigFixButton=(title,key2,value)=>{var _a9;if(!checkResultDiv2)return;const tmpDiv=createDiv();tmpDiv.addClass("ob-btn-config-fix");tmpDiv.innerHTML=``;const x2=checkResultDiv2.appendChild(tmpDiv);null==(_a9=x2.querySelector("button"))||_a9.addEventListener("click",(()=>{fireAndForget((async()=>{Logger($msg("obsidianLiveSyncSettingTab.logCouchDbConfigSet",{title,key:key2,value}));const res2=await requestToCouchDBWithCredentials(this.editingSettings.couchDB_URI,credential,void 0,key2,value,void 0,customHeaders);if(200==res2.status){Logger($msg("obsidianLiveSyncSettingTab.logCouchDbConfigUpdated",{title}),LOG_LEVEL_NOTICE);checkResultDiv2.removeChild(x2);await checkConfig(checkResultDiv2)}else{Logger($msg("obsidianLiveSyncSettingTab.logCouchDbConfigFail",{title}),LOG_LEVEL_NOTICE);Logger(res2.text,LOG_LEVEL_VERBOSE)}}))}))};addResult($msg("obsidianLiveSyncSettingTab.msgNotice"),["ob-btn-config-head"]);addResult($msg("obsidianLiveSyncSettingTab.msgIfConfigNotPersistent"),["ob-btn-config-info"]);addResult($msg("obsidianLiveSyncSettingTab.msgConfigCheck"),["ob-btn-config-head"]);this.editingSettings.couchDB_USER in responseConfig.admins?addResult($msg("obsidianLiveSyncSettingTab.okAdminPrivileges")):addResult($msg("obsidianLiveSyncSettingTab.warnNoAdmin"));if("true"!=(null==(_a8=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_a8.require_valid_user)){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errRequireValidUser"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetRequireValidUser"),"chttpd/require_valid_user","true")}else addResult($msg("obsidianLiveSyncSettingTab.okRequireValidUser"));if("true"!=(null==(_b4=null==responseConfig?void 0:responseConfig.chttpd_auth)?void 0:_b4.require_valid_user)){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errRequireValidUserAuth"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth"),"chttpd_auth/require_valid_user","true")}else addResult($msg("obsidianLiveSyncSettingTab.okRequireValidUserAuth"));if(null==responseConfig?void 0:responseConfig.httpd["WWW-Authenticate"])addResult($msg("obsidianLiveSyncSettingTab.okWwwAuth"));else{isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errMissingWwwAuth"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetWwwAuth"),"httpd/WWW-Authenticate",'Basic realm="couchdb"')}if("true"!=(null==(_c3=null==responseConfig?void 0:responseConfig.httpd)?void 0:_c3.enable_cors)){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errEnableCors"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgEnableCors"),"httpd/enable_cors","true")}else addResult($msg("obsidianLiveSyncSettingTab.okEnableCors"));if(!isCloudantURI(this.editingSettings.couchDB_URI)){if(Number(null!=(_e2=null==(_d2=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_d2.max_http_request_size)?_e2:0)<4294967296){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errMaxRequestSize"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetMaxRequestSize"),"chttpd/max_http_request_size","4294967296")}else addResult($msg("obsidianLiveSyncSettingTab.okMaxRequestSize"));if(Number(null!=(_g=null==(_f=null==responseConfig?void 0:responseConfig.couchdb)?void 0:_f.max_document_size)?_g:0)<5e7){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errMaxDocumentSize"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetMaxDocSize"),"couchdb/max_document_size","50000000")}else addResult($msg("obsidianLiveSyncSettingTab.okMaxDocumentSize"))}if("true"!=(null==(_h=null==responseConfig?void 0:responseConfig.cors)?void 0:_h.credentials)){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errCorsCredentials"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetCorsCredentials"),"cors/credentials","true")}else addResult($msg("obsidianLiveSyncSettingTab.okCorsCredentials"));const ConfiguredOrigins=((null!=(_j=null==(_i2=null==responseConfig?void 0:responseConfig.cors)?void 0:_i2.origins)?_j:"")+"").split(",");if("*"==(null==(_k=null==responseConfig?void 0:responseConfig.cors)?void 0:_k.origins)||-1!==ConfiguredOrigins.indexOf("app://obsidian.md")&&-1!==ConfiguredOrigins.indexOf("capacitor://localhost")&&-1!==ConfiguredOrigins.indexOf("http://localhost"))addResult($msg("obsidianLiveSyncSettingTab.okCorsOrigins"));else{addResult($msg("obsidianLiveSyncSettingTab.errCorsOrigins"));addConfigFixButton($msg("obsidianLiveSyncSettingTab.msgSetCorsOrigins"),"cors/origins","app://obsidian.md,capacitor://localhost,http://localhost");isSuccessful=!1}addResult($msg("obsidianLiveSyncSettingTab.msgConnectionCheck"),["ob-btn-config-head"]);addResult($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(this.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})));addResult($msg("obsidianLiveSyncSettingTab.msgOriginCheck",{org}));if("true"!=responseHeaders["access-control-allow-credentials"]){addResult($msg("obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials"));isSuccessful=!1}else addResult($msg("obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin"));responseHeaders["access-control-allow-origin"]!=org?addResult($msg("obsidianLiveSyncSettingTab.warnCorsOriginUnmatched",{from:origin,to:responseHeaders["access-control-allow-origin"]})):addResult($msg("obsidianLiveSyncSettingTab.okCorsOriginMatched"))}addResult($msg("obsidianLiveSyncSettingTab.msgDone"),["ob-btn-config-head"]);addResult($msg("obsidianLiveSyncSettingTab.msgConnectionProxyNote"),["ob-btn-config-info"]);Logger($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"),LOG_LEVEL_INFO)}catch(ex){if(401==(null==ex?void 0:ex.status)){isSuccessful=!1;addResult($msg("obsidianLiveSyncSettingTab.errAccessForbidden"));addResult($msg("obsidianLiveSyncSettingTab.errCannotContinueTest"));Logger($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"),LOG_LEVEL_INFO)}else{Logger($msg("obsidianLiveSyncSettingTab.logCheckingConfigFailed"),LOG_LEVEL_NOTICE);Logger(ex);isSuccessful=!1}}return isSuccessful};addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleRemoteServer")).then((paneEl2=>{this.createEl(paneEl2,"div",{text:$msg("obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync")},void 0,visibleOnly((()=>this.isAnySyncEnabled()))).addClass("op-warn-info");new LiveSyncSetting(paneEl2).autoWireDropDown("remoteType",{holdValue:!0,options:{[REMOTE_COUCHDB]:$msg("obsidianLiveSyncSettingTab.optionCouchDB"),[REMOTE_MINIO]:$msg("obsidianLiveSyncSettingTab.optionMinioS3R2"),[REMOTE_P2P]:"Only Peer-to-Peer"},onUpdate:this.enableOnlySyncDisabled});addPanel(paneEl2,"Peer-to-Peer",void 0,this.onlyOnOnlyP2P).then((paneEl3=>{const syncWarnP2P=this.createEl(paneEl3,"div",{text:""});import_obsidian.MarkdownRenderer.render(this.plugin.app,"This feature is a Work In Progress, and configurable on `P2P Replicator` Pane.\nThe pane also can be launched by `P2P Replicator` command from the Command Palette.\n",syncWarnP2P,"/",this.plugin);syncWarnP2P.addClass("op-warn-info");new LiveSyncSetting(paneEl3).setName("Apply Settings").setClass("wizardHidden").addApplyButton(["remoteType"])}));addPanel(paneEl2,$msg("obsidianLiveSyncSettingTab.titleMinioS3R2"),void 0,this.onlyOnMinIO).then((paneEl3=>{const syncWarnMinio=this.createEl(paneEl3,"div",{text:""}),ObjectStorageMessage=$msg("obsidianLiveSyncSettingTab.msgObjectStorageWarning");import_obsidian.MarkdownRenderer.render(this.plugin.app,ObjectStorageMessage,syncWarnMinio,"/",this.plugin);syncWarnMinio.addClass("op-warn-info");new LiveSyncSetting(paneEl3).autoWireText("endpoint",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireText("accessKey",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireText("secretKey",{holdValue:!0,isPassword:!0});new LiveSyncSetting(paneEl3).autoWireText("region",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireText("bucket",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireText("bucketPrefix",{holdValue:!0,placeHolder:"vaultname/"});new LiveSyncSetting(paneEl3).autoWireToggle("useCustomRequestHandler",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireTextArea("bucketCustomHeaders",{holdValue:!0,placeHolder:"x-custom-header: value\n x-custom-header2: value2"});new LiveSyncSetting(paneEl3).setName($msg("obsidianLiveSyncSettingTab.nameTestConnection")).addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.btnTest")).setDisabled(!1).onClick((async()=>{await this.testConnection(this.editingSettings)}))));new LiveSyncSetting(paneEl3).setName($msg("obsidianLiveSyncSettingTab.nameApplySettings")).setClass("wizardHidden").addApplyButton(["remoteType","endpoint","region","accessKey","secretKey","bucket","useCustomRequestHandler","bucketCustomHeaders","bucketPrefix"]).addOnUpdate(this.onlyOnMinIO)}));addPanel(paneEl2,$msg("obsidianLiveSyncSettingTab.titleCouchDB"),void 0,this.onlyOnCouchDB).then((paneEl3=>{this.plugin.$$isMobile()?this.createEl(paneEl3,"div",{text:$msg("obsidianLiveSyncSettingTab.msgNonHTTPSWarning")},void 0,visibleOnly((()=>!this.editingSettings.couchDB_URI.startsWith("https://")))).addClass("op-warn"):this.createEl(paneEl3,"div",{text:$msg("obsidianLiveSyncSettingTab.msgNonHTTPSInfo")},void 0,visibleOnly((()=>!this.editingSettings.couchDB_URI.startsWith("https://")))).addClass("op-warn-info");new LiveSyncSetting(paneEl3).autoWireText("couchDB_URI",{holdValue:!0,onUpdate:this.enableOnlySyncDisabled});new LiveSyncSetting(paneEl3).autoWireToggle("useJWT",{holdValue:!0,onUpdate:this.enableOnlySyncDisabled});new LiveSyncSetting(paneEl3).autoWireText("couchDB_USER",{holdValue:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>!this.editingSettings.useJWT)))});new LiveSyncSetting(paneEl3).autoWireText("couchDB_PASSWORD",{holdValue:!0,isPassword:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>!this.editingSettings.useJWT)))});const algorithms={["HS256"]:"HS256",["HS512"]:"HS512",["ES256"]:"ES256",["ES512"]:"ES512"};new LiveSyncSetting(paneEl3).autoWireDropDown("jwtAlgorithm",{options:algorithms,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT)))});new LiveSyncSetting(paneEl3).autoWireTextArea("jwtKey",{holdValue:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT)))});let generatedKeyDivEl;new LiveSyncSetting(paneEl3).setDesc("Generate ES256 Keypair for testing").addButton((button=>button.setButtonText("Generate").onClick((async()=>{const crypto3=await getWebCrypto(),keyPair=await crypto3.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),pubKey=await crypto3.subtle.exportKey("spki",keyPair.publicKey),privateKey2=await crypto3.subtle.exportKey("pkcs8",keyPair.privateKey),encodedPublicKey=await arrayBufferToBase64Single(pubKey),privateKeyPem=`> -----BEGIN PRIVATE KEY-----\n> ${await arrayBufferToBase64Single(privateKey2)}\n> -----END PRIVATE KEY-----`,publicKeyPem=`> -----BEGIN PUBLIC KEY-----\\n${encodedPublicKey}\\n-----END PUBLIC KEY-----`,title=$msg("Setting.GenerateKeyPair.Title"),msg=$msg("Setting.GenerateKeyPair.Desc",{public_key:publicKeyPem,private_key:privateKeyPem});await import_obsidian.MarkdownRenderer.render(this.plugin.app,"## "+title+"\n\n"+msg,generatedKeyDivEl,"/",this.plugin)})))).addOnUpdate(combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT))));generatedKeyDivEl=this.createEl(paneEl3,"div",{text:""},(el=>{}),visibleOnly((()=>this.editingSettings.useJWT)));new LiveSyncSetting(paneEl3).autoWireText("jwtKid",{holdValue:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT)))});new LiveSyncSetting(paneEl3).autoWireText("jwtSub",{holdValue:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT)))});new LiveSyncSetting(paneEl3).autoWireNumeric("jwtExpDuration",{holdValue:!0,onUpdate:combineOnUpdate(this.enableOnlySyncDisabled,visibleOnly((()=>this.editingSettings.useJWT)))});new LiveSyncSetting(paneEl3).autoWireText("couchDB_DBNAME",{holdValue:!0,onUpdate:this.enableOnlySyncDisabled});new LiveSyncSetting(paneEl3).autoWireTextArea("couchDB_CustomHeaders",{holdValue:!0});new LiveSyncSetting(paneEl3).autoWireToggle("useRequestAPI",{holdValue:!0,onUpdate:this.enableOnlySyncDisabled});new LiveSyncSetting(paneEl3).setName($msg("obsidianLiveSyncSettingTab.nameTestDatabaseConnection")).setClass("wizardHidden").setDesc($msg("obsidianLiveSyncSettingTab.descTestDatabaseConnection")).addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.btnTest")).setDisabled(!1).onClick((async()=>{await this.testConnection()}))));new LiveSyncSetting(paneEl3).setName($msg("obsidianLiveSyncSettingTab.nameValidateDatabaseConfig")).setDesc($msg("obsidianLiveSyncSettingTab.descValidateDatabaseConfig")).addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.btnCheck")).setDisabled(!1).onClick((async()=>{await checkConfig(checkResultDiv)}))));checkResultDiv=this.createEl(paneEl3,"div",{text:""});new LiveSyncSetting(paneEl3).setName($msg("obsidianLiveSyncSettingTab.nameApplySettings")).setClass("wizardHidden").addApplyButton(["remoteType","couchDB_URI","couchDB_USER","couchDB_PASSWORD","couchDB_DBNAME","jwtAlgorithm","jwtExpDuration","jwtKey","jwtSub","jwtKid","useJWT","couchDB_CustomHeaders","useRequestAPI"]).addOnUpdate(this.onlyOnCouchDB)}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleNotification"),(()=>{}),this.onlyOnCouchDB).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("notifyThresholdOfRemoteStorageSize",{}).setClass("wizardHidden")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.panelPrivacyEncryption")).then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("encrypt",{holdValue:!0});const isEncryptEnabled=visibleOnly((()=>this.isConfiguredAs("encrypt",!0)));new LiveSyncSetting(paneEl2).autoWireText("passphrase",{holdValue:!0,isPassword:!0,onUpdate:isEncryptEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("usePathObfuscation",{holdValue:!0,onUpdate:isEncryptEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("useDynamicIterationCount",{holdValue:!0,onUpdate:isEncryptEnabled}).setClass("wizardHidden")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleFetchSettings")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.titleFetchConfigFromRemote")).setDesc($msg("obsidianLiveSyncSettingTab.descFetchConfigFromRemote")).addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.buttonFetch")).setDisabled(!1).onClick((async()=>{const trialSetting={...this.initialSettings,...this.editingSettings},newTweaks=await this.plugin.$$checkAndAskUseRemoteConfiguration(trialSetting);if(!1!==newTweaks.result){if(this.inWizard){this.editingSettings={...this.editingSettings,...newTweaks.result};this.requestUpdate();return}this.closeSetting();this.plugin.settings={...this.plugin.settings,...newTweaks.result};if(newTweaks.requireFetch){if("no"==await this.plugin.confirm.askYesNoDialog($msg("SettingTab.Message.AskRebuild"),{defaultOption:"Yes"})){await this.plugin.$$saveSettingData();return}await this.plugin.$$saveSettingData();await this.plugin.rebuilder.scheduleFetch();await this.plugin.$$scheduleAppReload();return}await this.plugin.$$saveSettingData()}}))))}));new LiveSyncSetting(paneEl).setClass("wizardOnly").addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.buttonNext")).setCta().setDisabled(!1).onClick((async()=>{if((await checkConfig(checkResultDiv)||"no"!=await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgConfigCheckFailed"),{defaultOption:"No",title:$msg("obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed")}))&&(this.editingSettings.encrypt&&this.editingSettings.usePathObfuscation||"no"!=await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation"),{defaultOption:"No",title:$msg("obsidianLiveSyncSettingTab.titleEncryptionNotEnabled")}))){this.editingSettings.encrypt||(this.editingSettings.passphrase="");if(await this.isPassphraseValid()||"no"!=await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgInvalidPassphrase"),{defaultOption:"No",title:$msg("obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid")})){isCloudantURI(this.editingSettings.couchDB_URI)?this.editingSettings={...this.editingSettings,...PREFERRED_SETTING_CLOUDANT}:this.editingSettings.remoteType==REMOTE_MINIO?this.editingSettings={...this.editingSettings,...PREFERRED_JOURNAL_SYNC}:this.editingSettings={...this.editingSettings,...PREFERRED_SETTING_SELF_HOSTED};if("yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgFetchConfigFromRemote"),{defaultOption:"Yes",title:$msg("obsidianLiveSyncSettingTab.titleFetchConfig")})){const trialSetting={...this.initialSettings,...this.editingSettings},newTweaks=await this.plugin.$$checkAndAskUseRemoteConfiguration(trialSetting);if(!1!==newTweaks.result){this.editingSettings={...this.editingSettings,...newTweaks.result};this.requestUpdate()}}this.changeDisplay("30")}}}))))}function MultipleRegExpControl($$anchor,$$props){var ul,node,li_1,label_1,button_1,li_2,button_2,button_3;push($$props,!1);append_styles($$anchor,$$css6);const statusName=mutable_source(),modified=mutable_source(),isInvertedExp=mutable_source();let patterns=prop($$props,"patterns",28,(()=>[])),originals=prop($$props,"originals",24,(()=>[])),apply3=prop($$props,"apply",8,(_=>Promise.resolve()));legacy_pre_effect((()=>deep_read_state(patterns())),(()=>{set(statusName,patterns().map((e3=>function checkRegExp(pattern){return function isValidRegExp(regexp){try{const[,exp]=parseCustomRegExp(regexp);new RegExp(exp);return!0}catch(e3){return!1}}(pattern)?"✔":"⚠"}(e3))))}));legacy_pre_effect((()=>(deep_read_state(patterns()),deep_read_state(originals()))),(()=>{set(modified,patterns().map(((e3,i2)=>{var _a8;return e3!=(null!==(_a8=null===originals()||void 0===originals()?void 0:originals()[i2])&&void 0!==_a8?_a8:"")?"✏ ":""})))}));legacy_pre_effect((()=>(deep_read_state(patterns()),isInvertedRegExp)),(()=>{set(isInvertedExp,patterns().map((e3=>isInvertedRegExp(e3))))}));legacy_pre_effect_reset();init();each(node=child(ul=root5()),1,patterns,index,(($$anchor2,pattern,idx2)=>{var span,text_1,input,button,li=root_110(),label=child(li),text2=child(label);reset(label);span=sibling(label,2);text_1=child(span,!0);reset(span);remove_input_defaults(input=sibling(span,2));button=sibling(input,2);reset(li);template_effect((()=>{var _a8,_b4;set_text(text2,`${null!=(_a8=get(modified)[idx2])?_a8:""}${null!=(_b4=get(statusName)[idx2])?_b4:""}`);set_text(text_1,get(isInvertedExp)[idx2]?"INVERTED":"");set_class(input,1,clsx2(get(modified)[idx2]),"svelte-1rsazmf")}));bind_value(input,(()=>patterns()[idx2]),($$value=>(patterns()[idx2]=$$value,invalidate_inner_signals((()=>patterns())))));event("click",button,(()=>function remove(idx2){patterns(patterns()[idx2]="",!0)}(idx2)));append($$anchor2,li)}));label_1=child(li_1=sibling(node,2));button_1=child(label_1);reset(label_1);reset(li_1);li_2=sibling(li_1,2);button_2=child(li_2);button_3=sibling(button_2,2);reset(li_2);reset(ul);template_effect((($0,$1)=>{button_2.disabled=$0;button_3.disabled=$1}),[()=>get(statusName).some((e3=>"⚠"===e3))||get(modified).every((e3=>""===e3)),()=>get(statusName).some((e3=>"⚠"===e3))||get(modified).every((e3=>""===e3))],derived_safe_equal);event("click",button_1,(()=>function add(){patterns([...patterns(),""])}()));event("click",button_2,(()=>apply3()(patterns())));event("click",button_3,(()=>function revert2(){patterns([...originals()])}()));append($$anchor,ul);pop()}function paneSelector(paneEl,{addPanel}){addPanel(paneEl,"Normal Files").then((paneEl2=>{paneEl2.addClass("wizardHidden");mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files.").setClass("wizardHidden").controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncOnlyRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.display()}}});mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Non-Synchronising files").setDesc("(RegExp) If this is set, any changes to local and remote files that match this will be skipped.").setClass("wizardHidden").controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncIgnoreRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.display()}}});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("syncMaxSizeInMB",{clampMin:0});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("useIgnoreFiles");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireTextArea("ignoreFiles",{onUpdate:visibleOnly((()=>this.isConfiguredAs("useIgnoreFiles",!0)))})}));addPanel(paneEl,"Hidden Files",void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{const targetPatternSetting=new LiveSyncSetting(paneEl2).setName("Target patterns").setClass("wizardHidden").setDesc("Patterns to match files for syncing"),patTarget=splitCustomRegExpList(this.editingSettings.syncInternalFilesTargetPatterns,",");mount(MultipleRegExpControl,{target:targetPatternSetting.controlEl,props:{patterns:patTarget,originals:[...patTarget],apply:async newPatterns=>{this.editingSettings.syncInternalFilesTargetPatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.display()}}});const defaultSkipPattern="\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/",defaultSkipPatternXPlat=defaultSkipPattern+",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$",pat=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,",");mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Ignore patterns").setClass("wizardHidden").setDesc("").controlEl,props:{patterns:pat,originals:[...pat],apply:async newPatterns=>{this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.display()}}});const addDefaultPatterns=async patterns=>{const oldList=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,","),newList=splitCustomRegExpList(patterns,","),allSet=new Set([...oldList,...newList]);this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList([...allSet],",");await this.saveAllDirtySettings();this.display()};new LiveSyncSetting(paneEl2).setName("Add default patterns").setClass("wizardHidden").addButton((button=>{button.setButtonText("Default").onClick((async()=>{await addDefaultPatterns(defaultSkipPattern)}))})).addButton((button=>{button.setButtonText("Cross-platform").onClick((async()=>{await addDefaultPatterns(defaultSkipPatternXPlat)}))}))}))}function paneSyncSettings(paneEl,{addPanel,addPane}){if(""!=this.editingSettings.versionUpFlash){const c3=this.createEl(paneEl,"div",{text:this.editingSettings.versionUpFlash,cls:"op-warn sls-setting-hidden"},(el=>{this.createEl(el,"button",{text:$msg("obsidianLiveSyncSettingTab.btnGotItAndUpdated")},(e3=>{e3.addClass("mod-cta");e3.addEventListener("click",(()=>{fireAndForget((async()=>{this.editingSettings.versionUpFlash="";await this.saveAllDirtySettings();c3.remove()}))}))}))}),visibleOnly((()=>!this.isConfiguredAs("versionUpFlash",""))))}this.createEl(paneEl,"div",{text:$msg("obsidianLiveSyncSettingTab.msgSelectAndApplyPreset"),cls:"wizardOnly"}).addClasses(["op-warn-info"]);addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationPreset")).then((paneEl2=>{const options=this.editingSettings.remoteType==REMOTE_COUCHDB?{NONE:"",LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")}:{NONE:"",PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")};new LiveSyncSetting(paneEl2).autoWireDropDown("preset",{options,holdValue:!0}).addButton((button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnApply"));button.onClick((async()=>{await this.saveAllDirtySettings()}))}));this.addOnSaved("preset",(async currentPreset=>{if(""==currentPreset){Logger($msg("obsidianLiveSyncSettingTab.logSelectAnyPreset"),LOG_LEVEL_NOTICE);return}const presetAllDisabled={batchSave:!1,liveSync:!1,periodicReplication:!1,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!1,syncOnFileOpen:!1,syncAfterMerge:!1},presetLiveSync={...presetAllDisabled,liveSync:!0},presetPeriodic={...presetAllDisabled,batchSave:!0,periodicReplication:!0,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!0,syncOnFileOpen:!0,syncAfterMerge:!0};if("LIVESYNC"==currentPreset){this.editingSettings={...this.editingSettings,...presetLiveSync};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredLiveSync"),LOG_LEVEL_NOTICE)}else if("PERIODIC"==currentPreset){this.editingSettings={...this.editingSettings,...presetPeriodic};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredPeriodic"),LOG_LEVEL_NOTICE)}else{Logger($msg("obsidianLiveSyncSettingTab.logConfiguredDisabled"),LOG_LEVEL_NOTICE);this.editingSettings={...this.editingSettings,...presetAllDisabled}}if(this.inWizard){this.closeSetting();this.inWizard=!1;if(this.editingSettings.isConfigured)if(this.isNeedRebuildLocal()||this.isNeedRebuildRemote())await this.confirmRebuild();else{await this.saveAllDirtySettings();await this.plugin.$$realizeSettingSyncMode();this.plugin.$$askReload()}else{this.editingSettings.isConfigured=!0;await this.saveAllDirtySettings();await this.plugin.$$realizeSettingSyncMode();await this.rebuildDB("localOnly");"yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgGenerateSetupURI"),{defaultOption:"Yes",title:$msg("obsidianLiveSyncSettingTab.titleCongratulations")})&&eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI2)}}else{await this.saveAllDirtySettings();await this.plugin.$$realizeSettingSyncMode()}}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationMethod")).then((paneEl2=>{paneEl2.addClass("wizardHidden");const onlyOnNonLiveSync=visibleOnly((()=>!this.isConfiguredAs("syncMode","LIVESYNC"))),onlyOnPeriodic=visibleOnly((()=>this.isConfiguredAs("syncMode","PERIODIC"))),optionsSyncMode=this.editingSettings.remoteType==REMOTE_COUCHDB?{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents"),LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync")}:{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents")};new LiveSyncSetting(paneEl2).autoWireDropDown("syncMode",{options:optionsSyncMode}).setClass("wizardHidden");this.addOnSaved("syncMode",(async value=>{this.editingSettings.liveSync=!1;this.editingSettings.periodicReplication=!1;"LIVESYNC"==value?this.editingSettings.liveSync=!0:"PERIODIC"==value&&(this.editingSettings.periodicReplication=!0);await this.saveSettings(["liveSync","periodicReplication"]);await this.plugin.$$realizeSettingSyncMode()}));new LiveSyncSetting(paneEl2).autoWireNumeric("periodicReplicationInterval",{clampMax:5e3,onUpdate:onlyOnPeriodic}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("syncMinimumInterval",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnEditorSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnFileOpen",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnStart",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncAfterMerge",{onUpdate:onlyOnNonLiveSync})}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleUpdateThinning"),void 0,visibleOnly((()=>!this.isConfiguredAs("syncMode","LIVESYNC")))).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("batchSave");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batchSaveMinimumDelay",{acceptZero:!0,onUpdate:visibleOnly((()=>this.isConfiguredAs("batchSave",!0)))});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batchSaveMaximumDelay",{acceptZero:!0,onUpdate:visibleOnly((()=>this.isConfiguredAs("batchSave",!0)))})}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleDeletionPropagation"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("trashInsteadDelete");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("doNotDeleteFolder")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleConflictResolution"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("resolveConflictsByNewerFile");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("checkConflictOnlyOnOpen");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("showMergeDialogOnlyOnActive")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireText("settingSyncFile",{holdValue:!0}).addApplyButton(["settingSyncFile"]);new LiveSyncSetting(paneEl2).autoWireToggle("writeCredentialsForSettingSync");new LiveSyncSetting(paneEl2).autoWireToggle("notifyAllSettingSyncFile")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleHiddenFiles"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");const LABEL_ENABLED=$msg("obsidianLiveSyncSettingTab.labelEnabled"),LABEL_DISABLED=$msg("obsidianLiveSyncSettingTab.labelDisabled");new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameHiddenFileSynchronization")).setClass("wizardHidden").settingEl.createDiv("").innerText=this.editingSettings.syncInternalFiles?LABEL_ENABLED:LABEL_DISABLED;this.editingSettings.syncInternalFiles?new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDisableHiddenFileSync")).setClass("wizardHidden").addButton((button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnDisable")).onClick((async()=>{this.editingSettings.syncInternalFiles=!1;await this.saveAllDirtySettings();this.display()}))})):new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameEnableHiddenFileSync")).setClass("wizardHidden").addButton((button=>{button.setButtonText("Merge").onClick((async()=>{this.closeSetting();await this.plugin.$anyConfigureOptionalSyncFeature("MERGE")}))})).addButton((button=>{button.setButtonText("Fetch").onClick((async()=>{this.closeSetting();await this.plugin.$anyConfigureOptionalSyncFeature("FETCH")}))})).addButton((button=>{button.setButtonText("Overwrite").onClick((async()=>{this.closeSetting();await this.plugin.$anyConfigureOptionalSyncFeature("OVERWRITE")}))}));new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("suppressNotifyHiddenFilesChange",{});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncInternalFilesBeforeReplication",{onUpdate:visibleOnly((()=>this.isConfiguredAs("watchInternalFileChanges",!0)))});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("syncInternalFilesInterval",{clampMin:10,acceptZero:!0})}))}function paneCustomisationSync(paneEl,{addPanel}){addPanel(paneEl,"Customization Sync").then((paneEl2=>{const enableOnlyOnPluginSyncIsNotEnabled=enableOnly((()=>this.isConfiguredAs("usePluginSync",!1))),visibleOnlyOnPluginSyncEnabled=visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0)));this.createEl(paneEl2,"div",{text:"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.",cls:"op-warn"},(c3=>{}),visibleOnly((()=>this.isConfiguredAs("deviceAndVaultName",""))));this.createEl(paneEl2,"div",{text:"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.",cls:"op-warn-info"},(c3=>{}),visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0))));new LiveSyncSetting(paneEl2).autoWireText("deviceAndVaultName",{placeHolder:"desktop",onUpdate:enableOnlyOnPluginSyncIsNotEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSyncV2");new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSync",{onUpdate:enableOnly((()=>!this.isConfiguredAs("deviceAndVaultName","")))});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPlugins",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPluginsPeriodic",{onUpdate:visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0)&&this.isConfiguredAs("autoSweepPlugins",!0)))});new LiveSyncSetting(paneEl2).autoWireToggle("notifyPluginOrSettingUpdated",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).setName("Open").setDesc("Open the dialog").addButton((button=>{button.setButtonText("Open").setDisabled(!1).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2)}))})).addOnUpdate(visibleOnlyOnPluginSyncEnabled)}))}function paneHatch(paneEl,{addPanel}){addPanel(paneEl,$msg("Setting.TroubleShooting")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("Setting.TroubleShooting.Doctor")).setDesc($msg("Setting.TroubleShooting.Doctor.Desc")).addButton((button=>button.setButtonText("Run Doctor").setCta().setDisabled(!1).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_RUN_DOCTOR,"you wanted(Thank you)!")}))));new LiveSyncSetting(paneEl2).setName("Prepare the 'report' to create an issue").addButton((button=>button.setButtonText("Copy Report to clipboard").setCta().setDisabled(!1).onClick((async()=>{let responseConfig={};const REDACTED="𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";if(this.editingSettings.remoteType==REMOTE_COUCHDB)try{const credential=generateCredentialObject(this.editingSettings),customHeaders=parseHeaderValues(this.editingSettings.couchDB_CustomHeaders),r4=await requestToCouchDBWithCredentials(this.editingSettings.couchDB_URI,credential,window.origin,void 0,void 0,void 0,customHeaders);Logger(JSON.stringify(r4.json,null,2));responseConfig=r4.json;responseConfig.couch_httpd_auth.secret=REDACTED;responseConfig.couch_httpd_auth.authentication_db=REDACTED;responseConfig.couch_httpd_auth.authentication_redirect=REDACTED;responseConfig.couchdb.uuid=REDACTED;responseConfig.admins=REDACTED;delete responseConfig.jwt_keys;"secret"in responseConfig.chttpd_auth&&(responseConfig.chttpd_auth.secret=REDACTED)}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE);responseConfig={error:"Requesting information from the remote CouchDB has failed. If you are using IBM Cloudant, this is normal behaviour."}}else this.editingSettings.remoteType==REMOTE_MINIO&&(responseConfig={error:"Object Storage Synchronisation"});const defaultKeys=Object.keys(DEFAULT_SETTINGS),pluginConfig=JSON.parse(JSON.stringify(this.editingSettings)),pluginKeys=Object.keys(pluginConfig);for(const key2 of pluginKeys)defaultKeys.includes(key2)||delete pluginConfig[key2];pluginConfig.couchDB_DBNAME=REDACTED;pluginConfig.couchDB_PASSWORD=REDACTED;const scheme=pluginConfig.couchDB_URI.startsWith("http:")?"(HTTP)":pluginConfig.couchDB_URI.startsWith("https:")?"(HTTPS)":"";pluginConfig.couchDB_URI=isCloudantURI(pluginConfig.couchDB_URI)?"cloudant":`self-hosted${scheme}`;pluginConfig.couchDB_USER=REDACTED;pluginConfig.passphrase=REDACTED;pluginConfig.encryptedPassphrase=REDACTED;pluginConfig.encryptedCouchDBConnection=REDACTED;pluginConfig.accessKey=REDACTED;pluginConfig.secretKey=REDACTED;const redact=source2=>`${REDACTED}(${source2.length} letters)`;pluginConfig.region=redact(pluginConfig.region);pluginConfig.bucket=redact(pluginConfig.bucket);pluginConfig.pluginSyncExtendedSetting={};pluginConfig.P2P_AppID=redact(pluginConfig.P2P_AppID);pluginConfig.P2P_passphrase=redact(pluginConfig.P2P_passphrase);pluginConfig.P2P_roomID=redact(pluginConfig.P2P_roomID);pluginConfig.P2P_relays=redact(pluginConfig.P2P_relays);pluginConfig.jwtKey=redact(pluginConfig.jwtKey);pluginConfig.jwtSub=redact(pluginConfig.jwtSub);pluginConfig.jwtKid=redact(pluginConfig.jwtKid);pluginConfig.bucketCustomHeaders=redact(pluginConfig.bucketCustomHeaders);pluginConfig.couchDB_CustomHeaders=redact(pluginConfig.couchDB_CustomHeaders);const endpoint=pluginConfig.endpoint;if(""==endpoint)pluginConfig.endpoint="Not configured or AWS";else{const endpointScheme=pluginConfig.endpoint.startsWith("http:")?"(HTTP)":pluginConfig.endpoint.startsWith("https:")?"(HTTPS)":"";pluginConfig.endpoint=`${-1!==endpoint.indexOf(".r2.cloudflarestorage.")?"R2":"self-hosted?"}(${endpointScheme})`}const obsidianInfo={navigator:navigator.userAgent,fileSystem:this.plugin.$$isStorageInsensitive()?"insensitive":"sensitive"},msgConfig=`# ---- Obsidian info ----\n${(0,import_obsidian.stringifyYaml)(obsidianInfo)}\n---\n# ---- remote config ----\n${(0,import_obsidian.stringifyYaml)(responseConfig)}\n---\n# ---- Plug-in config ----\n${(0,import_obsidian.stringifyYaml)({version:this.manifestVersion,...pluginConfig})}`;console.log(msgConfig);await navigator.clipboard.writeText(msgConfig);Logger("Generated report has been copied to clipboard. Please report the issue with this! Thank you for your cooperation!",LOG_LEVEL_NOTICE)}))));new LiveSyncSetting(paneEl2).autoWireToggle("writeLogToTheFile")}));addPanel(paneEl,"Scram Switches").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("suspendFileWatching");this.addOnSaved("suspendFileWatching",(()=>this.plugin.$$askReload()));new LiveSyncSetting(paneEl2).autoWireToggle("suspendParseReplicationResult");this.addOnSaved("suspendParseReplicationResult",(()=>this.plugin.$$askReload()))}));addPanel(paneEl,"Recovery and Repair").then((paneEl2=>{const addResult=async(path2,file,fileOnDB)=>{const storageFileStat=file?await this.plugin.storageAccess.statHidden(file):null;resultArea.appendChild(this.createEl(resultArea,"div",{},(el=>{el.appendChild(this.createEl(el,"h6",{text:path2}));el.appendChild(this.createEl(el,"div",{},(infoGroupEl=>{infoGroupEl.appendChild(this.createEl(infoGroupEl,"div",{text:"Storage : Modified: "+(storageFileStat?`${new Date(storageFileStat.mtime).toLocaleString()}, Size:${storageFileStat.size}`:"Missing:")}));infoGroupEl.appendChild(this.createEl(infoGroupEl,"div",{text:"Database: Modified: "+(fileOnDB?`${new Date(fileOnDB.mtime).toLocaleString()}, Size:${fileOnDB.size}`:"Missing:")}))})));fileOnDB&&file&&el.appendChild(this.createEl(el,"button",{text:"Show history"},(buttonEl=>{buttonEl.onClickEvent((()=>{eventHub.emitEvent(EVENT_REQUEST_SHOW_HISTORY,{file,fileOnDB})}))})));file&&el.appendChild(this.createEl(el,"button",{text:"Storage -> Database"},(buttonEl=>{buttonEl.onClickEvent((async()=>{if(file.startsWith(".")){const addOn=this.plugin.getAddOn(HiddenFileSync.name);if(addOn){const file2=(await addOn.scanInternalFiles()).find((e3=>e3.path==path2));if(!file2){Logger(`Failed to find the file in the internal files: ${path2}`,LOG_LEVEL_NOTICE);return}if(!await addOn.storeInternalFileToDatabase(file2,!0)){Logger(`Failed to store the file to the database (Hidden file): ${file2}`,LOG_LEVEL_NOTICE);return}}}else if(!await this.plugin.fileHandler.storeFileToDB(file,!0)){Logger(`Failed to store the file to the database: ${file}`,LOG_LEVEL_NOTICE);return}el.remove()}))})));fileOnDB&&el.appendChild(this.createEl(el,"button",{text:"Database -> Storage"},(buttonEl=>{buttonEl.onClickEvent((async()=>{if(fileOnDB.path.startsWith(ICHeader)){const addOn=this.plugin.getAddOn(HiddenFileSync.name);if(addOn&&!await addOn.extractInternalFileFromDatabase(path2,!0)){Logger(`Failed to store the file to the database (Hidden file): ${file}`,LOG_LEVEL_NOTICE);return}}else if(!await this.plugin.fileHandler.dbToStorage(fileOnDB,null,!0)){Logger(`Failed to store the file to the storage: ${fileOnDB.path}`,LOG_LEVEL_NOTICE);return}el.remove()}))})));return el})))},checkBetweenStorageAndDatabase=async(file,fileOnDB)=>{const dataContent=readAsBlob(fileOnDB),content=createBlob(await this.plugin.storageAccess.readHiddenFileBinary(file));if(await isDocContentSame(content,dataContent))Logger(`Compare: SAME: ${file}`);else{Logger(`Compare: CONTENT IS NOT MATCHED! ${file}`,LOG_LEVEL_NOTICE);addResult(file,file,fileOnDB)}};new LiveSyncSetting(paneEl2).setName("Recreate missing chunks for all files").setDesc("This will recreate chunks for all files. If there were missing chunks, this may fix the errors.").addButton((button=>button.setButtonText("Recreate all").setCta().onClick((async()=>{await this.plugin.fileHandler.createAllChunks(!0)}))));new LiveSyncSetting(paneEl2).setName("Resolve All conflicted files by the newer one").setDesc("Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.").addButton((button=>button.setButtonText("Resolve All").setCta().onClick((async()=>{await this.plugin.rebuilder.resolveAllConflictedFilesByNewerOnes()}))));new LiveSyncSetting(paneEl2).setName("Verify and repair all files").setDesc("Compare the content of files between on local database and storage. If not matched, you will be asked which one you want to keep.").addButton((button=>button.setButtonText("Verify all").setDisabled(!1).setCta().onClick((async()=>{Logger("Start verifying all files",LOG_LEVEL_NOTICE,"verify");const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns"),targetPatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");this.plugin.localDatabase.hashCaches.clear();Logger("Start verifying all files",LOG_LEVEL_NOTICE,"verify");const files=this.plugin.settings.syncInternalFiles?await this.plugin.storageAccess.getFilesIncludeHidden("/",targetPatterns,ignorePatterns):await this.plugin.storageAccess.getFileNames(),documents=[],adn=this.plugin.localDatabase.findAllDocs();for await(const i3 of adn){const path2=getPath2(i3);path2.startsWith(ICXHeader)||path2.startsWith(PSCHeader)||!this.plugin.settings.syncInternalFiles&&path2.startsWith(ICHeader)||documents.push(stripAllPrefixes(path2))}const allPaths=[...new Set([...documents,...files])];let i2=0;const incProc=()=>{i2++;i2%25==0&&Logger(`Checking ${i2}/${allPaths.length} files \n`,LOG_LEVEL_NOTICE,"verify-processed")},semaphore=Semaphore(10),processes=allPaths.map((async path2=>{try{if(shouldBeIgnored(path2))return incProc();const stat=!!await this.plugin.storageAccess.isExistsIncludeHidden(path2)&&await this.plugin.storageAccess.statHidden(path2),fileOnStorage=null!=stat&&stat;if(!await this.plugin.$$isTargetFile(path2))return incProc();const releaser=await semaphore.acquire(1);if(fileOnStorage&&this.plugin.$$isFileSizeExceeded(fileOnStorage.size))return incProc();try{const dbPath=path2.startsWith(".")?addPrefix(path2,ICHeader):path2,fileOnDB=await this.plugin.localDatabase.getDBEntry(dbPath);if(fileOnDB&&this.plugin.$$isFileSizeExceeded(fileOnDB.size))return incProc();if(!fileOnDB&&fileOnStorage){Logger(`Compare: Not found on the local database: ${path2}`,LOG_LEVEL_NOTICE);addResult(path2,path2,!1);return incProc()}if(fileOnDB&&!fileOnStorage){Logger(`Compare: Not found on the storage: ${path2}`,LOG_LEVEL_NOTICE);addResult(path2,!1,fileOnDB);return incProc()}fileOnStorage&&fileOnDB&&await checkBetweenStorageAndDatabase(path2,fileOnDB)}catch(ex){Logger(`Error while processing ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{releaser();incProc()}}catch(ex){Logger(`Error while processing without semaphore ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);Logger("done",LOG_LEVEL_NOTICE,"verify")}))));const resultArea=paneEl2.createDiv({text:""});new LiveSyncSetting(paneEl2).setName("Check and convert non-path-obfuscated files").setDesc("").addButton((button=>button.setButtonText("Perform").setDisabled(!1).setWarning().onClick((async()=>{var _a8,_b4,_c3;for await(const docName of this.plugin.localDatabase.findAllDocNames())if(!docName.startsWith("f:")){const idEncoded=await this.plugin.$$path2id(docName),doc=await this.plugin.localDatabase.getRaw(docName);if(!doc)continue;if("newnote"!=doc.type&&"plain"!=doc.type)continue;if(null!=(_a8=null==doc?void 0:doc.deleted)&&_a8)continue;const newDoc={...doc};newDoc._id=idEncoded;newDoc.path=docName;delete newDoc._rev;try{const obfuscatedDoc=await this.plugin.localDatabase.getRaw(idEncoded,{revs_info:!0});null==(_b4=obfuscatedDoc._revs_info)||_b4.shift();const previousRev=null==(_c3=obfuscatedDoc._revs_info)?void 0:_c3.shift();newDoc._rev=previousRev?previousRev.rev:"1-"+`00000000000000000000000000000000${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}`.slice(-32);const ret=await this.plugin.localDatabase.putRaw(newDoc,{force:!0});if(ret.ok){Logger(`${docName} has been converted as conflicted document`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.plugin.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE);await this.plugin.$$queueConflictCheckIfOpen(docName)}else{Logger(`Converting ${docName} Failed!`,LOG_LEVEL_NOTICE);Logger(ret,LOG_LEVEL_VERBOSE)}}catch(ex){if(404==(null==ex?void 0:ex.status)){if((await this.plugin.localDatabase.putRaw(newDoc)).ok){Logger(`${docName} has been converted`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.plugin.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE)}}else{Logger(`Something went wrong while converting ${docName}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}}Logger("Converting finished",LOG_LEVEL_NOTICE)}))))}));addPanel(paneEl,"Reset").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Back to non-configured").addButton((button=>button.setButtonText("Back").setDisabled(!1).onClick((async()=>{this.editingSettings.isConfigured=!1;await this.saveAllDirtySettings();this.plugin.$$askReload()}))));new LiveSyncSetting(paneEl2).setName("Delete all customization sync data").addButton((button=>button.setButtonText("Delete").setDisabled(!1).setWarning().onClick((async()=>{Logger("Deleting customization sync data",LOG_LEVEL_NOTICE);const newData=(await this.plugin.localDatabase.allDocsRaw({startkey:"ix:",endkey:"ix:􏿿",include_docs:!0})).rows.map((e3=>({...e3.doc,_deleted:!0})));Logger(`${(await this.plugin.localDatabase.bulkDocsRaw(newData)).length} items have been removed, to confirm how many items are left, please perform it again.`,LOG_LEVEL_NOTICE)}))))}))}function paneAdvanced(paneEl,{addPanel}){addPanel(paneEl,"Memory cache").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireNumeric("hashCacheMaxCount",{clampMin:10});new LiveSyncSetting(paneEl2).autoWireNumeric("hashCacheMaxAmount",{clampMin:1})}));addPanel(paneEl,"Local Database Tweak").then((paneEl2=>{paneEl2.addClass("wizardHidden");const items=ChunkAlgorithmNames;new LiveSyncSetting(paneEl2).autoWireDropDown("chunkSplitterVersion",{options:items});new LiveSyncSetting(paneEl2).autoWireNumeric("customChunkSize",{clampMin:0,acceptZero:!0})}));addPanel(paneEl,"Transfer Tweak").then((paneEl2=>{new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("readChunksOnline",{onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("concurrencyOfReadChunksOnline",{clampMin:10,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("minimumIntervalOfReadChunksOnline",{clampMin:10,onUpdate:this.onlyOnCouchDB})}))}function panePowerUsers(paneEl,{addPanel}){addPanel(paneEl,"Remote Database Tweak").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("useEden").setClass("wizardHidden");const onlyUsingEden=visibleOnly((()=>this.isConfiguredAs("useEden",!0)));new LiveSyncSetting(paneEl2).autoWireNumeric("maxChunksInEden",{onUpdate:onlyUsingEden}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("maxTotalLengthInEden",{onUpdate:onlyUsingEden}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("maxAgeInEden",{onUpdate:onlyUsingEden}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireToggle("enableCompression").setClass("wizardHidden")}));addPanel(paneEl,"CouchDB Connection Tweak",void 0,this.onlyOnCouchDB).then((paneEl2=>{paneEl2.addClass("wizardHidden");this.createEl(paneEl2,"div",{text:"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."},void 0,this.onlyOnCouchDB).addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batch_size",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batches_limit",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("useTimeouts",{onUpdate:this.onlyOnCouchDB})}));addPanel(paneEl,"Configuration Encryption").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Encrypting sensitive configuration items").autoWireDropDown("configPassphraseStore",{options:{"":"Default",LOCALSTORAGE:"Use a custom passphrase",ASK_AT_LAUNCH:"Ask an passphrase at every launch"},holdValue:!0}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireText("configPassphrase",{isPassword:!0,holdValue:!0}).setClass("wizardHidden").addOnUpdate((()=>({disabled:!this.isConfiguredAs("configPassphraseStore","LOCALSTORAGE")})));new LiveSyncSetting(paneEl2).addApplyButton(["configPassphrase","configPassphraseStore"]).setClass("wizardHidden")}));addPanel(paneEl,"Developer").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("enableDebugTools").setClass("wizardHidden")}))}function panePatches(paneEl,{addPanel}){addPanel(paneEl,"Compatibility (Metadata)").then((paneEl2=>{new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("deleteMetadataOfDeletedFiles");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("automaticallyDeleteMetadataOfDeletedFiles",{onUpdate:visibleOnly((()=>this.isConfiguredAs("deleteMetadataOfDeletedFiles",!0)))})}));addPanel(paneEl,"Compatibility (Conflict Behaviour)").then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("disableMarkdownAutoMerge");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("writeDocumentsIfConflicted")}));addPanel(paneEl,"Compatibility (Database structure)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("useIndexedDBAdapter",{invert:!0,holdValue:!0});new LiveSyncSetting(paneEl2).autoWireToggle("doNotUseFixedRevisionForChunks",{holdValue:!0}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireToggle("handleFilenameCaseSensitive",{holdValue:!0}).setClass("wizardHidden");this.addOnSaved("useIndexedDBAdapter",(async()=>{await this.saveAllDirtySettings();await this.rebuildDB("localOnly")}))}));addPanel(paneEl,"Compatibility (Internal API Usage)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("watchInternalFileChanges",{invert:!0})}));addPanel(paneEl,"Edge case addressing (Database)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireText("additionalSuffixOfDatabaseName",{holdValue:!0}).addApplyButton(["additionalSuffixOfDatabaseName"]);this.addOnSaved("additionalSuffixOfDatabaseName",(async key2=>{Logger("Suffix has been changed. Reopening database...",LOG_LEVEL_NOTICE);await this.plugin.$$initializeDatabase()}));new LiveSyncSetting(paneEl2).autoWireDropDown("hashAlg",{options:{"":"Old Algorithm",xxhash32:"xxhash32 (Fast but less collision resistance)",xxhash64:"xxhash64 (Fastest)","mixed-purejs":"PureJS fallback (Fast, W/O WebAssembly)",sha1:"Older fallback (Slow, W/O WebAssembly)"}});this.addOnSaved("hashAlg",(async()=>{await this.plugin.localDatabase._prepareHashFunctions()}))}));addPanel(paneEl,"Edge case addressing (Behaviour)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("doNotSuspendOnFetching");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("doNotDeleteFolder")}));addPanel(paneEl,"Edge case addressing (Processing)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableWorkerForGeneratingChunks");new LiveSyncSetting(paneEl2).autoWireToggle("processSmallFilesInUIThread",{onUpdate:visibleOnly((()=>this.isConfiguredAs("disableWorkerForGeneratingChunks",!1)))})}));addPanel(paneEl,"Compatibility (Trouble addressed)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableCheckingConfigMismatch")}))}function paneMaintenance(paneEl,{addPanel}){this.createEl(paneEl,"div",{text:"The remote database is locked for synchronization to prevent vault corruption because this device isn't marked as 'resolved'. Please backup your vault, reset the local database, and select 'Mark this device as resolved'. This warning will persist until the device is confirmed as resolved by replication.",cls:"op-warn"},(c3=>{this.createEl(c3,"button",{text:"I've made a backup, mark this device 'resolved'",cls:"mod-warning"},(e3=>{e3.addEventListener("click",(()=>{fireAndForget((async()=>{await this.plugin.$$markRemoteResolved();this.display()}))}))}))}),visibleOnly((()=>{var _a8,_b4;return null==(_b4=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b4.remoteLockedAndDeviceNotAccepted})));this.createEl(paneEl,"div",{text:"To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database. This warning kept showing until confirming the device is resolved by the replication",cls:"op-warn"},(c3=>this.createEl(c3,"button",{text:"I'm ready, unlock the database",cls:"mod-warning"},(e3=>{e3.addEventListener("click",(()=>{fireAndForget((async()=>{await this.plugin.$$markRemoteUnlocked();this.display()}))}))}))),visibleOnly((()=>{var _a8,_b4;return null==(_b4=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b4.remoteLocked})));addPanel(paneEl,"Scram!").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Lock Server").setDesc("Lock the remote server to prevent synchronization with other devices.").addButton((button=>button.setButtonText("Lock").setDisabled(!1).setWarning().onClick((async()=>{await this.plugin.$$markRemoteLocked()})))).addOnUpdate(this.onlyOnCouchDBOrMinIO);new LiveSyncSetting(paneEl2).setName("Emergency restart").setDesc("Disables all synchronization and restart.").addButton((button=>button.setButtonText("Flag and restart").setDisabled(!1).setWarning().onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG,"");this.plugin.$$performRestart()}))))}));addPanel(paneEl,"Syncing",(()=>{}),this.onlyOnCouchDBOrMinIO).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Resend").setDesc("Resend all chunks to the remote.").addButton((button=>button.setButtonText("Send chunks").setWarning().setDisabled(!1).onClick((async()=>{this.plugin.replicator instanceof LiveSyncCouchDBReplicator&&await this.plugin.replicator.sendChunks(this.plugin.settings,void 0,!0,0)})))).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Reset journal received history").setDesc("Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.").addButton((button=>button.setButtonText("Reset received").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,receivedFiles:new Set,knownIDs:new Set})));Logger("Journal received history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Reset journal sent history").setDesc("Initialise journal sent history. On the next sync, every item except this device received will be sent again.").addButton((button=>button.setButtonText("Reset sent history").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set})));Logger("Journal sent history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO)}));addPanel(paneEl,"Garbage Collection (Beta)",(e3=>e3),this.onlyOnP2POrCouchDB).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Remove all orphaned chunks").setDesc("Remove all orphaned chunks from the local database.").addButton((button=>button.setButtonText("Remove").setWarning().setDisabled(!1).onClick((async()=>{var _a8;await(null==(_a8=this.plugin.getAddOn(LocalDatabaseMaintenance.name))?void 0:_a8.removeUnusedChunks())}))));new LiveSyncSetting(paneEl2).setName("Resurrect deleted chunks").setDesc("If you have deleted chunks before fully synchronised and missed some chunks, you possibly can resurrect them.").addButton((button=>button.setButtonText("Try resurrect").setWarning().setDisabled(!1).onClick((async()=>{var _a8;await(null==(_a8=this.plugin.getAddOn(LocalDatabaseMaintenance.name))?void 0:_a8.resurrectChunks())}))));new LiveSyncSetting(paneEl2).setName("Commit File Deletion").setDesc("Completely delete all deleted documents from the local database.").addButton((button=>button.setButtonText("Delete").setWarning().setDisabled(!1).onClick((async()=>{var _a8;await(null==(_a8=this.plugin.getAddOn(LocalDatabaseMaintenance.name))?void 0:_a8.commitFileDeletion())}))))}));addPanel(paneEl,"Rebuilding Operations (Local)").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Fetch from remote").setDesc("Restore or reconstruct local database from remote.").addButton((button=>button.setButtonText("Fetch").setWarning().setDisabled(!1).onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG3_HR,"");this.plugin.$$performRestart()})))).addButton((button=>button.setButtonText("Fetch w/o restarting").setWarning().setDisabled(!1).onClick((async()=>{await this.rebuildDB("localOnly")}))));new LiveSyncSetting(paneEl2).setName("Fetch rebuilt DB (Save local documents before)").setDesc("Restore or reconstruct local database from remote database but use local chunks.").addButton((button=>button.setButtonText("Save and Fetch").setWarning().setDisabled(!1).onClick((async()=>{await this.rebuildDB("localOnlyWithChunks")})))).addOnUpdate(this.onlyOnCouchDB)}));addPanel(paneEl,"Total Overhaul",(()=>{}),this.onlyOnCouchDBOrMinIO).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Rebuild everything").setDesc("Rebuild local and remote database with local files.").addButton((button=>button.setButtonText("Rebuild").setWarning().setDisabled(!1).onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG2_HR,"");this.plugin.$$performRestart()})))).addButton((button=>button.setButtonText("Rebuild w/o restarting").setWarning().setDisabled(!1).onClick((async()=>{await this.rebuildDB("rebuildBothByThisDevice")}))))}));addPanel(paneEl,"Rebuilding Operations (Remote Only)",(()=>{}),this.onlyOnCouchDBOrMinIO).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Perform cleanup").setDesc("Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.").addButton((button=>button.setButtonText("Perform").setDisabled(!1).onClick((async()=>{const replicator=this.plugin.replicator;Logger("Cleanup has been began",LOG_LEVEL_NOTICE,"compaction");await replicator.compactRemote(this.editingSettings)?Logger("Cleanup has been completed!",LOG_LEVEL_NOTICE,"compaction"):Logger("Cleanup has been failed!",LOG_LEVEL_NOTICE,"compaction")})))).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Overwrite remote").setDesc("Overwrite remote with local DB and passphrase.").addButton((button=>button.setButtonText("Send").setWarning().setDisabled(!1).onClick((async()=>{await this.rebuildDB("remoteOnly")}))));new LiveSyncSetting(paneEl2).setName("Reset all journal counter").setDesc("Initialise all journal history, On the next sync, every item will be received and sent.").addButton((button=>button.setButtonText("Reset all").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().resetCheckpointInfo();Logger("Journal exchange history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Purge all journal counter").setDesc("Purge all download/upload cache.").addButton((button=>button.setButtonText("Reset all").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().resetAllCaches();Logger("Journal download/upload cache has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Fresh Start Wipe").setDesc("Delete all data on the remote server.").addButton((button=>button.setButtonText("Delete").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,receivedFiles:new Set,knownIDs:new Set,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set})));await this.resetRemoteBucket();Logger("Deleted all data on remote server",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO)}));addPanel(paneEl,"Reset").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Delete local database to reset or uninstall Self-hosted LiveSync").addButton((button=>button.setButtonText("Delete").setWarning().setDisabled(!1).onClick((async()=>{await this.plugin.$$resetLocalDatabase();await this.plugin.$$initializeDatabase()}))))}))}function isImage(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["png","jpg","jpeg","gif","bmp","webp"].includes(ext2)}function readDocument(w2){if(0==w2.data.length)return"";if(isImage(w2.path))return new Uint8Array(decodeBinary(w2.data));if("plain"==w2.type||"plain"==w2.datatype)return getDocData(w2.data);if(function isComparableTextDecode(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["json"].includes(ext2)}(w2.path))return readString(new Uint8Array(decodeBinary(w2.data)));if(function isComparableText(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return isPlainText(path2)||["md","mdx","txt","json"].includes(ext2)}(w2.path))return getDocData(w2.data);try{return readString(new Uint8Array(decodeBinary(w2.data)))}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE)}return getDocData(w2.data)}function GlobalHistory($$anchor,$$props){function mtimeToDate(mtime){return new Date(mtime).toLocaleString()}async function getHistory(showDiffInfo2,showChunkCorrected2,checkStorageDiff2){set(loading,!0);const newDisplay=[],page=await async function fetchChanges(){var _a8,_b4,_c3;try{const db=plugin3().localDatabase;let result=[];for await(const docA of db.findAllNormalDocs()){if(docA.mtimemtime)continue;if(get(range_to_epoch){var _a9;return{...p5,[c3[0]]:(null!==(_a9=p5[c3[0]])&&void 0!==_a9?_a9:0)+c3[1].length}}),pxInit);diffDetail=`-${px[DIFF_DELETE4]}, +${px[DIFF_INSERT4]}`}}const isDeleted2=doc._deleted||(null==doc?void 0:doc.deleted)||!1;isDeleted2&&(diffDetail+=" 🗑️");if(rev3==docA._rev&&get(checkStorageDiff)&&await plugin3().storageAccess.isExistsIncludeHidden(stripAllPrefixes(getPath2(docA)))){const data=await plugin3().storageAccess.readHiddenFileBinary(stripAllPrefixes(getPath2(docA))),d4=readAsBlob(doc);diffDetail+=await isDocContentSame(data,d4)?" ⚖️":" ⚠️"}const docPath=getPath2(doc),[filename,...pathItems]=docPath.split("/").reverse();let chunksStatus="";if(get(showChunkCorrected)){const chunks=null!==(_b4=null==doc?void 0:doc.children)&&void 0!==_b4?_b4:[],loadedChunks=await db.allDocsRaw({keys:[...chunks]}),totalCount=loadedChunks.rows.length,errorCount=loadedChunks.rows.filter((e3=>"error"in e3)).length;chunksStatus=0==errorCount?`✅ ${totalCount}`:`🔎 ${errorCount} ✅ ${totalCount}`}result.push({id:doc._id,rev:doc._rev,path:docPath,dirname:pathItems.reverse().join("/"),filename,mtime,mtimeDisp:mtimeToDate(mtime),size:null!==(_c3=null==doc?void 0:doc.size)&&void 0!==_c3?_c3:0,isDeleted:isDeleted2,changes:diffDetail,chunks:chunksStatus,isPlain})}}return[...result].sort(((a2,b3)=>b3.mtime-a2.mtime))}finally{set(loading,!1)}}();newDisplay.push(...page);set(history,[...newDisplay])}var div,div_1,div_2,input,div_3,input_1,div_4,label,input_2,label_1,input_3,label_2,input_4,node,consequent,table2,tbody,tr,node_1,consequent_1,tr_1,td3,node_2,consequent_2,alternate,node_3,tr_3,td_6,node_6,consequent_5,alternate_2;push($$props,!1);append_styles($$anchor,$$css7);let plugin3=prop($$props,"plugin",8),showDiffInfo=mutable_source(!1),showChunkCorrected=mutable_source(!1),checkStorageDiff=mutable_source(!1),range_from_epoch=mutable_source(Date.now()-6048e5),range_to_epoch=mutable_source(Date.now()+1728e5);const timezoneOffset=(new Date).getTimezoneOffset();let dispDateFrom=mutable_source(new Date(get(range_from_epoch)-timezoneOffset).toISOString().split("T")[0]),dispDateTo=mutable_source(new Date(get(range_to_epoch)-timezoneOffset).toISOString().split("T")[0]),history=mutable_source([]),loading=mutable_source(!1);onMount((async()=>{await getHistory(get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))}));onDestroy((()=>{}));legacy_pre_effect((()=>(get(dispDateFrom),get(dispDateTo),get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))),(()=>{set(range_from_epoch,new Date(get(dispDateFrom)).getTime()+timezoneOffset);set(range_to_epoch,new Date(get(dispDateTo)).getTime()+timezoneOffset);getHistory(get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))}));legacy_pre_effect_reset();init();div_1=sibling(child(div=root6()),2);div_2=child(div_1);remove_input_defaults(input=sibling(child(div_2)));reset(div_2);div_3=sibling(div_2,2);remove_input_defaults(input_1=sibling(child(div_3)));reset(div_3);div_4=sibling(div_3,2);label=sibling(child(div_4),2);remove_input_defaults(input_2=child(label));next();reset(label);label_1=sibling(label,2);remove_input_defaults(input_3=child(label_1));next();reset(label_1);label_2=sibling(label_1,2);remove_input_defaults(input_4=child(label_2));next();reset(label_2);reset(div_4);reset(div_1);node=sibling(div_1,2);consequent=$$anchor2=>{append($$anchor2,root_111())};if_block(node,($$render=>{get(loading)&&$$render(consequent)}));tbody=child(table2=sibling(node,2));tr=child(tbody);node_1=sibling(child(tr),4);consequent_1=$$anchor2=>{append($$anchor2,root_24())};if_block(node_1,($$render=>{get(showChunkCorrected)&&$$render(consequent_1)}));reset(tr);td3=child(tr_1=sibling(tr));node_2=child(td3);consequent_2=$$anchor2=>{append($$anchor2,root_33())};alternate=$$anchor2=>{var div_7=root_44(),button=child(div_7);reset(div_7);event("click",button,(()=>function nextWeek(){set(dispDateTo,new Date(get(range_to_epoch)-timezoneOffset+6048e5).toISOString().split("T")[0])}()));append($$anchor2,div_7)};if_block(node_2,($$render=>{get(loading)?$$render(consequent_2):$$render(alternate,!1)}));reset(td3);reset(tr_1);each(node_3=sibling(tr_1),1,(()=>get(history)),index,(($$anchor2,entry)=>{var td_2,div_8,span,text_1,span_1,a_1,text_2,td_3,span_2,node_4,consequent_3,alternate_1,td_4,text_5,node_5,consequent_4,tr_2=root_53(),td_1=child(tr_2),text2=child(td_1,!0);reset(td_1);div_8=child(td_2=sibling(td_1));span=child(div_8);text_1=child(span);reset(span);a_1=child(span_1=sibling(span,2));text_2=child(a_1,!0);reset(a_1);reset(span_1);reset(div_8);reset(td_2);span_2=child(td_3=sibling(td_2));node_4=child(span_2);consequent_3=$$anchor3=>{var a_2=root_64(),text_3=child(a_2,!0);reset(a_2);template_effect((()=>set_text(text_3,get(entry).rev)));event("click",a_2,(()=>{var _a8;return function showHistory(file,rev3){new DocumentHistoryModal(plugin3().app,plugin3(),file,void 0,rev3).open()}(get(entry).path,(null==(_a8=get(entry))?void 0:_a8.rev)||"")}));append($$anchor3,a_2)};alternate_1=$$anchor3=>{var text_4=text();template_effect((()=>set_text(text_4,get(entry).rev)));append($$anchor3,text_4)};if_block(node_4,($$render=>{get(entry).isPlain?$$render(consequent_3):$$render(alternate_1,!1)}));reset(span_2);reset(td_3);td_4=sibling(td_3);text_5=child(td_4,!0);reset(td_4);node_5=sibling(td_4);consequent_4=$$anchor3=>{var td_5=root_83(),text_6=child(td_5,!0);reset(td_5);template_effect((()=>set_text(text_6,get(entry).chunks)));append($$anchor3,td_5)};if_block(node_5,($$render=>{get(showChunkCorrected)&&$$render(consequent_4)}));reset(tr_2);template_effect(($0=>{set_text(text2,get(entry).mtimeDisp);set_text(text_1,`/${null!=$0?$0:""}`);set_text(text_2,get(entry).filename);set_text(text_5,get(entry).changes)}),[()=>get(entry).dirname.split("/").join("​/")],derived_safe_equal);event("click",a_1,(()=>function openFile(file){plugin3().app.workspace.openLinkText(file,file)}(get(entry).path)));append($$anchor2,tr_2)}));td_6=child(tr_3=sibling(node_3));node_6=child(td_6);consequent_5=$$anchor2=>{append($$anchor2,root_93())};alternate_2=$$anchor2=>{var div_10=root_102(),button_1=child(div_10);reset(div_10);event("click",button_1,(()=>function prevWeek(){set(dispDateFrom,new Date(get(range_from_epoch)-timezoneOffset-6048e5).toISOString().split("T")[0])}()));append($$anchor2,div_10)};if_block(node_6,($$render=>{get(loading)?$$render(consequent_5):$$render(alternate_2,!1)}));reset(td_6);reset(tr_3);reset(tbody);reset(table2);reset(div);template_effect((()=>{input.disabled=get(loading);input_1.disabled=get(loading);input_2.disabled=get(loading);input_3.disabled=get(loading);input_4.disabled=get(loading)}));bind_value(input,(()=>get(dispDateFrom)),($$value=>set(dispDateFrom,$$value)));bind_value(input_1,(()=>get(dispDateTo)),($$value=>set(dispDateTo,$$value)));bind_checked(input_2,(()=>get(showDiffInfo)),($$value=>set(showDiffInfo,$$value)));bind_checked(input_3,(()=>get(showChunkCorrected)),($$value=>set(showChunkCorrected,$$value)));bind_checked(input_4,(()=>get(checkStorageDiff)),($$value=>set(checkStorageDiff,$$value)));append($$anchor,div);pop()}function startWatching(_,replicator,peer){replicator.watchPeer(get(peer).peerId)}function stopWatching(__1,replicator,peer){replicator.unwatchPeer(get(peer).peerId)}function sync2(__2,replicator,peer){replicator.sync(get(peer).peerId,!1)}function moreMenu(evt,peer){eventHub.emitEvent(EVENT_P2P_PEER_SHOW_EXTRA_MENU,{peer:get(peer),event:evt})}async function saveAndApply(_,plugin3,eP2PEnabled,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast,$$props,eDeviceName,deviceName){const newSettings={...plugin3().settings,P2P_Enabled:get(eP2PEnabled),P2P_relays:get(eRelay),P2P_roomID:get(eRoomId),P2P_passphrase:get(ePassword),P2P_AppID:get(eAppId),P2P_AutoAccepting:get(eAutoAccept)?1:0,P2P_AutoStart:get(eAutoStart),P2P_AutoBroadcast:get(eAutoBroadcast)};plugin3().settings=newSettings;$$props.cmdSync.setConfig("p2p_device_name",get(eDeviceName));set(deviceName,get(eDeviceName),!0);await plugin3().saveSettings()}async function revert(__1,eP2PEnabled,settings,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast){set(eP2PEnabled,get(settings).P2P_Enabled,!0);set(eRelay,get(settings).P2P_relays,!0);set(eRoomId,get(settings).P2P_roomID,!0);set(ePassword,get(settings).P2P_passphrase,!0);set(eAppId,get(settings).P2P_AppID,!0);set(eAutoAccept,1==get(settings).P2P_AutoAccepting);set(eAutoStart,get(settings).P2P_AutoStart,!0);set(eAutoBroadcast,get(settings).P2P_AutoBroadcast,!0)}async function openServer(__2,$$props){await $$props.cmdSync.open()}function startBroadcasting(__3,$$props){$$props.cmdSync.enableBroadcastCastings()}function stopBroadcasting(__4,$$props){$$props.cmdSync.disableBroadcastCastings()}function P2PReplicatorPane($$anchor,$$props){async function closeServer(){await $$props.cmdSync.close()}var _a8,_b4,_c3,article,details,summary,text2,p4,text_1,p_1,text_2,details_1,summary_1,text_4,table2,tbody,tr,td3,label,input,tr_1,td_1,label_1,input_1,tr_2,td_2,label_2,input_2,tr_3,td_3,label_3,input_3,tr_4,td_4,label_4,input_4,tr_5,td_5,label_5,input_5,tr_6,td_6,label_6,input_6,button_2,button_3,div,div_1,node_1,consequent,alternate,div_2,node_2,consequent_1,alternate_1,div_3,table_1,tbody_1;push($$props,!0);append_styles($$anchor,$$css9);let plugin3=prop($$props,"plugin",7);(function setContext(key2,context2){get_or_init_context_map("setContext").set(key2,context2)})("getReplicator",(()=>$$props.cmdSync));const initialSettings={...plugin3().settings};let settings=state(proxy(initialSettings));const initialDeviceName=null!==(_a8=$$props.cmdSync.getConfig("p2p_device_name"))&&void 0!==_a8?_a8:plugin3().$$getVaultName();let deviceName=state(proxy(initialDeviceName)),eP2PEnabled=state(proxy(initialSettings.P2P_Enabled)),eRelay=state(proxy(initialSettings.P2P_relays)),eRoomId=state(proxy(initialSettings.P2P_roomID)),ePassword=state(proxy(initialSettings.P2P_passphrase)),eAppId=state(proxy(initialSettings.P2P_AppID)),eDeviceName=state(proxy(initialDeviceName)),eAutoAccept=state(1==initialSettings.P2P_AutoAccepting),eAutoStart=state(proxy(initialSettings.P2P_AutoStart)),eAutoBroadcast=state(proxy(initialSettings.P2P_AutoBroadcast));const isP2PEnabledModified=user_derived((()=>get(eP2PEnabled)!==get(settings).P2P_Enabled)),isRelayModified=user_derived((()=>get(eRelay)!==get(settings).P2P_relays)),isRoomIdModified=user_derived((()=>get(eRoomId)!==get(settings).P2P_roomID)),isPasswordModified=user_derived((()=>get(ePassword)!==get(settings).P2P_passphrase)),isAppIdModified=user_derived((()=>get(eAppId)!==get(settings).P2P_AppID)),isDeviceNameModified=user_derived((()=>get(eDeviceName)!==get(deviceName))),isAutoAcceptModified=user_derived((()=>get(eAutoAccept)!==(1==get(settings).P2P_AutoAccepting))),isAutoStartModified=user_derived((()=>get(eAutoStart)!==get(settings).P2P_AutoStart)),isAutoBroadcastModified=user_derived((()=>get(eAutoBroadcast)!==get(settings).P2P_AutoBroadcast)),isAnyModified=user_derived((()=>get(isP2PEnabledModified)||get(isRelayModified)||get(isRoomIdModified)||get(isPasswordModified)||get(isAppIdModified)||get(isDeviceNameModified)||get(isAutoAcceptModified)||get(isAutoStartModified)||get(isAutoBroadcastModified)));let serverInfo=state(void 0),replicatorInfo=state(void 0);const applyLoadSettings=(d4,force)=>{const{P2P_relays,P2P_roomID,P2P_passphrase,P2P_AppID,P2P_AutoAccepting}=d4;!force&&get(isP2PEnabledModified)||set(eP2PEnabled,d4.P2P_Enabled,!0);!force&&get(isRelayModified)||set(eRelay,P2P_relays,!0);!force&&get(isRoomIdModified)||set(eRoomId,P2P_roomID,!0);!force&&get(isPasswordModified)||set(ePassword,P2P_passphrase,!0);!force&&get(isAppIdModified)||set(eAppId,P2P_AppID,!0);const newAutoAccept=1===P2P_AutoAccepting;!force&&get(isAutoAcceptModified)||set(eAutoAccept,newAutoAccept);!force&&get(isAutoStartModified)||set(eAutoStart,d4.P2P_AutoStart,!0);!force&&get(isAutoBroadcastModified)||set(eAutoBroadcast,d4.P2P_AutoBroadcast,!0);set(settings,d4,!0)};onMount((()=>{const r4=eventHub.onEvent("setting-saved",(async d4=>{applyLoadSettings(d4,!1);closeServer()})),r22=(eventHub.onEvent(EVENT_LAYOUT_READY,(()=>{applyLoadSettings(plugin3().settings,!0)})),eventHub.onEvent(EVENT_SERVER_STATUS,(status=>{var _a9;set(serverInfo,status,!0);set(advertisements,null!==(_a9=null==status?void 0:status.knownAdvertisements)&&void 0!==_a9?_a9:[],!0)}))),r32=eventHub.onEvent(EVENT_P2P_REPLICATOR_STATUS,(status=>{set(replicatorInfo,status,!0)}));eventHub.emitEvent(EVENT_REQUEST_STATUS);return()=>{r4();r22();r32()}}));let isConnected=user_derived((()=>{var _a9;return null!==(_a9=null===get(serverInfo)||void 0===get(serverInfo)?void 0:get(serverInfo).isConnected)&&void 0!==_a9&&_a9})),serverPeerId=user_derived((()=>{var _a9;return null!==(_a9=null===get(serverInfo)||void 0===get(serverInfo)?void 0:get(serverInfo).serverPeerId)&&void 0!==_a9?_a9:""})),advertisements=state(proxy([])),autoSyncPeers=user_derived((()=>get(settings).P2P_AutoSyncPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3)))),autoWatchPeers=user_derived((()=>get(settings).P2P_AutoWatchPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3)))),syncOnCommand=user_derived((()=>get(settings).P2P_SyncOnReplication.split(",").map((e3=>e3.trim())).filter((e3=>e3))));const peers=user_derived((()=>get(advertisements).map((ad2=>{let accepted;const isTemporaryAccepted=ad2.isTemporaryAccepted;accepted=void 0===isTemporaryAccepted?void 0===ad2.isAccepted?"Unknown":ad2.isAccepted?"Accepted":"Denied":!0===isTemporaryAccepted?"Accepted in session":"Denied in session";const isFetching=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).replicatingFrom.indexOf(ad2.peerId)),isSending=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).replicatingTo.indexOf(ad2.peerId)),isWatching=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).watchingPeers.indexOf(ad2.peerId)),syncOnStart=-1!==get(autoSyncPeers).indexOf(ad2.name),watchOnStart=-1!==get(autoWatchPeers).indexOf(ad2.name),syncOnReplicationCommand=-1!==get(syncOnCommand).indexOf(ad2.name);return{name:ad2.name,peerId:ad2.peerId,accepted,status:ad2.isAccepted?"Connected":"Disconnected",isSending,isFetching,isWatching,syncOnConnect:syncOnStart,watchOnConnect:watchOnStart,syncOnReplicationCommand}})))),initialDialogStatus=(()=>{var _a9;try{return JSON.parse(null!==(_a9=$$props.cmdSync.getConfig("p2p-dialog-status"))&&void 0!==_a9?_a9:"{}")}catch(e3){return{}}})();let isNoticeOpened=state(proxy(null===(_b4=initialDialogStatus.notice)||void 0===_b4||_b4)),isSettingOpened=state(proxy(null===(_c3=initialDialogStatus.setting)||void 0===_c3||_c3));user_effect((()=>{const dialogStatus={notice:get(isNoticeOpened),setting:get(isSettingOpened)};$$props.cmdSync.setConfig("p2p-dialog-status",JSON.stringify(dialogStatus))}));details=sibling(child(article=root8()),2);summary=child(details);text2=child(summary,!0);reset(summary);p4=sibling(summary,2);text_1=child(p4,!0);reset(p4);p_1=sibling(p4,2);text_2=child(p_1,!0);reset(p_1);each(sibling(p_1,2),17,(()=>$msg("P2P.Note.description").split("\n\n")),index,(($$anchor2,paragraph)=>{var p_2=root_114(),text_3=child(p_2,!0);reset(p_2);template_effect((()=>set_text(text_3,get(paragraph))));append($$anchor2,p_2)}));reset(details);summary_1=child(details_1=sibling(details,4));text_4=child(summary_1,!0);reset(summary_1);tbody=child(table2=sibling(summary_1,2));tr=child(tbody);td3=sibling(child(tr));label=child(td3);remove_input_defaults(input=child(label));reset(label);reset(td3);reset(tr);tr_1=sibling(tr);td_1=sibling(child(tr_1));label_1=child(td_1);remove_input_defaults(input_1=child(label_1));sibling(input_1,2).__click=[on_click3,function useDefaultRelay(){set(eRelay,DEFAULT_SETTINGS.P2P_relays,!0)}];reset(label_1);reset(td_1);reset(tr_1);tr_2=sibling(tr_1);td_2=sibling(child(tr_2));label_2=child(td_2);remove_input_defaults(input_2=child(label_2));sibling(input_2,2).__click=[on_click_12,function chooseRandom(){set(eRoomId,function generateRandom(length){let buf="";for(;buf.length{append($$anchor2,root_26())};alternate=$$anchor2=>{var p_4=root_35(),text_5=child(p_4);reset(p_4);template_effect((()=>{var _a9;return set_text(text_5,`Connected to Signaling Server (as Peer ID: ${null!=(_a9=get(serverPeerId))?_a9:""})`)}));append($$anchor2,p_4)};if_block(node_1,($$render=>{get(isConnected)?$$render(alternate,!1):$$render(consequent)}));reset(div_1);node_2=child(div_2=sibling(div_1,2));consequent_1=$$anchor2=>{var button_4=root_46();button_4.__click=[openServer,$$props];append($$anchor2,button_4)};alternate_1=$$anchor2=>{var node_3,consequent_3,fragment=root_55(),button_5=first_child(fragment);button_5.__click=closeServer;node_3=sibling(button_5,2);consequent_3=$$anchor3=>{var fragment_1=comment(),node_4=first_child(fragment_1),consequent_2=$$anchor4=>{var button_6=root_73();button_6.__click=[stopBroadcasting,$$props];append($$anchor4,button_6)},alternate_2=$$anchor4=>{var button_7=root_85();button_7.__click=[startBroadcasting,$$props];append($$anchor4,button_7)};if_block(node_4,($$render=>{var _a9;(null==(_a9=get(replicatorInfo))?void 0:_a9.isBroadcasting)?$$render(consequent_2):$$render(alternate_2,!1)}));append($$anchor3,fragment_1)};if_block(node_3,($$render=>{var _a9;void 0!==(null==(_a9=get(replicatorInfo))?void 0:_a9.isBroadcasting)&&$$render(consequent_3)}));next(2);append($$anchor2,fragment)};if_block(node_2,($$render=>{get(isConnected)?$$render(alternate_1,!1):$$render(consequent_1)}));reset(div_2);reset(div);div_3=sibling(div,2);table_1=sibling(child(div_3),2);each(tbody_1=sibling(child(table_1)),21,(()=>get(peers)),index,(($$anchor2,peer)=>{(function PeerStatusRow($$anchor,$$props){function select(d4,cond,def){return d4 in cond?cond[d4]:def}function makeDecision(isAccepted3,isTemporary){var _a8,_b4;null===(_b4=null===(_a8=cmdReplicator._replicatorInstance)||void 0===_a8?void 0:_a8.server)||void 0===_b4||_b4.makeDecision({peerId:get(peer).peerId,name:get(peer).name,decision:isAccepted3,isTemporary})}function revokeDecision(){var _a8,_b4;null===(_b4=null===(_a8=cmdReplicator._replicatorInstance)||void 0===_a8?void 0:_a8.server)||void 0===_b4||_b4.revokeDecision({peerId:get(peer).peerId,name:get(peer).name})}var tr,td3,div,div_1,span,text2,div_2,span_1,text_1,div_3,div_4,span_2,text_2,node,consequent,div_6,td_1,div_7,div_8,node_1,consequent_3,alternate,td_2,node_4,consequent_5;push($$props,!0);append_styles($$anchor,$$css8);let peer=user_derived((()=>$$props.peerStatus)),statusChips=user_derived((()=>[get(peer).isWatching?["WATCHING"]:[],get(peer).isFetching?["FETCHING"]:[],get(peer).isSending?["SENDING"]:[]].flat())),acceptedStatusChip=user_derived((()=>select(get(peer).accepted.toString(),{["Accepted"]:"ACCEPTED",["Accepted in session"]:"ACCEPTED (in session)",["Denied in session"]:"DENIED (in session)",["Denied"]:"DENIED",["Unknown"]:"NEW"},"")));const classList={["SENDING"]:"connected",["FETCHING"]:"connected",["WATCHING"]:"connected-live",["WAITING"]:"waiting",["ACCEPTED"]:"accepted",["DENIED"]:"denied",["NEW"]:"unknown"};let isAccepted2=user_derived((()=>"Accepted"===get(peer).accepted||"Accepted in session"===get(peer).accepted)),isDenied=user_derived((()=>"Denied"===get(peer).accepted||"Denied in session"===get(peer).accepted)),isNew=user_derived((()=>"Unknown"===get(peer).accepted));const cmdReplicator=function getContext(key2){return get_or_init_context_map("getContext").get(key2)}("getReplicator")(),replicator=cmdReplicator._replicatorInstance,peerAttrLabels=user_derived((()=>{const attrs=[];get(peer).syncOnConnect&&attrs.push("✔ SYNC");get(peer).watchOnConnect&&attrs.push("✔ WATCH");get(peer).syncOnReplicationCommand&&attrs.push("✔ SELECT");return attrs}));td3=child(tr=root7());div=child(td3);div_1=child(div);span=child(div_1);text2=child(span,!0);reset(span);reset(div_1);span_1=child(div_2=sibling(div_1,2));text_1=child(span_1);reset(span_1);reset(div_2);reset(div);div_4=child(div_3=sibling(div,2));span_2=child(div_4);text_2=child(span_2,!0);reset(span_2);reset(div_4);node=sibling(div_4,2);consequent=$$anchor2=>{var div_5=root_113();each(div_5,21,(()=>get(statusChips)),index,(($$anchor3,chip)=>{var span_3=root_25(),text_3=child(span_3,!0);reset(span_3);template_effect(($0=>{set_class(span_3,1,`chip ${null!=$0?$0:""}`,"svelte-d7sijc");set_text(text_3,get(chip))}),[()=>select(get(chip),classList)]);append($$anchor3,span_3)}));reset(div_5);append($$anchor2,div_5)};if_block(node,($$render=>{get(isAccepted2)&&$$render(consequent)}));each(div_6=sibling(node,2),21,(()=>get(peerAttrLabels)),index,(($$anchor2,attr2)=>{var span_4=root_34(),text_4=child(span_4,!0);reset(span_4);template_effect((()=>set_text(text_4,get(attr2))));append($$anchor2,span_4)}));reset(div_6);reset(div_3);reset(td3);div_7=child(td_1=sibling(td3));div_8=child(div_7);node_1=child(div_8);consequent_3=$$anchor2=>{var node_3,consequent_2,fragment=root_45(),node_2=first_child(fragment),consequent_1=$$anchor3=>{var fragment_1=root_54(),button=first_child(fragment_1);button.__click=[on_click2,makeDecision];sibling(button,2).__click=[on_click_1,makeDecision];append($$anchor3,fragment_1)};if_block(node_2,($$render=>{get(isAccepted2)||$$render(consequent_1)}));node_3=sibling(node_2,2);consequent_2=$$anchor3=>{var fragment_2=root_65(),button_2=first_child(fragment_2);button_2.__click=[on_click_2,makeDecision];sibling(button_2,2).__click=[on_click_3,makeDecision];append($$anchor3,fragment_2)};if_block(node_3,($$render=>{get(isDenied)||$$render(consequent_2)}));append($$anchor2,fragment)};alternate=$$anchor2=>{var button_4=root_72();button_4.__click=[on_click_4,revokeDecision];append($$anchor2,button_4)};if_block(node_1,($$render=>{get(isNew)?$$render(consequent_3):$$render(alternate,!1)}));reset(div_8);reset(div_7);reset(td_1);node_4=child(td_2=sibling(td_1));consequent_5=$$anchor2=>{var node_5,consequent_4,alternate_1,div_9=root_84(),div_10=child(div_9),button_5=child(div_10);button_5.__click=[sync2,replicator,peer];node_5=sibling(button_5,2);consequent_4=$$anchor3=>{var button_6=root_94();button_6.__click=[stopWatching,replicator,peer];append($$anchor3,button_6)};alternate_1=$$anchor3=>{var button_7=root_103();button_7.__click=[startWatching,replicator,peer];append($$anchor3,button_7)};if_block(node_5,($$render=>{get(peer).isWatching?$$render(consequent_4):$$render(alternate_1,!1)}));sibling(node_5,2).__click=[moreMenu,peer];reset(div_10);reset(div_9);template_effect((()=>button_5.disabled=get(peer).isSending||get(peer).isFetching));append($$anchor2,div_9)};if_block(node_4,($$render=>{get(isAccepted2)&&$$render(consequent_5)}));reset(td_2);reset(tr);template_effect(($0=>{var _a8;set_text(text2,get(peer).name);set_text(text_1,`(${null!=(_a8=get(peer).peerId)?_a8:""})`);set_class(span_2,1,`chip ${null!=$0?$0:""}`,"svelte-d7sijc");set_text(text_2,get(acceptedStatusChip))}),[()=>select(get(acceptedStatusChip),classList)]);append($$anchor,tr);pop()})($$anchor2,{get peerStatus(){return get(peer)}})}));reset(tbody_1);reset(table_1);reset(div_3);reset(article);template_effect((($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2);set_text(text_4,get(eRelay));set_class(label,1,clsx2({"is-dirty":get(isP2PEnabledModified)}),"svelte-1i6qkqk");set_class(label_1,1,clsx2({"is-dirty":get(isRelayModified)}),"svelte-1i6qkqk");set_class(label_2,1,clsx2({"is-dirty":get(isRoomIdModified)}),"svelte-1i6qkqk");set_class(label_3,1,clsx2({"is-dirty":get(isPasswordModified)}),"svelte-1i6qkqk");set_class(label_4,1,clsx2({"is-dirty":get(isDeviceNameModified)}),"svelte-1i6qkqk");set_class(label_5,1,clsx2({"is-dirty":get(isAutoStartModified)}),"svelte-1i6qkqk");set_class(label_6,1,clsx2({"is-dirty":get(isAutoBroadcastModified)}),"svelte-1i6qkqk");button_2.disabled=!get(isAnyModified);button_3.disabled=!get(isAnyModified)}),[()=>$msg("P2P.Note.Summary"),()=>$msg("P2P.Note.important_note"),()=>$msg("P2P.Note.important_note_sub")]);bind_property("open","toggle",details,($$value=>set(isNoticeOpened,$$value)),(()=>get(isNoticeOpened)));bind_checked(input,(()=>get(eP2PEnabled)),($$value=>set(eP2PEnabled,$$value)));bind_value(input_1,(()=>get(eRelay)),($$value=>set(eRelay,$$value)));bind_value(input_2,(()=>get(eRoomId)),($$value=>set(eRoomId,$$value)));bind_value(input_3,(()=>get(ePassword)),($$value=>set(ePassword,$$value)));bind_value(input_4,(()=>get(eDeviceName)),($$value=>set(eDeviceName,$$value)));bind_checked(input_5,(()=>get(eAutoStart)),($$value=>set(eAutoStart,$$value)));bind_checked(input_6,(()=>get(eAutoBroadcast)),($$value=>set(eAutoBroadcast,$$value)));bind_property("open","toggle",details_1,($$value=>set(isSettingOpened,$$value)),(()=>get(isSettingOpened)));append($$anchor,article);pop()}function getPlatformName(){return import_obsidian17.Platform.isAndroidApp?"android-app":import_obsidian17.Platform.isIosApp?"ios":import_obsidian17.Platform.isMacOS?"macos":import_obsidian17.Platform.isMobileApp?"mobile-app":import_obsidian17.Platform.isMobile?"mobile":import_obsidian17.Platform.isSafari?"safari":import_obsidian17.Platform.isDesktop?"desktop":import_obsidian17.Platform.isDesktopApp?"desktop-app":"unknown-obsidian"}function throwShouldBeOverridden(){throw new Error("This function should be overridden by the module.")}var LOG_LEVEL_VERBOSE,LOG_LEVEL_INFO,LOG_LEVEL_NOTICE,LEVEL_INFO,defaultLoggerEnv_minLogLevel,_logger,RESULT_TIMED_OUT,CANCELLED,AUTO_MERGED,NOT_CONFLICTED,MISSING_OR_ERROR,LEAVE_TO_SUBSEQUENT,MILESTONE_DOCID,MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY,REMOTE_COUCHDB,REMOTE_MINIO,REMOTE_P2P,AutoAccepting,P2P_DEFAULT_SETTINGS,ChunkAlgorithmNames,ChunkAlgorithms_V1,ChunkAlgorithms_V2,ChunkAlgorithms_V2Segmenter,ChunkAlgorithms_RabinKarp,DEFAULT_SETTINGS,KeyIndexOfSettings,PREFERRED_BASE,PREFERRED_SETTING_CLOUDANT,PREFERRED_SETTING_SELF_HOSTED,PREFERRED_JOURNAL_SYNC,TweakValuesShouldMatchedTemplate,IncompatibleChanges,CompatibleButLossyChanges,IncompatibleChangesInSpecificPattern,TweakValuesDefault,configurationNames,LEVEL_ADVANCED,LEVEL_POWER_USER,LEVEL_EDGE_CASE,TweakValuesTemplate,DEVICE_ID_PREFERRED,PREFIXMD_LOGFILE,PREFIXMD_LOGFILE_UC,FLAGMD_REDFLAG,FLAGMD_REDFLAG2,FLAGMD_REDFLAG2_HR,FLAGMD_REDFLAG3,FLAGMD_REDFLAG3_HR,SYNCINFO_ID,PREFIX_OBFUSCATED,PREFIX_ENCRYPTED_CHUNK,import_obsidian,import_obsidian2,import_diff_match_patch,normalizePath,PSCHeader,ICHeader,ICHeaderLength,ICXHeader,configURIBase,LRUCache,balanced,maybeMatch,range,escSlash,escOpen,escClose,escComma,escPeriod,escSlashPattern,escOpenPattern,escClosePattern,escCommaPattern,escPeriodPattern,slashPattern,openPattern,closePattern,commaPattern,periodPattern,assertValidPattern,posixClasses,braceEscape,regexpEscape,rangesToString,parseClass,unescape2,_root,_hasMagic,_uflag,_parts,_parent,_parentIndex,_negs,_filledNegs,_options,_toString,_emptyExt,_AST_instances,fillNegs_fn,_AST_static,parseAST_fn,partsToRegExp_fn,parseGlob_fn,types,isExtglobType,addPatternStart,justDots,reSpecials,regExpEscape,_AST,AST,escape,minimatch,starDotExtRE,starDotExtTest,starDotExtTestDot,starDotExtTestNocase,starDotExtTestNocaseDot,starDotStarRE,starDotStarTest,starDotStarTestDot,dotStarRE,dotStarTest,starRE,starTest,starTestDot,qmarksRE,qmarksTestNocase,qmarksTestNocaseDot,qmarksTestDot,qmarksTest,qmarksTestNoExt,qmarksTestNoExtDot,defaultPlatform,path_posix,sep,GLOBSTAR,filter,ext,defaults,braceExpand,makeRe,match,globMagic,regExpEscape2,Minimatch,webcrypto,encodeChunkSize,QUANTUM,te,td,regexpBase64,table,revTable,revMap,numMap,_hashString,matchOpts,delay,UNRESOLVED,promiseWithResolver,noop,currentYieldingAnimationFrame,TIMED_OUT_SIGNAL,webcrypto2,SALT,previousPassphrase,encryptionKey,_nonceV3,bufV3,previousDecryptionPassphrase,decryptionKey,KeyBuffs,decKeyBuffs,KEY_RECYCLE_COUNT,semiStaticFieldBuffer,nonceBuffer,webcrypto3,keyGCCount,decKeyIdx,decKeyMin,_a,FallbackWeakRef,EventHub,InterceptiveEventTarget,WrappedEvent,eventHub,APIBase,tasks,maxConcurrency,roundRobinIdx,workers,key,serializedMap,queueCount,waitingProcessMap,shareSerializedMap,skipDuplicatedMap,PaceMaker,NOT_AVAILABLE,READY_PICK_SIGNAL,READY_POST_SIGNAL,DISPOSE_ERROR,SyncInbox,Inbox,InboxWithEvent,ClerkState,SENTINEL_FINISHED,SENTINEL_FLUSH,ClerkBase,Clerk,ClerkGroup,Porter,Notifier,allRunningProcessors,QueueProcessor,ch2,wk,u8,u16,i32,fleb,fdeb,clim,freb,_a2,fl,revfl,_b,fd,revfd,rev,hMap,flt,fdt,flm,flrm,fdm,fdrm,max,bits,bits16,shft,slc,ec,err,inflt,wbits,wbits16,hTree,ln,lc,clen,wfblk,wblk,deo,et,dflt,dopt,mrg,wcln,ch,cbfs,wrkr,bInflt,bDflt,pbf,gopt,cbify,fltn,td2,x2,i2,encrypt2,decrypt2,isValidRemoteCouchDBURI,checkRemoteVersion,bumpRemoteVersion,checkSyncInfo,wrappedInflate,wrappedDeflate,replicationFilter,EDEN_ENCRYPTED_KEY,preprocessOutgoing,enableEncryption,_requestToCouchDBFetch,SYMBOL_A,SYMBOL_B,globalSlipBoard,throttle,_a3,isIndexDBCmpExist,globalConcurrencyController,map,revMap2,previousValues,MARK_DELETED,MARK_ISARRAY,MARK_SWAPPED,CustomRegExp,t,epochFNV1a,c1,c2,r1,r2,m,n,hashFunc,charNewLine,segmenter,MAX_ITEMS,globalSlipBoard2,BatchReader,ChunkCollector,import_diff_match_patch2,chunkSplittersMainThread,chunkSplittersWorker,LiveSyncLocalDB,LiveSyncAbstractReplicator,instanceOfAny,idbProxyableTypes,cursorAdvanceMethods,transactionDoneMap,transformCache,reverseTransformCache,idbProxyTraps,unwrap,readMethods,writeMethods,cachedMethods,advanceMethodProps,methodMap,advanceResults,ittrProxiedCursorToOriginalProxy,cursorIteratorTraps,databaseCache,OpenKeyValueDatabase,tasks2,intervals,waitingItems,PersistentMap,sameChangePairs,EVENT_LAYOUT_READY,EVENT_REQUEST_OPEN_SETUP_URI2,EVENT_REQUEST_COPY_SETUP_URI2,EVENT_REQUEST_SHOW_SETUP_QR,EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2,EVENT_REQUEST_RUN_DOCTOR,SHOULD_READ_NEW,NOT_USED,Refiner,BasicHeaderGenerator,JWTTokenGenerator,AuthorizationHeaderGenerator,memos,PeriodicProcessor,_requestToCouchDB,BASE_IS_NEW,TARGET_IS_NEW,EVEN,resolution,_cached,waitingTasks,prefixMapObject,decodePrefixMapObject,prefixMapNumber,decodePrefixMapNumber,decodeMapConstant,context,topologicalSortCache,_reactiveSourceId,collectingChunks,pluginScanningCount,hiddenFilesProcessingCount,hiddenFilesEventCount,logStore,logMessages,AbstractModule,AbstractObsidianModule,_a4,_b2,_c,EACH_ITEM_REACTIVE,EACH_INDEX_REACTIVE,EACH_IS_CONTROLLED,EACH_IS_ANIMATED,EACH_ITEM_IMMUTABLE,PROPS_IS_IMMUTABLE,PROPS_IS_RUNES,PROPS_IS_UPDATED,PROPS_IS_BINDABLE,PROPS_IS_LAZY_INITIAL,TEMPLATE_FRAGMENT,TEMPLATE_USE_IMPORT_NODE,HYDRATION_START,HYDRATION_START_ELSE,HYDRATION_END,HYDRATION_ERROR,UNINITIALIZED,FILENAME,NAMESPACE_HTML,_a5,_b3,node_env,dev_fallback_default,is_array,index_of,array_from,define_property,get_descriptor,get_descriptors,object_prototype,array_prototype,get_prototype_of,is_extensible,noop2,DERIVED,EFFECT,RENDER_EFFECT,BLOCK_EFFECT,BRANCH_EFFECT,ROOT_EFFECT,BOUNDARY_EFFECT,UNOWNED,DISCONNECTED,CLEAN,DIRTY,MAYBE_DIRTY,INERT,DESTROYED,EFFECT_RAN,EFFECT_TRANSPARENT,LEGACY_DERIVED_PROP,INSPECT_EFFECT,HEAD_EFFECT,EFFECT_HAS_DERIVED,EFFECT_IS_UPDATING,STATE_SYMBOL,LEGACY_PROPS,LOADING_ATTR_SYMBOL,bold,normal,hydrating,hydrate_node,tracing_expressions,legacy_mode_flag,tracing_mode_flag,$window,is_firefox,first_child_getter,next_sibling_getter,stack,request_idle_callback,micro_tasks,idle_tasks,handled_errors,is_throwing_error,is_flushing,last_scheduled_effect,is_updating_effect,is_destroying_effect,queued_root_effects,dev_effect_stack,active_reaction,untracking,active_effect,reaction_sources,new_deps,skipped_deps,untracked_writes,write_version,read_version,skip_reaction,captured_signals,STATUS_MASK,inspect_effects,old_values,component_context,dev_current_component_function,PASSIVE_EVENTS,all_styles,listening_to_form_reset,all_registered_events,root_event_handles,document_listeners,mounted_components,current_each_item,whitespace,IS_CUSTOM_ELEMENT,IS_HTML,setters_cache,pending,_listeners,_observer,_options2,_ResizeObserverSingleton_instances,getObserver_fn,_ResizeObserverSingleton,subscriber_queue,is_store_binding,IS_UNMOUNTED,spread_props_handler,_allMessages,SUPPORTED_I18N_LANGS,expandedMessage,allMessages,currentLang,missingTranslations,__onMissingTranslations,msgCache,on_click,root_1,root,$$css,import_obsidian3,SvelteItemView,LogPaneView,nodeCrypto,_0n,_1n,_2n,_3n,_8n,CURVE,divNearest,endo,groupLen,USE_ENDOMORPHISM,ShaError,JacobianPoint,pointPrecomputes,Point,Signature,hexes,asciis,POW_2_256,_sha256Sync,_hmacSha256Sync,SchnorrSignature,InternalSchnorrSignature,schnorr,crypto2,TAGS,TAGGED_HASH_PREFIXES,utils,alloc,genId,selfId,all,isBrowser,noOp,mkErr,encoder,decoder,encodeBytes,decodeBytes,toHex,topicPath,shuffle,getRelays,toJson,fromJson,strToNum,socketRetryPeriods,makeSocket,socketGetter,strToSha1,pack,unpack,sha12,genKey,encrypt3,decrypt3,peer_default,defaultIceServers,TypedArray,progressIndex,payloadIndex,chunkSize,internalNs,room_default,strategy_default,clients,privateKey,publicKey,subIdToTopic,msgHandlers,kindCache,now2,topicToKind,createEvent,subscribe,unsubscribe,joinRoom,defaultRelayUrls,ResponsePreventedError,DeviceDecisions,StoredMapLike,TrysteroReplicatorP2PClient,EVENT_SERVER_STATUS,EVENT_REQUEST_STATUS,EVENT_P2P_REPLICATOR_STATUS,TrysteroReplicatorP2PServer,p,instance,replicatorInstanceGetter,LiveSyncTrysteroReplicator,CBC_exports,KEY_LENGTH,ALGORITHM_NAME,SALT_PREFIX,SALT_LENGTH,TrysteroReplicator,P2PLogCollector,recentLogs,recentLogProcessor,ModuleLog,noticeIndex,LiveSyncCommands,root_12,root_4,root_6,root_5,root_10,root_2,root2,$$css2,JsonResolveModal,HiddenFileSync,import_diff_match_patch3,ConflictResolveModal,import_obsidian5,root_3,root_62,root_7,root_8,root_42,root_9,root_11,root_122,root_22,root_13,root_132,$$css3,import_obsidian6,root_14,root_23,root_32,root_82,root_63,root_52,root_133,root_15,root_18,root_16,root_112,root_19,root_92,root_43,root_21,root_20,root3,$$css4,PluginDialogModal,d,d2,DUMMY_HEAD,DUMMY_END,pluginList,pluginIsEnumerating,pluginV2Progress,pluginManifests,pluginManifestStore,PluginDataExDisplayV2,ConfigSync,getHttpHandlerExtensionConfiguration,resolveHttpHandlerRuntimeConfig,HttpAuthLocation,HttpApiKeyAuthLocation,EndpointURLScheme,AlgorithmId,FieldPosition,SMITHY_CONTEXT_KEY,IniSectionType,RequestHandlerProtocol,HttpRequest,HttpResponse,addExpectContinueMiddlewareOptions,getAddExpectContinuePlugin,RequestChecksumCalculation,DEFAULT_REQUEST_CHECKSUM_CALCULATION,ResponseChecksumValidation,DEFAULT_RESPONSE_CHECKSUM_VALIDATION,ChecksumAlgorithm,ChecksumLocation,DEFAULT_CHECKSUM_ALGORITHM,SelectorType,getDateHeader,getSkewCorrectedDate,isClockSkewed,getUpdatedSystemClockOffset,throwSigningPropertyError,validateSigningProperties,AwsSdkSigV4Signer,AwsSdkSigV4ASigner,getSmithyContext2,normalizeProvider,resolveAuthOptions,httpAuthSchemeMiddleware,httpAuthSchemeEndpointRuleSetMiddlewareOptions,getHttpAuthSchemeEndpointRuleSetPlugin,deserializerMiddleware,findHeader,serializerMiddleware,deserializerMiddlewareOption,serializerMiddlewareOption,defaultErrorHandler,defaultSuccessHandler,httpSigningMiddleware,httpSigningMiddlewareOptions,getHttpSigningPlugin,normalizeProvider2,alphabetByEncoding,alphabetByValue,bitsPerLetter,bitsPerByte,maxLetterValue,fromBase64,fromUtf8,toUint8Array,toUtf8,Uint8ArrayBlobAdapter,ReadableStreamRef,ChecksumStream,isReadableStream,createChecksumStream,ByteArrayCollector,createBufferedReadable,getAwsChunkedEncodingStream,escapeUri,hexEncode,keepAliveSupport,FetchHttpHandler,streamCollector,SHORT_TO_HEX,HEX_TO_SHORT,sdkStreamMixin,isBlobInstance,collectBody,resolvedPath,RequestBuilder,DefaultIdentityProviderConfig,isIdentityExpired,doesIdentityRequireRefresh,memoizeIdentityProvider,memoize,resolveAwsSdkSigV4AConfig,AMZ_DATE_QUERY_PARAM,AMZ_DATE_HEADER,GENERATED_HEADERS,SIGNATURE_HEADER,TOKEN_HEADER,ALWAYS_UNSIGNABLE_HEADERS,PROXY_HEADER_PATTERN,SEC_HEADER_PATTERN,EVENT_ALGORITHM_IDENTIFIER,signingKeyCache,cacheQueue,createScope,getSigningKey,hmac,getCanonicalHeaders,isArrayBuffer,getPayloadHash,HeaderFormatter,HEADER_VALUE_TYPE,UUID_PATTERN,Int64,hasHeader,moveHeadersToQuery,prepareRequest,getCanonicalQuery,iso8601,toDate,SignatureV4Base,SignatureV4,resolveAwsSdkSigV4Config,getAllAliases,getMiddlewareNameWithAliases,constructStack,stepWeights,priorityWeights,Client,Command,ClassBuilder,SENSITIVE_STRING,createAggregatedClient,parseBoolean,expectNumber,MAX_FLOAT,expectFloat32,expectLong,expectInt32,expectShort,expectByte,expectSizedInt,castInt,expectNonNull,expectObject,expectString,expectUnion,strictParseFloat32,NUMBER_REGEX,parseNumber,strictParseLong,strictParseInt32,strictParseShort,strictParseByte,stackTraceWarning,logger,DAYS,MONTHS,RFC3339_WITH_OFFSET,parseRfc3339DateTimeWithOffset,IMF_FIXDATE,RFC_850_DATE,ASC_TIME,parseRfc7231DateTime,buildDate,parseTwoDigitYear,adjustRfc850Year,parseMonthByShortName,DAYS_IN_MONTH,validateDayOfMonth,isLeapYear,parseDateValue,parseMilliseconds,parseOffsetToMilliseconds,stripLeadingZeroes,ServiceException,decorateServiceException,throwDefaultError,withBaseException,deserializeMetadata,loadConfigsForDefaultMode,getChecksumConfiguration2,resolveChecksumRuntimeConfig2,getRetryConfiguration,resolveRetryRuntimeConfig,getDefaultExtensionConfiguration,resolveDefaultRuntimeConfig2,getArrayIfSingleItem,getValueFromTextNode,isSerializableHeaderValue,LazyJsonString,NoOpLogger,mapWithFilter,applyInstruction,nonNullish,pass,serializeDateTime,collectBodyString,import_fast_xml_parser,parseXmlBody,parseXmlErrorBody,loadRestXmlErrorCode,CLIENT_SUPPORTED_ALGORITHMS,PRIORITY_ORDER_ALGORITHMS,getChecksumAlgorithmForRequest,getChecksumLocationName,hasHeader2,hasHeaderWithPrefix,isStreaming,__assign,fromUtf82,fromUtf83,AwsCrc32c,Crc32c,lookupTable,AwsCrc32,Crc32,lookupTable2,getCrc32ChecksumAlgorithmFunction,selectChecksumAlgorithmFunction,stringHasher,flexibleChecksumsMiddlewareOptions,flexibleChecksumsMiddleware,flexibleChecksumsInputMiddlewareOptions,flexibleChecksumsInputMiddleware,getChecksumAlgorithmListForResponse,isChecksumWithPartNumber,getChecksum,validateChecksumFromResponse,flexibleChecksumsResponseMiddlewareOptions,flexibleChecksumsResponseMiddleware,getFlexibleChecksumsPlugin,resolveFlexibleChecksumsConfig,hostHeaderMiddleware,hostHeaderMiddlewareOptions,getHostHeaderPlugin,loggerMiddlewareOptions,getLoggerPlugin,recursionDetectionMiddleware,addRecursionDetectionMiddlewareOptions,getRecursionDetectionPlugin,checkContentLengthHeaderMiddlewareOptions,getCheckContentLengthHeaderPlugin,regionRedirectEndpointMiddleware,regionRedirectEndpointMiddlewareOptions,regionRedirectMiddlewareOptions,getRegionRedirectMiddlewarePlugin,s3ExpiresMiddleware,s3ExpiresMiddlewareOptions,getS3ExpiresMiddlewarePlugin,_S3ExpressIdentityCache,S3ExpressIdentityCache,S3ExpressIdentityCacheEntry,_S3ExpressIdentityProviderImpl,S3ExpressIdentityProviderImpl,SelectorType2,SESSION_TOKEN_QUERY_PARAM,SESSION_TOKEN_HEADER,SignatureV4S3Express,s3ExpressMiddleware,s3ExpressMiddlewareOptions,getS3ExpressPlugin,signS3Express,defaultErrorHandler2,defaultSuccessHandler2,s3ExpressHttpSigningMiddleware,getS3ExpressHttpSigningPlugin,resolveS3Config,THROW_IF_EMPTY_BODY,throw200ExceptionsMiddleware,collectBody2,throw200ExceptionsMiddlewareOptions,getThrow200ExceptionsPlugin,validate,bucketEndpointMiddlewareOptions,validateBucketNameMiddlewareOptions,getValidateBucketNamePlugin,EndpointCache,IP_V4_REGEX,isIpAddress,VALID_HOST_LABEL_REGEX,isValidHostLabel,customEndpointFunctions,EndpointError,booleanEquals,getAttrPathList,getAttr,isSet,not,DEFAULT_PORTS,endpointFunctions,evaluateTemplate,getReferenceValue,evaluateExpression,callFunction,evaluateCondition,evaluateConditions,getEndpointHeaders,getEndpointProperty,getEndpointProperties,getEndpointUrl,evaluateEndpointRule,evaluateErrorRule,evaluateTreeRule,evaluateRules,resolveEndpoint,isVirtualHostableS3Bucket,selectedPartitionsInfo,awsEndpointFunctions,ACCOUNT_ID_ENDPOINT_REGEX,UA_NAME_ESCAPE_REGEX,UA_VALUE_ESCAPE_REGEX,userAgentMiddleware,escapeUserAgent,getUserAgentMiddlewareOptions,getUserAgentPlugin,isFipsRegion,getRealRegion,resolveRegionConfig,resolveEventStreamSerdeConfig,CONTENT_LENGTH_HEADER2,contentLengthMiddlewareOptions,getContentLengthPlugin,resolveParamsForS3,DOMAIN_PATTERN,IP_ADDRESS_PATTERN,DOTS_PATTERN,isDnsCompatibleBucketName,isArnBucketName,createConfigValueProvider,getEndpointFromConfig,parseUrl,toEndpointV1,getEndpointFromInstructions,resolveParams,endpointMiddleware,endpointMiddlewareOptions,getEndpointPlugin,resolveEndpointConfig,RETRY_MODES,DEFAULT_RETRY_MODE,CLOCK_SKEW_ERROR_CODES,THROTTLING_ERROR_CODES,TRANSIENT_ERROR_CODES,TRANSIENT_ERROR_STATUS_CODES,NODEJS_TIMEOUT_ERROR_CODES,isClockSkewCorrectedError,isBrowserNetworkError,isThrottlingError,isTransientError,isServerError,DefaultRateLimiter,getDefaultRetryBackoffStrategy,createDefaultRetryToken,StandardRetryStrategy,AdaptiveRetryStrategy,ConfiguredRetryStrategy,getRandomValues,rnds8,byteToHex,randomUUID,native_default,v4_default,asSdkError,resolveRetryConfig,isStreamingPayload,retryMiddleware,isRetryStrategyV2,getRetryErrorInfo,getRetryErrorType,retryMiddlewareOptions,getRetryPlugin,getRetryAfterHint,SignatureV4MultiRegion,cp,cq,cr,cs,ct,cu,cv,cw,cx,cy,cz,cA,cB,cC,cD,cE,cF,c,d3,e2,f,g,h,i,j,k,l,m2,n2,o,p2,q,r3,s,t2,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,aA,aB,aC,aD,aE,aF,aG,aH,aI,aJ,aK,aL,aM,aN,aO,aP,aQ,aR,aS,aT,aU,aV,aW,aX,aY,aZ,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz,bA,bB,bC,bD,bE,bF,bG,bH,bI,bJ,bK,bL,bM,bN,bO,bP,bQ,bR,bS,bT,bU,bV,bW,bX,bY,bZ,ca,cb,cc,cd,ce,cf,cg,ch3,ci,cj,ck,cl,cm,cn,co,ruleSet,cache,defaultEndpointResolver,defaultS3HttpAuthSchemeParametersProvider,defaultS3HttpAuthSchemeProvider,resolveHttpAuthSchemeConfig,resolveClientEndpointParameters,commonParams,S3ServiceException,NoSuchUpload,ObjectNotInActiveTierError,BucketAlreadyExists,BucketAlreadyOwnedByYou,NoSuchBucket,AnalyticsFilter,MetricsFilter,InvalidObjectState,NoSuchKey,NotFound,CompleteMultipartUploadOutputFilterSensitiveLog,CompleteMultipartUploadRequestFilterSensitiveLog,CopyObjectOutputFilterSensitiveLog,CopyObjectRequestFilterSensitiveLog,CreateMultipartUploadOutputFilterSensitiveLog,CreateMultipartUploadRequestFilterSensitiveLog,SessionCredentialsFilterSensitiveLog,CreateSessionOutputFilterSensitiveLog,CreateSessionRequestFilterSensitiveLog,ServerSideEncryptionByDefaultFilterSensitiveLog,ServerSideEncryptionRuleFilterSensitiveLog,ServerSideEncryptionConfigurationFilterSensitiveLog,GetBucketEncryptionOutputFilterSensitiveLog,SSEKMSFilterSensitiveLog,InventoryEncryptionFilterSensitiveLog,InventoryS3BucketDestinationFilterSensitiveLog,InventoryDestinationFilterSensitiveLog,InventoryConfigurationFilterSensitiveLog,GetBucketInventoryConfigurationOutputFilterSensitiveLog,GetObjectOutputFilterSensitiveLog,GetObjectRequestFilterSensitiveLog,GetObjectAttributesRequestFilterSensitiveLog,GetObjectTorrentOutputFilterSensitiveLog,HeadObjectOutputFilterSensitiveLog,HeadObjectRequestFilterSensitiveLog,ListBucketInventoryConfigurationsOutputFilterSensitiveLog,ListPartsRequestFilterSensitiveLog,XmlText,XmlNode,EncryptionTypeMismatch,InvalidRequest,InvalidWriteOffset,TooManyParts,ObjectAlreadyInActiveTierError,SelectObjectContentEventStream,PutBucketEncryptionRequestFilterSensitiveLog,PutBucketInventoryConfigurationRequestFilterSensitiveLog,PutObjectOutputFilterSensitiveLog,PutObjectRequestFilterSensitiveLog,EncryptionFilterSensitiveLog,S3LocationFilterSensitiveLog,OutputLocationFilterSensitiveLog,RestoreRequestFilterSensitiveLog,RestoreObjectRequestFilterSensitiveLog,SelectObjectContentOutputFilterSensitiveLog,SelectObjectContentRequestFilterSensitiveLog,UploadPartOutputFilterSensitiveLog,UploadPartRequestFilterSensitiveLog,UploadPartCopyOutputFilterSensitiveLog,UploadPartCopyRequestFilterSensitiveLog,WriteGetObjectResponseRequestFilterSensitiveLog,se_AbortMultipartUploadCommand,se_CompleteMultipartUploadCommand,se_CopyObjectCommand,se_CreateBucketCommand,se_CreateBucketMetadataTableConfigurationCommand,se_CreateMultipartUploadCommand,se_CreateSessionCommand,se_DeleteBucketCommand,se_DeleteBucketAnalyticsConfigurationCommand,se_DeleteBucketCorsCommand,se_DeleteBucketEncryptionCommand,se_DeleteBucketIntelligentTieringConfigurationCommand,se_DeleteBucketInventoryConfigurationCommand,se_DeleteBucketLifecycleCommand,se_DeleteBucketMetadataTableConfigurationCommand,se_DeleteBucketMetricsConfigurationCommand,se_DeleteBucketOwnershipControlsCommand,se_DeleteBucketPolicyCommand,se_DeleteBucketReplicationCommand,se_DeleteBucketTaggingCommand,se_DeleteBucketWebsiteCommand,se_DeleteObjectCommand,se_DeleteObjectsCommand,se_DeleteObjectTaggingCommand,se_DeletePublicAccessBlockCommand,se_GetBucketAccelerateConfigurationCommand,se_GetBucketAclCommand,se_GetBucketAnalyticsConfigurationCommand,se_GetBucketCorsCommand,se_GetBucketEncryptionCommand,se_GetBucketIntelligentTieringConfigurationCommand,se_GetBucketInventoryConfigurationCommand,se_GetBucketLifecycleConfigurationCommand,se_GetBucketLocationCommand,se_GetBucketLoggingCommand,se_GetBucketMetadataTableConfigurationCommand,se_GetBucketMetricsConfigurationCommand,se_GetBucketNotificationConfigurationCommand,se_GetBucketOwnershipControlsCommand,se_GetBucketPolicyCommand,se_GetBucketPolicyStatusCommand,se_GetBucketReplicationCommand,se_GetBucketRequestPaymentCommand,se_GetBucketTaggingCommand,se_GetBucketVersioningCommand,se_GetBucketWebsiteCommand,se_GetObjectCommand,se_GetObjectAclCommand,se_GetObjectAttributesCommand,se_GetObjectLegalHoldCommand,se_GetObjectLockConfigurationCommand,se_GetObjectRetentionCommand,se_GetObjectTaggingCommand,se_GetObjectTorrentCommand,se_GetPublicAccessBlockCommand,se_HeadBucketCommand,se_HeadObjectCommand,se_ListBucketAnalyticsConfigurationsCommand,se_ListBucketIntelligentTieringConfigurationsCommand,se_ListBucketInventoryConfigurationsCommand,se_ListBucketMetricsConfigurationsCommand,se_ListBucketsCommand,se_ListDirectoryBucketsCommand,se_ListMultipartUploadsCommand,se_ListObjectsCommand,se_ListObjectsV2Command,se_ListObjectVersionsCommand,se_ListPartsCommand,se_PutBucketAccelerateConfigurationCommand,se_PutBucketAclCommand,se_PutBucketAnalyticsConfigurationCommand,se_PutBucketCorsCommand,se_PutBucketEncryptionCommand,se_PutBucketIntelligentTieringConfigurationCommand,se_PutBucketInventoryConfigurationCommand,se_PutBucketLifecycleConfigurationCommand,se_PutBucketLoggingCommand,se_PutBucketMetricsConfigurationCommand,se_PutBucketNotificationConfigurationCommand,se_PutBucketOwnershipControlsCommand,se_PutBucketPolicyCommand,se_PutBucketReplicationCommand,se_PutBucketRequestPaymentCommand,se_PutBucketTaggingCommand,se_PutBucketVersioningCommand,se_PutBucketWebsiteCommand,se_PutObjectCommand,se_PutObjectAclCommand,se_PutObjectLegalHoldCommand,se_PutObjectLockConfigurationCommand,se_PutObjectRetentionCommand,se_PutObjectTaggingCommand,se_PutPublicAccessBlockCommand,se_RestoreObjectCommand,se_SelectObjectContentCommand,se_UploadPartCommand,se_UploadPartCopyCommand,se_WriteGetObjectResponseCommand,de_AbortMultipartUploadCommand,de_CompleteMultipartUploadCommand,de_CopyObjectCommand,de_CreateBucketCommand,de_CreateBucketMetadataTableConfigurationCommand,de_CreateMultipartUploadCommand,de_CreateSessionCommand,de_DeleteBucketCommand,de_DeleteBucketAnalyticsConfigurationCommand,de_DeleteBucketCorsCommand,de_DeleteBucketEncryptionCommand,de_DeleteBucketIntelligentTieringConfigurationCommand,de_DeleteBucketInventoryConfigurationCommand,de_DeleteBucketLifecycleCommand,de_DeleteBucketMetadataTableConfigurationCommand,de_DeleteBucketMetricsConfigurationCommand,de_DeleteBucketOwnershipControlsCommand,de_DeleteBucketPolicyCommand,de_DeleteBucketReplicationCommand,de_DeleteBucketTaggingCommand,de_DeleteBucketWebsiteCommand,de_DeleteObjectCommand,de_DeleteObjectsCommand,de_DeleteObjectTaggingCommand,de_DeletePublicAccessBlockCommand,de_GetBucketAccelerateConfigurationCommand,de_GetBucketAclCommand,de_GetBucketAnalyticsConfigurationCommand,de_GetBucketCorsCommand,de_GetBucketEncryptionCommand,de_GetBucketIntelligentTieringConfigurationCommand,de_GetBucketInventoryConfigurationCommand,de_GetBucketLifecycleConfigurationCommand,de_GetBucketLocationCommand,de_GetBucketLoggingCommand,de_GetBucketMetadataTableConfigurationCommand,de_GetBucketMetricsConfigurationCommand,de_GetBucketNotificationConfigurationCommand,de_GetBucketOwnershipControlsCommand,de_GetBucketPolicyCommand,de_GetBucketPolicyStatusCommand,de_GetBucketReplicationCommand,de_GetBucketRequestPaymentCommand,de_GetBucketTaggingCommand,de_GetBucketVersioningCommand,de_GetBucketWebsiteCommand,de_GetObjectCommand,de_GetObjectAclCommand,de_GetObjectAttributesCommand,de_GetObjectLegalHoldCommand,de_GetObjectLockConfigurationCommand,de_GetObjectRetentionCommand,de_GetObjectTaggingCommand,de_GetObjectTorrentCommand,de_GetPublicAccessBlockCommand,de_HeadBucketCommand,de_HeadObjectCommand,de_ListBucketAnalyticsConfigurationsCommand,de_ListBucketIntelligentTieringConfigurationsCommand,de_ListBucketInventoryConfigurationsCommand,de_ListBucketMetricsConfigurationsCommand,de_ListBucketsCommand,de_ListDirectoryBucketsCommand,de_ListMultipartUploadsCommand,de_ListObjectsCommand,de_ListObjectsV2Command,de_ListObjectVersionsCommand,de_ListPartsCommand,de_PutBucketAccelerateConfigurationCommand,de_PutBucketAclCommand,de_PutBucketAnalyticsConfigurationCommand,de_PutBucketCorsCommand,de_PutBucketEncryptionCommand,de_PutBucketIntelligentTieringConfigurationCommand,de_PutBucketInventoryConfigurationCommand,de_PutBucketLifecycleConfigurationCommand,de_PutBucketLoggingCommand,de_PutBucketMetricsConfigurationCommand,de_PutBucketNotificationConfigurationCommand,de_PutBucketOwnershipControlsCommand,de_PutBucketPolicyCommand,de_PutBucketReplicationCommand,de_PutBucketRequestPaymentCommand,de_PutBucketTaggingCommand,de_PutBucketVersioningCommand,de_PutBucketWebsiteCommand,de_PutObjectCommand,de_PutObjectAclCommand,de_PutObjectLegalHoldCommand,de_PutObjectLockConfigurationCommand,de_PutObjectRetentionCommand,de_PutObjectTaggingCommand,de_PutPublicAccessBlockCommand,de_RestoreObjectCommand,de_SelectObjectContentCommand,de_UploadPartCommand,de_UploadPartCopyCommand,de_WriteGetObjectResponseCommand,de_CommandError,throwDefaultError2,de_BucketAlreadyExistsRes,de_BucketAlreadyOwnedByYouRes,de_EncryptionTypeMismatchRes,de_InvalidObjectStateRes,de_InvalidRequestRes,de_InvalidWriteOffsetRes,de_NoSuchBucketRes,de_NoSuchKeyRes,de_NoSuchUploadRes,de_NotFoundRes,de_ObjectAlreadyInActiveTierErrorRes,de_ObjectNotInActiveTierErrorRes,de_TooManyPartsRes,de_SelectObjectContentEventStream,de_ContinuationEvent_event,de_EndEvent_event,de_ProgressEvent_event,de_RecordsEvent_event,de_StatsEvent_event,se_AbortIncompleteMultipartUpload,se_AccelerateConfiguration,se_AccessControlPolicy,se_AccessControlTranslation,se_AllowedHeaders,se_AllowedMethods,se_AllowedOrigins,se_AnalyticsAndOperator,se_AnalyticsConfiguration,se_AnalyticsExportDestination,se_AnalyticsFilter,se_AnalyticsS3BucketDestination,se_BucketInfo,se_BucketLifecycleConfiguration,se_BucketLoggingStatus,se_CompletedMultipartUpload,se_CompletedPart,se_CompletedPartList,se_Condition,se_CORSConfiguration,se_CORSRule,se_CORSRules,se_CreateBucketConfiguration,se_CSVInput,se_CSVOutput,se_DefaultRetention,se_Delete,se_DeleteMarkerReplication,se_Destination,se_Encryption,se_EncryptionConfiguration,se_ErrorDocument,se_EventBridgeConfiguration,se_EventList,se_ExistingObjectReplication,se_ExposeHeaders,se_FilterRule,se_FilterRuleList,se_GlacierJobParameters,se_Grant,se_Grantee,se_Grants,se_IndexDocument,se_InputSerialization,se_IntelligentTieringAndOperator,se_IntelligentTieringConfiguration,se_IntelligentTieringFilter,se_InventoryConfiguration,se_InventoryDestination,se_InventoryEncryption,se_InventoryFilter,se_InventoryOptionalFields,se_InventoryS3BucketDestination,se_InventorySchedule,se_JSONInput,se_JSONOutput,se_LambdaFunctionConfiguration,se_LambdaFunctionConfigurationList,se_LifecycleExpiration,se_LifecycleRule,se_LifecycleRuleAndOperator,se_LifecycleRuleFilter,se_LifecycleRules,se_LocationInfo,se_LoggingEnabled,se_MetadataEntry,se_MetadataTableConfiguration,se_Metrics,se_MetricsAndOperator,se_MetricsConfiguration,se_MetricsFilter,se_NoncurrentVersionExpiration,se_NoncurrentVersionTransition,se_NoncurrentVersionTransitionList,se_NotificationConfiguration,se_NotificationConfigurationFilter,se_ObjectIdentifier,se_ObjectIdentifierList,se_ObjectLockConfiguration,se_ObjectLockLegalHold,se_ObjectLockRetention,se_ObjectLockRule,se_OutputLocation,se_OutputSerialization,se_Owner,se_OwnershipControls,se_OwnershipControlsRule,se_OwnershipControlsRules,se_ParquetInput,se_PartitionedPrefix,se_PublicAccessBlockConfiguration,se_QueueConfiguration,se_QueueConfigurationList,se_Redirect,se_RedirectAllRequestsTo,se_ReplicaModifications,se_ReplicationConfiguration,se_ReplicationRule,se_ReplicationRuleAndOperator,se_ReplicationRuleFilter,se_ReplicationRules,se_ReplicationTime,se_ReplicationTimeValue,se_RequestPaymentConfiguration,se_RequestProgress,se_RestoreRequest,se_RoutingRule,se_RoutingRules,se_S3KeyFilter,se_S3Location,se_S3TablesDestination,se_ScanRange,se_SelectParameters,se_ServerSideEncryptionByDefault,se_ServerSideEncryptionConfiguration,se_ServerSideEncryptionRule,se_ServerSideEncryptionRules,se_SimplePrefix,se_SourceSelectionCriteria,se_SSEKMS,se_SseKmsEncryptedObjects,se_SSES3,se_StorageClassAnalysis,se_StorageClassAnalysisDataExport,se_Tag,se_Tagging,se_TagSet,se_TargetGrant,se_TargetGrants,se_TargetObjectKeyFormat,se_Tiering,se_TieringList,se_TopicConfiguration,se_TopicConfigurationList,se_Transition,se_TransitionList,se_UserMetadata,se_VersioningConfiguration,se_WebsiteConfiguration,de_AbortIncompleteMultipartUpload,de_AccessControlTranslation,de_AllowedHeaders,de_AllowedMethods,de_AllowedOrigins,de_AnalyticsAndOperator,de_AnalyticsConfiguration,de_AnalyticsConfigurationList,de_AnalyticsExportDestination,de_AnalyticsFilter,de_AnalyticsS3BucketDestination,de_Bucket,de_Buckets,de_Checksum,de_ChecksumAlgorithmList,de_CommonPrefix,de_CommonPrefixList,de_Condition,de_ContinuationEvent,de_CopyObjectResult,de_CopyPartResult,de_CORSRule,de_CORSRules,de_DefaultRetention,de_DeletedObject,de_DeletedObjects,de_DeleteMarkerEntry,de_DeleteMarkerReplication,de_DeleteMarkers,de_Destination,de_EncryptionConfiguration,de_EndEvent,de__Error,de_ErrorDetails,de_ErrorDocument,de_Errors,de_EventBridgeConfiguration,de_EventList,de_ExistingObjectReplication,de_ExposeHeaders,de_FilterRule,de_FilterRuleList,de_GetBucketMetadataTableConfigurationResult,de_GetObjectAttributesParts,de_Grant,de_Grantee,de_Grants,de_IndexDocument,de_Initiator,de_IntelligentTieringAndOperator,de_IntelligentTieringConfiguration,de_IntelligentTieringConfigurationList,de_IntelligentTieringFilter,de_InventoryConfiguration,de_InventoryConfigurationList,de_InventoryDestination,de_InventoryEncryption,de_InventoryFilter,de_InventoryOptionalFields,de_InventoryS3BucketDestination,de_InventorySchedule,de_LambdaFunctionConfiguration,de_LambdaFunctionConfigurationList,de_LifecycleExpiration,de_LifecycleRule,de_LifecycleRuleAndOperator,de_LifecycleRuleFilter,de_LifecycleRules,de_LoggingEnabled,de_MetadataTableConfigurationResult,de_Metrics,de_MetricsAndOperator,de_MetricsConfiguration,de_MetricsConfigurationList,de_MetricsFilter,de_MultipartUpload,de_MultipartUploadList,de_NoncurrentVersionExpiration,de_NoncurrentVersionTransition,de_NoncurrentVersionTransitionList,de_NotificationConfigurationFilter,de__Object,de_ObjectList,de_ObjectLockConfiguration,de_ObjectLockLegalHold,de_ObjectLockRetention,de_ObjectLockRule,de_ObjectPart,de_ObjectVersion,de_ObjectVersionList,de_Owner,de_OwnershipControls,de_OwnershipControlsRule,de_OwnershipControlsRules,de_Part,de_PartitionedPrefix,de_Parts,de_PartsList,de_PolicyStatus,de_Progress,de_PublicAccessBlockConfiguration,de_QueueConfiguration,de_QueueConfigurationList,de_Redirect,de_RedirectAllRequestsTo,de_ReplicaModifications,de_ReplicationConfiguration,de_ReplicationRule,de_ReplicationRuleAndOperator,de_ReplicationRuleFilter,de_ReplicationRules,de_ReplicationTime,de_ReplicationTimeValue,de_RestoreStatus,de_RoutingRule,de_RoutingRules,de_S3KeyFilter,de_S3TablesDestinationResult,de_ServerSideEncryptionByDefault,de_ServerSideEncryptionConfiguration,de_ServerSideEncryptionRule,de_ServerSideEncryptionRules,de_SessionCredentials,de_SourceSelectionCriteria,de_SSEKMS,de_SseKmsEncryptedObjects,de_SSES3,de_Stats,de_StorageClassAnalysis,de_StorageClassAnalysisDataExport,de_Tag,de_TagSet,de_TargetGrant,de_TargetGrants,de_TargetObjectKeyFormat,de_Tiering,de_TieringList,de_TopicConfiguration,de_TopicConfigurationList,de_Transition,de_TransitionList,deserializeMetadata2,collectBodyString2,_A,_AAO,_AC,_ACL,_ACLc,_ACLn,_ACP,_ACT,_ACc,_AD,_AED,_AF,_AH,_AHl,_AI,_AIMU,_AIc,_AKI,_AM,_AMl,_AO,_AOl,_APA,_APAc,_AQRD,_AR,_ARI,_AS,_ASBD,_ASEFF,_ASSEBD,_AT,_Ac,_B,_BAI,_BAS,_BGR,_BI,_BKE,_BLC,_BLCu,_BLN,_BLP,_BLS,_BLT,_BN,_BP,_BPA,_BPP,_BR,_BRy,_BS,_BT,_BVS,_Bu,_C,_CA,_CACL,_CBC,_CC,_CCRC,_CCRCC,_CCRCNVME,_CD,_CDr,_CE,_CF,_CFC,_CL,_CLo,_CM,_CMD,_CMU,_CORSC,_CORSR,_CORSRu,_CP,_CPo,_CR,_CRSBA,_CS,_CSHA,_CSHAh,_CSIM,_CSIMS,_CSINM,_CSIUS,_CSR,_CSSSECA,_CSSSECK,_CSSSECKMD,_CSV,_CSVI,_CSVIn,_CSVO,_CT,_CTo,_CTom,_CTon,_Ch,_Co,_Cod,_Com,_Con,_D,_DAI,_DE,_DM,_DMR,_DMRS,_DMVI,_DMe,_DN,_DR,_DRe,_Da,_Dat,_De,_Del,_Des,_Desc,_E,_EA,_EBC,_EBO,_EC,_ECn,_ED,_EH,_EHx,_EM,_EODM,_EOR,_EORS,_ERP,_ES,_ESBO,_ESx,_ET,_ETa,_ETn,_ETv,_ETx,_En,_Ena,_End,_Er,_Err,_Ev,_Eve,_Ex,_Exp,_F,_FD,_FHI,_FO,_FR,_FRN,_FRV,_FRi,_Fi,_Fo,_Fr,_G,_GFC,_GJP,_GR,_GRACP,_GW,_GWACP,_Gr,_Gra,_HECRE,_HN,_HRC,_I,_IC,_ICL,_ID,_ID_,_IDn,_IE,_IEn,_IF,_IFn,_IFnv,_II,_IIOV,_IL,_IM,_IMIT,_IMLMT,_IMS,_IMSf,_INM,_IOF,_IOV,_IP,_IPA,_IRIP,_IS,_ISBD,_ISn,_IT,_ITAO,_ITAT,_ITC,_ITCL,_ITD,_ITF,_ITI,_ITS,_IUS,_In,_Ini,_JSON,_JSONI,_JSONO,_JSONT,_K,_KC,_KI,_KM,_KMSC,_KMSKI,_KMSMKID,_KPE,_L,_LC,_LE,_LEi,_LFA,_LFC,_LFCa,_LI,_LM,_LMT,_LNAS,_LP,_LR,_LRAO,_LRF,_LT,_M,_MAO,_MAS,_MB,_MC,_MCL,_MD,_MDB,_MDf,_ME,_MF,_MFA,_MFAD,_MI,_MK,_MKe,_MM,_MOS,_MP,_MS,_MTC,_MTCR,_MU,_MV,_Me,_Mes,_Mi,_Mo,_N,_NC,_NCF,_NCT,_ND,_NI,_NKM,_NM,_NNV,_NPNM,_NUIM,_NVE,_NVIM,_NVT,_NVTo,_O,_OA,_OC,_OCACL,_OCR,_OF,_OI,_OK,_OL,_OLC,_OLE,_OLEFB,_OLLH,_OLLHS,_OLM,_OLR,_OLRM,_OLRUD,_OLRb,_OO,_OOA,_OOw,_OP,_OS,_OSGT,_OSGTB,_OSLT,_OSLTB,_OSV,_OSb,_OVI,_Ob,_P,_PABC,_PC,_PDS,_PI,_PN,_PNM,_PP,_Pa,_Par,_Parq,_Part,_Pe,_Pr,_Pri,_Q,_QA,_QC,_QCu,_QCuo,_QEC,_QF,_Qu,_R,_RART,_RC,_RCC,_RCD,_RCE,_RCL,_RCT,_RCe,_RD,_RE,_RED,_RKKID,_RKPW,_RKW,_RM,_RMS,_ROP,_RP,_RPB,_RPC,_RPe,_RR,_RRAO,_RRF,_RRS,_RRT,_RRe,_RRes,_RRo,_RRou,_RS,_RSe,_RT,_RTS,_RTV,_RTe,_RUD,_Re,_Red,_Ro,_Ru,_Rul,_S,_SA,_SAK,_SBD,_SC,_SCA,_SCADE,_SCASV,_SCt,_SDV,_SK,_SKEO,_SKEOS,_SKF,_SKe,_SL,_SM,_SOCR,_SP,_SPi,_SR,_SS,_SSC,_SSE,_SSEA,_SSEBD,_SSEC,_SSECA,_SSECK,_SSECKMD,_SSEKMS,_SSEKMSEC,_SSEKMSKI,_SSER,_SSES,_ST,_STBA,_STD,_STDR,_STN,_S_,_Sc,_Se,_Si,_St,_Su,_T,_TA,_TAa,_TB,_TBA,_TC,_TCo,_TCop,_TD,_TDMOS,_TG,_TGa,_TN,_TNa,_TOKF,_TP,_TPC,_TS,_TSC,_Ta,_Tag,_Ti,_Tie,_Tier,_Tim,_To,_Top,_Tr,_Tra,_Ty,_U,_UI,_UIM,_UM,_URI,_Up,_V,_VC,_VCe,_VI,_VIM,_Va,_Ve,_WC,_WOB,_WRL,_Y,_a6,_ac,_acl,_ar,_at,_br,_c2,_cc,_cd,_ce,_cl,_cl_,_cm,_cr,_ct,_ct_,_d,_de,_e,_en,_et,_eta,_ex,_fo,_i,_im,_ims,_in,_inm,_it,_ius,_km,_l,_lh,_lm,_lo,_log,_lt,_m,_mT,_ma,_mb,_mdb,_me,_mk,_mp,_mu,_n,_oC,_ol,_p,_pAB,_pN,_pS,_pnm,_pr,_r,_rP,_ra,_rcc,_rcd,_rce,_rcl,_rct,_re,_res,_ret,_s,_sa,_se,_st,_t,_to,_u,_uI,_uim,_v,_vI,_ve,_ver,_vim,_w,_x,_xaa,_xaad,_xaapa,_xaari,_xaas,_xabgr,_xabln,_xablt,_xabole,_xabolt,_xabr,_xaca,_xacc,_xacc_,_xacc__,_xacm,_xacrsba,_xacs,_xacs_,_xacs__,_xacsim,_xacsims,_xacsinm,_xacsius,_xacsm,_xacsr,_xacssseca,_xacssseck,_xacssseckm,_xacsvi,_xact,_xadm,_xae,_xaebo,_xafec,_xafem,_xafhar,_xafhcc,_xafhcd,_xafhce,_xafhcl,_xafhcr,_xafhct,_xafhe,_xafhe_,_xafhlm,_xafhxacc,_xafhxacc_,_xafhxacc__,_xafhxacs,_xafhxacs_,_xafhxadm,_xafhxae,_xafhxamm,_xafhxampc,_xafhxaollh,_xafhxaolm,_xafhxaolrud,_xafhxar,_xafhxarc,_xafhxars,_xafhxasc,_xafhxasse,_xafhxasseakki,_xafhxassebke,_xafhxasseca,_xafhxasseckm,_xafhxatc,_xafhxavi,_xafs,_xagfc,_xagr,_xagra,_xagw,_xagwa,_xaimit,_xaimlmt,_xaims,_xam,_xamd,_xamm,_xamos,_xamp,_xampc,_xaoa,_xaollh,_xaolm,_xaolrud,_xaoo,_xaooa,_xaos,_xapnm,_xar,_xarc,_xarop,_xarp,_xarr,_xars,_xart,_xasc,_xasca,_xasdv,_xasebo,_xasse,_xasseakki,_xassebke,_xassec,_xasseca,_xasseck,_xasseckm,_xat,_xatc,_xatd,_xatdmos,_xavi,_xawob,_xawrl,_xi,CreateSessionCommand,fromUtf84,SHA_1_HASH,SHA_1_HMAC_ALGO,EMPTY_DATA_SHA_1,fallbackWindow,Sha1,subtleCryptoMethods,Sha12,SHA_256_HASH,SHA_256_HMAC_ALGO,EMPTY_DATA_SHA_256,Sha256,KEY,INIT,MAX_HASHABLE_LENGTH,RawSha256,Sha2562,Sha2563,import_bowser,createDefaultUserAgentProvider,Int642,HeaderMarshaller,HEADER_VALUE_TYPE2,BOOLEAN_TAG,BYTE_TAG,SHORT_TAG,INT_TAG,LONG_TAG,BINARY_TAG,STRING_TAG,TIMESTAMP_TAG,UUID_TAG,UUID_PATTERN2,EventStreamCodec,MessageDecoderStream,MessageEncoderStream,SmithyMessageDecoderStream,SmithyMessageEncoderStream,EventStreamMarshaller,readableStreamtoIterable,iterableToReadableStream,EventStreamMarshaller2,isReadableStream2,eventStreamSerdeProvider2,blobHasher,invalidProvider,INIT2,Md5,TEXT_ENCODER,calculateBodyLength,getRuntimeConfig,DEFAULTS_MODE_OPTIONS,import_bowser2,resolveDefaultsModeConfig,isMobileBrowser,getRuntimeConfig2,getAwsRegionExtensionConfiguration,resolveAwsRegionExtensionConfiguration,getHttpAuthExtensionConfiguration,resolveHttpAuthRuntimeConfig,resolveRuntimeExtensions,S3Client,AbortMultipartUploadCommand,ssecMiddlewareOptions,getSsecPlugin,CompleteMultipartUploadCommand,CopyObjectCommand,locationConstraintMiddlewareOptions,getLocationConstraintPlugin,CreateBucketCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectAclCommand,PutObjectCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RestoreObjectCommand,SelectObjectContentCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand,S3,applyMd5BodyChecksumMiddleware,hasHeader3,CheckPointInfoDefault,PREFIX_TRENCH,idx,series,indexes,inProgress,failed,Trench,RECORD_SPLIT,UNIT_SPLIT,te4,JournalSyncAbstract,JournalSyncMinio,MILSTONE_DOCID,currentVersionRange,LiveSyncJournalReplicator,currentVersionRange2,selectorOnDemandPull,LiveSyncCouchDBReplicator,ObsHttpHandler,measures,root_17,root4,$$css5,import_obsidian7,TestPaneView,ModuleDev,SerializedFileAccess,StorageEventManager,StorageEventManagerObsidian,import_obsidian8,ModuleFileAccessObsidian,AutoClosableModal,InputStringDialog,PopoverSelectString,MessageBox,askYesNo,askSelectString,askString,ModuleInputUIObsidian,ConditionType,RuleLevel,DoctorRegulationV0_24_30,DoctorRegulation,_a7,OnDialogSettingsDefault,SettingInformation,ModuleMigration,ModuleCheckRemoteSize,import_diff_match_patch4,ModuleConflictResolver,ModuleInteractiveConflictResolver,import_obsidian10,ModuleObsidianSettings,ModuleRedFlag,ModuleObsidianMenu,import_qrcode_generator,ModuleSetupObsidian,ModuleDatabaseFileAccess,ModuleFileHandler,PouchError,MISSING_BULK_DOCS,MISSING_DOC,REV_CONFLICT,INVALID_ID,MISSING_ID,RESERVED_ID,UNKNOWN_ERROR,BAD_ARG,QUERY_PARSE_ERROR,DOC_VALIDATION,BAD_REQUEST,NOT_AN_OBJECT,IDB_ERROR,INVALID_REV,MISSING_STUB,getRandomValues2,rnds82,regex_default2,validate_default2,byteToHex2,stringify_default2,v4_default2,thisAtob,thisBtoa,import_spark_md5,import_events20,funcToString,objectCtorString,MAX_NUM_CONCURRENT_REQUESTS,hasLocal,nextTick,Changes,keys2,qName,qParser,parser,uuid,f3,h2,MIN_MAGNITUDE,MAGNITUDE_DIGITS,SEP,combinationFields,matchers,index_browser_es_default,import_events21,Changes2,validRevRegex,AbstractPouchDB,TaskQueue,PouchInternal,PouchDB,ActiveTasks,eventEmitter,index_es_default,import_vuvuzela,import_spark_md52,setImmediateShim2,MD5_CHUNK_SIZE2,reservedWords,dataWords,ADAPTER_VERSION,DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE,META_STORE,LOCAL_STORE,DETECT_BLOB_SUPPORT_STORE,changesHandler$1,running,queue,cachedDBs,blobSupportPromise,openReqList,index_es_default2,import_spark_md53,setImmediateShim3,MD5_CHUNK_SIZE3,IDB_NULL,IDB_FALSE,IDB_TRUE,TEST_KEY_INVALID,TEST_PATH_INVALID,KEY_INVALID,PATH_INVALID,SLASH,IS_DOT,DOC_STORE2,META_LOCAL_STORE,POUCHDB_IDB_VERSION,versionMultiplier,BINARY_ATTACHMENTS,COUCH_COLLATE_LO,COUCH_COLLATE_HI,IDB_COLLATE_LO,IDB_COLLATE_HI,ADAPTER_NAME,idbChanges,openDatabases,index_es_default3,CHANGES_BATCH_SIZE,MAX_SIMULTANEOUS_REVS,CHANGES_TIMEOUT_BUFFER,DEFAULT_HEARTBEAT,supportsBulkGetMap,index_es_default4,QueryParseError,NotFoundError,BuiltInError,import_spark_md54,TaskQueue2,persistentQueues,tempViewQueue,index_es_default5,log,isArray,toJSON,builtInReduce__sum,builtInReduce__count,builtInReduce__stats,abstract,index_browser_es_default2,CHECKPOINT_VERSION,REPLICATOR,CHECKPOINT_HISTORY_SIZE,LOWEST_SEQ,CheckpointerInternal,comparisons,index_es_default6,import_spark_md55,setImmediateShim5,index_es_default7,import_events22,STARTING_BACK_OFF,Replication,Sync,index_es_default8,import_spark_md56,nativeFlat,polyFlat,flatten,requireValidation,arrayTypeComparisonOperators,equalityOperators,abstractMapper,ddocIdPrefix,COLLATE_LO,COLLATE_HI,SHORT_CIRCUIT_QUERY,logicalMatchers,plugin2,index_browser_es_default3,import_transform_pouch,ModuleObsidianAPI,ModuleObsidianEvents,combineOnUpdate,setLevelClass,import_obsidian11,LiveSyncSetting,updateInformation,lastVersion,import_obsidian12,root_110,root5,$$css6,EVENT_REQUEST_SHOW_HISTORY,LocalDatabaseMaintenance,toc,stubs,ObsidianLiveSyncSettingTab,ModuleObsidianSettingDialogue,DocumentHistoryModal,ModuleObsidianDocumentHistory,root_111,root_24,root_33,root_44,root_64,root_83,root_53,root_93,root_102,root6,$$css7,GlobalHistoryView,ModuleObsidianGlobalHistory,SETTING_HEADER,ModuleObsidianSettingsAsMarkdown,ModuleInitializerFile,ModuleKeyValueDB,ModulePouchDB,ModuleReplicator,ModuleReplicatorCouchDB,ModuleReplicatorMinIO,ModuleTargetFilter,ModulePeriodicProcess,ModuleRemoteGovernor,ModuleLocalDatabaseObsidian,ModuleConflictChecker,ModuleResolvingMismatchedTweaks,ModuleIntegratedTest,ModuleRebuilder,import_obsidian14,ModuleReplicateTest,ModuleLiveSyncMain,ModuleExtraSyncObsidian,EVENT_P2P_PEER_SHOW_EXTRA_MENU,AcceptedStatus,ConnectionStatus,root_25,root_113,root_34,on_click2,on_click_1,root_54,on_click_2,on_click_3,root_65,root_45,on_click_4,root_72,root_94,root_103,root_84,root7,$$css8,root_114,on_click3,on_click_12,root_26,root_35,root_46,root_73,root_85,root_55,root8,$$css9,import_obsidian15,P2PReplicatorPaneView,ObsidianAPIBase,instance2,p3,import_obsidian17,webcrypto4,Environment,P2PReplicatorCommandBase,P2PReplicator,InterceptiveAll,InterceptiveEvery,InterceptiveAny,ObsidianLiveSyncPlugin,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__typeError=msg=>{throw TypeError(msg)},__defNormalProp=(obj,key2,value)=>key2 in obj?__defProp(obj,key2,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key2]=value,__commonJS=(cb2,mod2)=>function __require(){return mod2||(0,cb2[__getOwnPropNames(cb2)[0]])((mod2={exports:{}}).exports,mod2),mod2.exports},__export=(target,all2)=>{for(var name in all2)__defProp(target,name,{get:all2[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key2 of __getOwnPropNames(from))__hasOwnProp.call(to,key2)||key2===except||__defProp(to,key2,{get:()=>from[key2],enumerable:!(desc=__getOwnPropDesc(from,key2))||desc.enumerable});return to},__toESM=(mod2,isNodeMode,target)=>(target=null!=mod2?__create(__getProtoOf(mod2)):{},__copyProps(!isNodeMode&&mod2&&mod2.__esModule?target:__defProp(target,"default",{value:mod2,enumerable:!0}),mod2)),__toCommonJS=mod2=>__copyProps(__defProp({},"__esModule",{value:!0}),mod2),__publicField=(obj,key2,value)=>__defNormalProp(obj,"symbol"!=typeof key2?key2+"":key2,value),__accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg),__privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method),require_diff_match_patch=__commonJS({"node_modules/diff-match-patch/index.js"(exports,module2){var diff_match_patch4=function(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=.5;this.Match_Distance=1e3;this.Patch_DeleteThreshold=.5;this.Patch_Margin=4;this.Match_MaxBits=32};diff_match_patch4.Diff=function(op,text2){return[op,text2]};diff_match_patch4.prototype.diff_main=function(text1,text2,opt_checklines,opt_deadline){var deadline,checklines,commonlength,commonprefix,commonsuffix,diffs;void 0===opt_deadline&&(opt_deadline=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);deadline=opt_deadline;if(null==text1||null==text2)throw new Error("Null input. (diff_main)");if(text1==text2)return text1?[new diff_match_patch4.Diff(0,text1)]:[];void 0===opt_checklines&&(opt_checklines=!0);checklines=opt_checklines;commonlength=this.diff_commonPrefix(text1,text2);commonprefix=text1.substring(0,commonlength);text1=text1.substring(commonlength);text2=text2.substring(commonlength);commonlength=this.diff_commonSuffix(text1,text2);commonsuffix=text1.substring(text1.length-commonlength);text1=text1.substring(0,text1.length-commonlength);text2=text2.substring(0,text2.length-commonlength);diffs=this.diff_compute_(text1,text2,checklines,deadline);commonprefix&&diffs.unshift(new diff_match_patch4.Diff(0,commonprefix));commonsuffix&&diffs.push(new diff_match_patch4.Diff(0,commonsuffix));this.diff_cleanupMerge(diffs);return diffs};diff_match_patch4.prototype.diff_compute_=function(text1,text2,checklines,deadline){var diffs,longtext,shorttext,i2,hm,text1_a,text1_b,text2_a,text2_b,mid_common,diffs_a,diffs_b;if(!text1)return[new diff_match_patch4.Diff(1,text2)];if(!text2)return[new diff_match_patch4.Diff(-1,text1)];longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;if(-1!=(i2=longtext.indexOf(shorttext))){diffs=[new diff_match_patch4.Diff(1,longtext.substring(0,i2)),new diff_match_patch4.Diff(0,shorttext),new diff_match_patch4.Diff(1,longtext.substring(i2+shorttext.length))];text1.length>text2.length&&(diffs[0][0]=diffs[2][0]=-1);return diffs}if(1==shorttext.length)return[new diff_match_patch4.Diff(-1,text1),new diff_match_patch4.Diff(1,text2)];if(hm=this.diff_halfMatch_(text1,text2)){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3];mid_common=hm[4];diffs_a=this.diff_main(text1_a,text2_a,checklines,deadline);diffs_b=this.diff_main(text1_b,text2_b,checklines,deadline);return diffs_a.concat([new diff_match_patch4.Diff(0,mid_common)],diffs_b)}return checklines&&text1.length>100&&text2.length>100?this.diff_lineMode_(text1,text2,deadline):this.diff_bisect_(text1,text2,deadline)};diff_match_patch4.prototype.diff_lineMode_=function(text1,text2,deadline){var linearray,diffs,pointer,count_delete,count_insert,text_delete,text_insert,subDiff,j2,a2=this.diff_linesToChars_(text1,text2);text1=a2.chars1;text2=a2.chars2;linearray=a2.lineArray;diffs=this.diff_main(text1,text2,!1,deadline);this.diff_charsToLines_(diffs,linearray);this.diff_cleanupSemantic(diffs);diffs.push(new diff_match_patch4.Diff(0,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer=1&&count_insert>=1){diffs.splice(pointer-count_delete-count_insert,count_delete+count_insert);pointer=pointer-count_delete-count_insert;for(j2=(subDiff=this.diff_main(text_delete,text_insert,!1,deadline)).length-1;j2>=0;j2--)diffs.splice(pointer,0,subDiff[j2]);pointer+=subDiff.length}count_insert=0;count_delete=0;text_delete="";text_insert="";break}pointer++}diffs.pop();return diffs};diff_match_patch4.prototype.diff_bisect_=function(text1,text2,deadline){var x2,delta,front,k1start,k1end,k2start,k2end,d4,k1,k1_offset,x1,y1,k2_offset,x22,k2,y2,text1_length=text1.length,text2_length=text2.length,max_d=Math.ceil((text1_length+text2_length)/2),v_offset=max_d,v_length=2*max_d,v1=new Array(v_length),v2=new Array(v_length);for(x2=0;x2deadline);d4++){for(k1=-d4+k1start;k1<=d4-k1end;k1+=2){k1_offset=v_offset+k1;y1=(x1=k1==-d4||k1!=d4&&v1[k1_offset-1]text1_length)k1end+=2;else if(y1>text2_length)k1start+=2;else if(front&&(k2_offset=v_offset+delta-k1)>=0&&k2_offset=(x22=text1_length-v2[k2_offset]))return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}for(k2=-d4+k2start;k2<=d4-k2end;k2+=2){k2_offset=v_offset+k2;y2=(x22=k2==-d4||k2!=d4&&v2[k2_offset-1]text1_length)k2end+=2;else if(y2>text2_length)k2start+=2;else if(!front&&(k1_offset=v_offset+delta-k2)>=0&&k1_offset=(x22=text1_length-x22))return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}}}return[new diff_match_patch4.Diff(-1,text1),new diff_match_patch4.Diff(1,text2)]};diff_match_patch4.prototype.diff_bisectSplit_=function(text1,text2,x2,y2,deadline){var text1a=text1.substring(0,x2),text2a=text2.substring(0,y2),text1b=text1.substring(x2),text2b=text2.substring(y2),diffs=this.diff_main(text1a,text2a,!1,deadline),diffsb=this.diff_main(text1b,text2b,!1,deadline);return diffs.concat(diffsb)};diff_match_patch4.prototype.diff_linesToChars_=function(text1,text2){function diff_linesToCharsMunge_(text3){for(var line,chars="",lineStart=0,lineEnd=-1,lineArrayLength=lineArray.length;lineEndtext2_length?text1=text1.substring(text1_length-text2_length):text1_length=longtext2.length?[best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,best_common]:null}var longtext,shorttext,dmp,hm1,hm2,hm,text1_a,text1_b,text2_a,text2_b;if(this.Diff_Timeout<=0)return null;longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;if(longtext.length<4||2*shorttext.lengthhm2[4].length?hm1:hm2:hm1;if(text1.length>text2.length){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3]}else{text2_a=hm[0];text2_b=hm[1];text1_a=hm[2];text1_b=hm[3]}return[text1_a,text1_b,text2_a,text2_b,hm[4]]};diff_match_patch4.prototype.diff_cleanupSemantic=function(diffs){for(var deletion,insertion,overlap_length1,overlap_length2,changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,length_insertions1=0,length_deletions1=0,length_insertions2=0,length_deletions2=0;pointer0?equalities[equalitiesLength-1]:-1;length_insertions1=0;length_deletions1=0;length_insertions2=0;length_deletions2=0;lastEquality=null;changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs);this.diff_cleanupSemanticLossless(diffs);pointer=1;for(;pointer=(overlap_length2=this.diff_commonOverlap_(insertion,deletion))){if(overlap_length1>=deletion.length/2||overlap_length1>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(0,insertion.substring(0,overlap_length1)));diffs[pointer-1][1]=deletion.substring(0,deletion.length-overlap_length1);diffs[pointer+1][1]=insertion.substring(overlap_length1);pointer++}}else if(overlap_length2>=deletion.length/2||overlap_length2>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(0,deletion.substring(0,overlap_length2)));diffs[pointer-1][0]=1;diffs[pointer-1][1]=insertion.substring(0,insertion.length-overlap_length2);diffs[pointer+1][0]=-1;diffs[pointer+1][1]=deletion.substring(overlap_length2);pointer++}pointer++}pointer++}};diff_match_patch4.prototype.diff_cleanupSemanticLossless=function(diffs){function diff_cleanupSemanticScore_(one,two){var char1,char2,nonAlphaNumeric1,nonAlphaNumeric2,whitespace1,whitespace2,lineBreak1,lineBreak2,blankLine1,blankLine2;if(!one||!two)return 6;char1=one.charAt(one.length-1);char2=two.charAt(0);nonAlphaNumeric1=char1.match(diff_match_patch4.nonAlphaNumericRegex_);nonAlphaNumeric2=char2.match(diff_match_patch4.nonAlphaNumericRegex_);whitespace1=nonAlphaNumeric1&&char1.match(diff_match_patch4.whitespaceRegex_);whitespace2=nonAlphaNumeric2&&char2.match(diff_match_patch4.whitespaceRegex_);lineBreak1=whitespace1&&char1.match(diff_match_patch4.linebreakRegex_);lineBreak2=whitespace2&&char2.match(diff_match_patch4.linebreakRegex_);blankLine1=lineBreak1&&one.match(diff_match_patch4.blanklineEndRegex_);blankLine2=lineBreak2&&two.match(diff_match_patch4.blanklineStartRegex_);return blankLine1||blankLine2?5:lineBreak1||lineBreak2?4:nonAlphaNumeric1&&!whitespace1&&whitespace2?3:whitespace1||whitespace2?2:nonAlphaNumeric1||nonAlphaNumeric2?1:0}for(var equality1,edit,equality2,commonOffset,commonString,bestEquality1,bestEdit,bestEquality2,bestScore,score,pointer=1;pointer=bestScore){bestScore=score;bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2}}if(diffs[pointer-1][1]!=bestEquality1){if(bestEquality1)diffs[pointer-1][1]=bestEquality1;else{diffs.splice(pointer-1,1);pointer--}diffs[pointer][1]=bestEdit;if(bestEquality2)diffs[pointer+1][1]=bestEquality2;else{diffs.splice(pointer+1,1);pointer--}}}pointer++}};diff_match_patch4.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch4.whitespaceRegex_=/\s/;diff_match_patch4.linebreakRegex_=/[\r\n]/;diff_match_patch4.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch4.blanklineStartRegex_=/^\r?\n\r?\n/;diff_match_patch4.prototype.diff_cleanupEfficiency=function(diffs){for(var changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,pre_ins=!1,pre_del=!1,post_ins=!1,post_del=!1;pointer0?equalities[equalitiesLength-1]:-1;post_ins=post_del=!1}changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs)};diff_match_patch4.prototype.diff_cleanupMerge=function(diffs){var pointer,count_delete,count_insert,text_delete,text_insert,commonlength,changes3;diffs.push(new diff_match_patch4.Diff(0,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer1){if(0!==count_delete&&0!==count_insert){if(0!==(commonlength=this.diff_commonPrefix(text_insert,text_delete))){if(pointer-count_delete-count_insert>0&&0==diffs[pointer-count_delete-count_insert-1][0])diffs[pointer-count_delete-count_insert-1][1]+=text_insert.substring(0,commonlength);else{diffs.splice(0,0,new diff_match_patch4.Diff(0,text_insert.substring(0,commonlength)));pointer++}text_insert=text_insert.substring(commonlength);text_delete=text_delete.substring(commonlength)}if(0!==(commonlength=this.diff_commonSuffix(text_insert,text_delete))){diffs[pointer][1]=text_insert.substring(text_insert.length-commonlength)+diffs[pointer][1];text_insert=text_insert.substring(0,text_insert.length-commonlength);text_delete=text_delete.substring(0,text_delete.length-commonlength)}}pointer-=count_delete+count_insert;diffs.splice(pointer,count_delete+count_insert);if(text_delete.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(-1,text_delete));pointer++}if(text_insert.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(1,text_insert));pointer++}pointer++}else if(0!==pointer&&0==diffs[pointer-1][0]){diffs[pointer-1][1]+=diffs[pointer][1];diffs.splice(pointer,1)}else pointer++;count_insert=0;count_delete=0;text_delete="";text_insert="";break}""===diffs[diffs.length-1][1]&&diffs.pop();changes3=!1;pointer=1;for(;pointerloc)break;last_chars1=chars1;last_chars2=chars2}return diffs.length!=x2&&-1===diffs[x2][0]?last_chars2:last_chars2+(loc-last_chars1)};diff_match_patch4.prototype.diff_prettyHtml=function(diffs){var x2,op,text2,html2=[],pattern_amp=/&/g,pattern_lt=//g,pattern_para=/\n/g;for(x2=0;x2");switch(op){case 1:html2[x2]=''+text2+"";break;case-1:html2[x2]=''+text2+"";break;case 0:html2[x2]=""+text2+"";break}}return html2.join("")};diff_match_patch4.prototype.diff_text1=function(diffs){var x2,text2=[];for(x2=0;x2this.Match_MaxBits)throw new Error("Pattern too long for this browser.");s2=this.match_alphabet_(pattern);dmp=this;score_threshold=this.Match_Threshold;if(-1!=(best_loc=text2.indexOf(pattern,loc))){score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold);-1!=(best_loc=text2.lastIndexOf(pattern,loc+pattern.length))&&(score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold))}matchmask=1<=start;j2--){charMatch=s2[text2.charAt(j2-1)];rd[j2]=0===d4?(rd[j2+1]<<1|1)&charMatch:(rd[j2+1]<<1|1)&charMatch|(last_rd[j2+1]|last_rd[j2])<<1|1|last_rd[j2+1];if(rd[j2]&matchmask&&(score=match_bitapScore_(d4,j2-1))<=score_threshold){score_threshold=score;if(!((best_loc=j2-1)>loc))break;start=Math.max(1,2*loc-best_loc)}}if(match_bitapScore_(d4+1,loc)>score_threshold)break;last_rd=rd}return best_loc};diff_match_patch4.prototype.match_alphabet_=function(pattern){var i2,s2={};for(i2=0;i22){this.diff_cleanupSemantic(diffs);this.diff_cleanupEfficiency(diffs)}}else if(a2&&"object"==typeof a2&&void 0===opt_b&&void 0===opt_c){diffs=a2;text1=this.diff_text1(diffs)}else if("string"==typeof a2&&opt_b&&"object"==typeof opt_b&&void 0===opt_c){text1=a2;diffs=opt_b}else{if("string"!=typeof a2||"string"!=typeof opt_b||!opt_c||"object"!=typeof opt_c)throw new Error("Unknown call format to patch_make.");text1=a2;diffs=opt_c}if(0===diffs.length)return[];patches=[];patch=new diff_match_patch4.patch_obj;patchDiffLength=0;char_count1=0;char_count2=0;prepatch_text=text1;postpatch_text=text1;for(x2=0;x2=2*this.Patch_Margin&&patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch);patch=new diff_match_patch4.patch_obj;patchDiffLength=0;prepatch_text=postpatch_text;char_count1=char_count2}break}1!==diff_type&&(char_count1+=diff_text.length);-1!==diff_type&&(char_count2+=diff_text.length)}if(patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch)}return patches};diff_match_patch4.prototype.patch_deepCopy=function(patches){var x2,patch,patchCopy,y2,patchesCopy=[];for(x2=0;x2this.Match_MaxBits?-1!=(start_loc=this.match_main(text2,text1.substring(0,this.Match_MaxBits),expected_loc))&&(-1==(end_loc=this.match_main(text2,text1.substring(text1.length-this.Match_MaxBits),expected_loc+text1.length-this.Match_MaxBits))||start_loc>=end_loc)&&(start_loc=-1):start_loc=this.match_main(text2,text1,expected_loc);if(-1==start_loc){results[x2]=!1;delta-=patches[x2].length2-patches[x2].length1}else{results[x2]=!0;delta=start_loc-expected_loc;if(text1==(text22=-1==end_loc?text2.substring(start_loc,start_loc+text1.length):text2.substring(start_loc,end_loc+this.Match_MaxBits)))text2=text2.substring(0,start_loc)+this.diff_text2(patches[x2].diffs)+text2.substring(start_loc+text1.length);else{diffs=this.diff_main(text1,text22,!1);if(text1.length>this.Match_MaxBits&&this.diff_levenshtein(diffs)/text1.length>this.Patch_DeleteThreshold)results[x2]=!1;else{this.diff_cleanupSemanticLossless(diffs);index1=0;for(y2=0;y2diffs[0][1].length){extraLength=paddingLength-diffs[0][1].length;diffs[0][1]=nullPadding.substring(diffs[0][1].length)+diffs[0][1];patch.start1-=extraLength;patch.start2-=extraLength;patch.length1+=extraLength;patch.length2+=extraLength}if(0==(diffs=(patch=patches[patches.length-1]).diffs).length||0!=diffs[diffs.length-1][0]){diffs.push(new diff_match_patch4.Diff(0,nullPadding));patch.length1+=paddingLength;patch.length2+=paddingLength}else if(paddingLength>diffs[diffs.length-1][1].length){extraLength=paddingLength-diffs[diffs.length-1][1].length;diffs[diffs.length-1][1]+=nullPadding.substring(0,extraLength);patch.length1+=extraLength;patch.length2+=extraLength}return nullPadding};diff_match_patch4.prototype.patch_splitMax=function(patches){var x2,bigpatch,start1,start2,precontext,patch,empty2,diff_type,diff_text,postcontext,patch_size=this.Match_MaxBits;for(x2=0;x22*patch_size){patch.length1+=diff_text.length;start1+=diff_text.length;empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));bigpatch.diffs.shift()}else{diff_text=diff_text.substring(0,patch_size-patch.length1-this.Patch_Margin);patch.length1+=diff_text.length;start1+=diff_text.length;if(0===diff_type){patch.length2+=diff_text.length;start2+=diff_text.length}else empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));diff_text==bigpatch.diffs[0][1]?bigpatch.diffs.shift():bigpatch.diffs[0][1]=bigpatch.diffs[0][1].substring(diff_text.length)}}precontext=(precontext=this.diff_text2(patch.diffs)).substring(precontext.length-this.Patch_Margin);if(""!==(postcontext=this.diff_text1(bigpatch.diffs).substring(0,this.Patch_Margin))){patch.length1+=postcontext.length;patch.length2+=postcontext.length;0!==patch.diffs.length&&0===patch.diffs[patch.diffs.length-1][0]?patch.diffs[patch.diffs.length-1][1]+=postcontext:patch.diffs.push(new diff_match_patch4.Diff(0,postcontext))}empty2||patches.splice(++x2,0,patch)}}};diff_match_patch4.prototype.patch_toText=function(patches){var x2,text2=[];for(x2=0;x25&&"xml"===tagname)return getErrorObject("InvalidXml","XML declaration allowed only at the start of the document.",getLineNumberForPosition(xmlData,i2));if("?"==xmlData[i2]&&">"==xmlData[i2+1]){i2++;break}}return i2}function readCommentAndCDATA(xmlData,i2){if(xmlData.length>i2+5&&"-"===xmlData[i2+1]&&"-"===xmlData[i2+2]){for(i2+=3;i2"===xmlData[i2+2]){i2+=2;break}}else if(xmlData.length>i2+8&&"D"===xmlData[i2+1]&&"O"===xmlData[i2+2]&&"C"===xmlData[i2+3]&&"T"===xmlData[i2+4]&&"Y"===xmlData[i2+5]&&"P"===xmlData[i2+6]&&"E"===xmlData[i2+7]){let angleBracketsCount=1;for(i2+=8;i2"===xmlData[i2]){angleBracketsCount--;if(0===angleBracketsCount)break}}else if(xmlData.length>i2+9&&"["===xmlData[i2+1]&&"C"===xmlData[i2+2]&&"D"===xmlData[i2+3]&&"A"===xmlData[i2+4]&&"T"===xmlData[i2+5]&&"A"===xmlData[i2+6]&&"["===xmlData[i2+7])for(i2+=8;i2"===xmlData[i2+2]){i2+=2;break}return i2}function readAttributeStr(xmlData,i2){let attrStr="",startChar="",tagClosed=!1;for(;i2"===xmlData[i2]&&""===startChar){tagClosed=!0;break}attrStr+=xmlData[i2]}return""===startChar&&{value:attrStr,index:i2,tagClosed}}function validateAttributeString(attrStr,options){const matches=util.getAllMatches(attrStr,validAttrStrRegxp),attrNames={};for(let i2=0;i2"!==xmlData[i2]&&" "!==xmlData[i2]&&"\t"!==xmlData[i2]&&"\n"!==xmlData[i2]&&"\r"!==xmlData[i2];i2++)tagName+=xmlData[i2];tagName=tagName.trim();if("/"===tagName[tagName.length-1]){tagName=tagName.substring(0,tagName.length-1);i2--}if(!(tagname=tagName,util.isName(tagname))){let msg;msg=0===tagName.trim().length?"Invalid space after '<'.":"Tag '"+tagName+"' is an invalid name.";return getErrorObject("InvalidTag",msg,getLineNumberForPosition(xmlData,i2))}const result=readAttributeStr(xmlData,i2);if(!1===result)return getErrorObject("InvalidAttr","Attributes for '"+tagName+"' have open quote.",getLineNumberForPosition(xmlData,i2));let attrStr=result.value;i2=result.index;if("/"===attrStr[attrStr.length-1]){const attrStrStart=i2-attrStr.length;attrStr=attrStr.substring(0,attrStr.length-1);const isValid=validateAttributeString(attrStr,options);if(!0!==isValid)return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,attrStrStart+isValid.err.line));tagFound=!0}else if(closingTag){if(!result.tagClosed)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' doesn't have proper closing.",getLineNumberForPosition(xmlData,i2));if(attrStr.trim().length>0)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' can't have attributes or invalid starting.",getLineNumberForPosition(xmlData,tagStartPos));if(0===tags.length)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' has not been opened.",getLineNumberForPosition(xmlData,tagStartPos));{const otg=tags.pop();if(tagName!==otg.tagName){let openPos=getLineNumberForPosition(xmlData,otg.tagStartPos);return getErrorObject("InvalidTag","Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",getLineNumberForPosition(xmlData,tagStartPos))}0==tags.length&&(reachedRoot=!0)}}else{const isValid=validateAttributeString(attrStr,options);if(!0!==isValid)return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,i2-attrStr.length+isValid.err.line));if(!0===reachedRoot)return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(xmlData,i2));-1!==options.unpairedTags.indexOf(tagName)||tags.push({tagName,tagStartPos});tagFound=!0}for(i2++;i20)||getErrorObject("InvalidXml","Invalid '"+JSON.stringify(tags.map((t3=>t3.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):getErrorObject("InvalidXml","Start tag expected.",1)};doubleQuote='"';singleQuote="'";validAttrStrRegxp=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g")}}),require_OptionsBuilder=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports){var defaultOptions={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(tagName,val2){return val2},attributeValueProcessor:function(attrName,val2){return val2},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(tagName,jPath,attrs){return tagName}};exports.buildOptions=function(options){return Object.assign({},defaultOptions,options)};exports.defaultOptions=defaultOptions}}),require_xmlNode=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports,module2){"use strict";module2.exports=class{constructor(tagname){this.tagname=tagname;this.child=[];this[":@"]={}}add(key2,val2){"__proto__"===key2&&(key2="#__proto__");this.child.push({[key2]:val2})}addChild(node){"__proto__"===node.tagname&&(node.tagname="#__proto__");node[":@"]&&Object.keys(node[":@"]).length>0?this.child.push({[node.tagname]:node.child,[":@"]:node[":@"]}):this.child.push({[node.tagname]:node.child})}}}}),require_DocTypeReader=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports,module2){function readEntityExp(xmlData,i2){let entityName2="";for(;i2"===xmlData[i2]){if(comment2){if("-"===xmlData[i2-1]&&"-"===xmlData[i2-2]){comment2=!1;angleBracketsCount--}}else angleBracketsCount--;if(0===angleBracketsCount)break}else"["===xmlData[i2]?hasBody=!0:exp+=xmlData[i2];else{if(hasBody&&isEntity(xmlData,i2)){i2+=7;[entityName,val,i2]=readEntityExp(xmlData,i2+1);-1===val.indexOf("&")&&(entities[validateEntityName(entityName)]={regx:RegExp(`&${entityName};`,"g"),val})}else if(hasBody&&isElement(xmlData,i2))i2+=8;else if(hasBody&&isAttlist(xmlData,i2))i2+=8;else if(hasBody&&isNotation(xmlData,i2))i2+=9;else{if(!isComment)throw new Error("Invalid DOCTYPE");comment2=!0}angleBracketsCount++;exp=""}if(0!==angleBracketsCount)throw new Error("Unclosed DOCTYPE")}return{entities,i:i2}}}}),require_strnum=__commonJS({"node_modules/strnum/strnum.js"(exports,module2){var hexRegex=/^[-+]?0x[a-fA-F0-9]+$/,numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,consider={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};module2.exports=function toNumber(str,options={}){options=Object.assign({},consider,options);if(!str||"string"!=typeof str)return str;let trimmedStr=str.trim();if(void 0!==options.skipLike&&options.skipLike.test(trimmedStr))return str;if("0"===str)return 0;if(options.hex&&hexRegex.test(trimmedStr))return function parse_int(numStr,base){if(parseInt)return parseInt(numStr,base);if(Number.parseInt)return Number.parseInt(numStr,base);if(window&&window.parseInt)return window.parseInt(numStr,base);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(trimmedStr,16);if(-1!==trimmedStr.search(/[eE]/)){const notation=trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(notation){if(options.leadingZeros)trimmedStr=(notation[1]||"")+notation[3];else if("0"!==notation[2]||"."!==notation[3][0])return str;return options.eNotation?Number(trimmedStr):str}return str}{const match3=numRegex.exec(trimmedStr);if(match3){const sign2=match3[1],leadingZeros=match3[2];let numTrimmedByZeros=function trimZeros(numStr){if(numStr&&-1!==numStr.indexOf(".")){"."===(numStr=numStr.replace(/0+$/,""))?numStr="0":"."===numStr[0]?numStr="0"+numStr:"."===numStr[numStr.length-1]&&(numStr=numStr.substr(0,numStr.length-1));return numStr}return numStr}(match3[3]);if(!options.leadingZeros&&leadingZeros.length>0&&sign2&&"."!==trimmedStr[2])return str;if(!options.leadingZeros&&leadingZeros.length>0&&!sign2&&"."!==trimmedStr[1])return str;if(options.leadingZeros&&leadingZeros===str)return 0;{const num=Number(trimmedStr),numStr=""+num;return-1!==numStr.search(/[eE]/)?options.eNotation?num:str:-1!==trimmedStr.indexOf(".")?"0"===numStr&&""===numTrimmedByZeros||numStr===numTrimmedByZeros||sign2&&numStr==="-"+numTrimmedByZeros?num:str:leadingZeros?numTrimmedByZeros===numStr||sign2+numTrimmedByZeros===numStr?num:str:trimmedStr===numStr||trimmedStr===sign2+numStr?num:str}}return str}}}}),require_OrderedObjParser=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports,module2){"use strict";function addExternalEntities(externalEntities){const entKeys=Object.keys(externalEntities);for(let i2=0;i20){escapeEntities||(val2=this.replaceEntitiesValue(val2));const newval=this.options.tagValueProcessor(tagName,val2,jPath,hasAttributes,isLeafNode);return null==newval?val2:typeof newval!=typeof val2||newval!==val2?newval:this.options.trimValues||val2.trim()===val2?parseValue(val2,this.options.parseTagValue,this.options.numberParseOptions):val2}}}function resolveNameSpace(tagname){if(this.options.removeNSPrefix){const tags=tagname.split(":"),prefix="/"===tagname.charAt(0)?"/":"";if("xmlns"===tags[0])return"";2===tags.length&&(tagname=prefix+tags[1])}return tagname}function buildAttributesMap(attrStr,jPath,tagName){if(!this.options.ignoreAttributes&&"string"==typeof attrStr){const matches=util.getAllMatches(attrStr,attrsRegx),len=matches.length,attrs={};for(let i2=0;i2",i2,`${tagName} is not closed`);if(xmlData.substring(i2+2,closeIndex).trim()===tagName){openTagCount--;if(0===openTagCount)return{tagContent:xmlData.substring(startIndex,i2),i:closeIndex}}i2=closeIndex}else if("?"===xmlData[i2+1])i2=findClosingIndex(xmlData,"?>",i2+1,"StopNode is not closed.");else if("!--"===xmlData.substr(i2+1,3))i2=findClosingIndex(xmlData,"--\x3e",i2+3,"StopNode is not closed.");else if("!["===xmlData.substr(i2+1,2))i2=findClosingIndex(xmlData,"]]>",i2,"StopNode is not closed.")-2;else{const tagData=readTagExp(xmlData,i2,">");if(tagData){(tagData&&tagData.tagName)===tagName&&"/"!==tagData.tagExp[tagData.tagExp.length-1]&&openTagCount++;i2=tagData.closeIndex}}}function parseValue(val2,shouldParse,options){if(shouldParse&&"string"==typeof val2){const newval=val2.trim();return"true"===newval||"false"!==newval&&toNumber(val2,options)}return util.isExist(val2)?val2:""}var util=require_util(),xmlNode=require_xmlNode(),readDocType=require_DocTypeReader(),toNumber=require_strnum(),attrsRegx=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm"),parseXml=function(xmlData){xmlData=xmlData.replace(/\r\n?/g,"\n");const xmlObj=new xmlNode("!xml");let currentNode=xmlObj,textData="",jPath="";for(let i2=0;i2",i2,"Closing Tag is not closed.");let tagName=xmlData.substring(i2+2,closeIndex).trim();if(this.options.removeNSPrefix){const colonIndex=tagName.indexOf(":");-1!==colonIndex&&(tagName=tagName.substr(colonIndex+1))}this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));currentNode&&(textData=this.saveTextToParentTag(textData,currentNode,jPath));const lastTagName=jPath.substring(jPath.lastIndexOf(".")+1);if(tagName&&-1!==this.options.unpairedTags.indexOf(tagName))throw new Error(`Unpaired tag can not be used as closing tag: `);let propIndex=0;if(lastTagName&&-1!==this.options.unpairedTags.indexOf(lastTagName)){propIndex=jPath.lastIndexOf(".",jPath.lastIndexOf(".")-1);this.tagsNodeStack.pop()}else propIndex=jPath.lastIndexOf(".");jPath=jPath.substring(0,propIndex);currentNode=this.tagsNodeStack.pop();textData="";i2=closeIndex}else if("?"===xmlData[i2+1]){let tagData=readTagExp(xmlData,i2,!1,"?>");if(!tagData)throw new Error("Pi Tag is not closed.");textData=this.saveTextToParentTag(textData,currentNode,jPath);if(this.options.ignoreDeclaration&&"?xml"===tagData.tagName||this.options.ignorePiTags);else{const childNode=new xmlNode(tagData.tagName);childNode.add(this.options.textNodeName,"");tagData.tagName!==tagData.tagExp&&tagData.attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagData.tagExp,jPath,tagData.tagName));this.addChild(currentNode,childNode,jPath)}i2=tagData.closeIndex+1}else if("!--"===xmlData.substr(i2+1,3)){const endIndex=findClosingIndex(xmlData,"--\x3e",i2+4,"Comment is not closed.");if(this.options.commentPropName){const comment2=xmlData.substring(i2+4,endIndex-2);textData=this.saveTextToParentTag(textData,currentNode,jPath);currentNode.add(this.options.commentPropName,[{[this.options.textNodeName]:comment2}])}i2=endIndex}else if("!D"===xmlData.substr(i2+1,2)){const result=readDocType(xmlData,i2);this.docTypeEntities=result.entities;i2=result.i}else if("!["===xmlData.substr(i2+1,2)){const closeIndex=findClosingIndex(xmlData,"]]>",i2,"CDATA is not closed.")-2,tagExp=xmlData.substring(i2+9,closeIndex);textData=this.saveTextToParentTag(textData,currentNode,jPath);let val2=this.parseTextData(tagExp,currentNode.tagname,jPath,!0,!1,!0,!0);null==val2&&(val2="");this.options.cdataPropName?currentNode.add(this.options.cdataPropName,[{[this.options.textNodeName]:tagExp}]):currentNode.add(this.options.textNodeName,val2);i2=closeIndex+2}else{let result=readTagExp(xmlData,i2,this.options.removeNSPrefix),tagName=result.tagName;const rawTagName=result.rawTagName;let tagExp=result.tagExp,attrExpPresent=result.attrExpPresent,closeIndex=result.closeIndex;this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));currentNode&&textData&&"!xml"!==currentNode.tagname&&(textData=this.saveTextToParentTag(textData,currentNode,jPath,!1));const lastTag=currentNode;if(lastTag&&-1!==this.options.unpairedTags.indexOf(lastTag.tagname)){currentNode=this.tagsNodeStack.pop();jPath=jPath.substring(0,jPath.lastIndexOf("."))}tagName!==xmlObj.tagname&&(jPath+=jPath?"."+tagName:tagName);if(this.isItStopNode(this.options.stopNodes,jPath,tagName)){let tagContent="";if(tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1){if("/"===tagName[tagName.length-1]){tagName=tagName.substr(0,tagName.length-1);jPath=jPath.substr(0,jPath.length-1);tagExp=tagName}else tagExp=tagExp.substr(0,tagExp.length-1);i2=result.closeIndex}else if(-1!==this.options.unpairedTags.indexOf(tagName))i2=result.closeIndex;else{const result2=this.readStopNodeData(xmlData,rawTagName,closeIndex+1);if(!result2)throw new Error(`Unexpected end of ${rawTagName}`);i2=result2.i;tagContent=result2.tagContent}const childNode=new xmlNode(tagName);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));tagContent&&(tagContent=this.parseTextData(tagContent,tagName,jPath,!0,attrExpPresent,!0,!0));jPath=jPath.substr(0,jPath.lastIndexOf("."));childNode.add(this.options.textNodeName,tagContent);this.addChild(currentNode,childNode,jPath)}else{if(tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1){if("/"===tagName[tagName.length-1]){tagName=tagName.substr(0,tagName.length-1);jPath=jPath.substr(0,jPath.length-1);tagExp=tagName}else tagExp=tagExp.substr(0,tagExp.length-1);this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));const childNode=new xmlNode(tagName);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));this.addChild(currentNode,childNode,jPath);jPath=jPath.substr(0,jPath.lastIndexOf("."))}else{const childNode=new xmlNode(tagName);this.tagsNodeStack.push(currentNode);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));this.addChild(currentNode,childNode,jPath);currentNode=childNode}textData="";i2=closeIndex}}else textData+=xmlData[i2];return xmlObj.child},replaceEntitiesValue=function(val2){if(this.options.processEntities){for(let entityName2 in this.docTypeEntities){const entity=this.docTypeEntities[entityName2];val2=val2.replace(entity.regx,entity.val)}for(let entityName2 in this.lastEntities){const entity=this.lastEntities[entityName2];val2=val2.replace(entity.regex,entity.val)}if(this.options.htmlEntities)for(let entityName2 in this.htmlEntities){const entity=this.htmlEntities[entityName2];val2=val2.replace(entity.regex,entity.val)}val2=val2.replace(this.ampEntity.regex,this.ampEntity.val)}return val2};module2.exports=class{constructor(options){this.options=options;this.currentNode=null;this.tagsNodeStack=[];this.docTypeEntities={};this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}};this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"};this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(_,str)=>String.fromCharCode(Number.parseInt(str,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(_,str)=>String.fromCharCode(Number.parseInt(str,16))}};this.addExternalEntities=addExternalEntities;this.parseXml=parseXml;this.parseTextData=parseTextData;this.resolveNameSpace=resolveNameSpace;this.buildAttributesMap=buildAttributesMap;this.isItStopNode=isItStopNode;this.replaceEntitiesValue=replaceEntitiesValue;this.readStopNodeData=readStopNodeData;this.saveTextToParentTag=saveTextToParentTag;this.addChild=addChild}}}}),require_node2json=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports){"use strict";function compress(arr,options,jPath){let text2;const compressedObj={};for(let i2=0;i20&&(compressedObj[options.textNodeName]=text2):void 0!==text2&&(compressedObj[options.textNodeName]=text2);return compressedObj}function propName(obj){const keys3=Object.keys(obj);for(let i2=0;i2`;isPreviousElementTag=!1;continue}if(tagName===options.commentPropName){xmlStr+=indentation+`\x3c!--${tagObj[tagName][0][options.textNodeName]}--\x3e`;isPreviousElementTag=!0;continue}if("?"===tagName[0]){const attStr2=attr_to_str(tagObj[":@"],options),tempInd="?xml"===tagName?"":indentation;let piTextNodeName=tagObj[tagName][0][options.textNodeName];piTextNodeName=0!==piTextNodeName.length?" "+piTextNodeName:"";xmlStr+=tempInd+`<${tagName}${piTextNodeName}${attStr2}?>`;isPreviousElementTag=!0;continue}let newIdentation=indentation;""!==newIdentation&&(newIdentation+=options.indentBy);const tagStart=indentation+`<${tagName}${attr_to_str(tagObj[":@"],options)}`,tagValue=arrToStr(tagObj[tagName],options,newJPath,newIdentation);if(-1!==options.unpairedTags.indexOf(tagName))options.suppressUnpairedNode?xmlStr+=tagStart+">":xmlStr+=tagStart+"/>";else if(tagValue&&0!==tagValue.length||!options.suppressEmptyNode)if(tagValue&&tagValue.endsWith(">"))xmlStr+=tagStart+`>${tagValue}${indentation}`;else{xmlStr+=tagStart+">";tagValue&&""!==indentation&&(tagValue.includes("/>")||tagValue.includes("`}else xmlStr+=tagStart+"/>";isPreviousElementTag=!0}return xmlStr}function propName(obj){const keys3=Object.keys(obj);for(let i2=0;i20&&options.processEntities)for(let i2=0;i20&&(indentation="\n");return arrToStr(jArray,options,"",indentation)}}}),require_json2xml=__commonJS({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports,module2){"use strict";function Builder(options){this.options=Object.assign({},defaultOptions,options);if(this.options.ignoreAttributes||this.options.attributesGroupName)this.isAttribute=function(){return!1};else{this.attrPrefixLen=this.options.attributeNamePrefix.length;this.isAttribute=isAttribute}this.processTextOrObjNode=processTextOrObjNode;if(this.options.format){this.indentate=indentate;this.tagEndChar=">\n";this.newLine="\n"}else{this.indentate=function(){return""};this.tagEndChar=">";this.newLine=""}}function processTextOrObjNode(object,key2,level){const result=this.j2x(object,level+1);return void 0!==object[this.options.textNodeName]&&1===Object.keys(object).length?this.buildTextValNode(object[this.options.textNodeName],key2,result.attrStr,level):this.buildObjectNode(result.val,key2,result.attrStr,level)}function indentate(level){return this.options.indentBy.repeat(level)}function isAttribute(name){return!(!name.startsWith(this.options.attributeNamePrefix)||name===this.options.textNodeName)&&name.substr(this.attrPrefixLen)}var buildFromOrderedJs=require_orderedJs2Xml(),defaultOptions={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(key2,a2){return a2},attributeValueProcessor:function(attrName,a2){return a2},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};Builder.prototype.build=function(jObj){if(this.options.preserveOrder)return buildFromOrderedJs(jObj,this.options);Array.isArray(jObj)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(jObj={[this.options.arrayNodeName]:jObj});return this.j2x(jObj,0).val};Builder.prototype.j2x=function(jObj,level){let attrStr="",val2="";for(let key2 in jObj)if(Object.prototype.hasOwnProperty.call(jObj,key2))if(void 0===jObj[key2])this.isAttribute(key2)&&(val2+="");else if(null===jObj[key2])this.isAttribute(key2)?val2+="":"?"===key2[0]?val2+=this.indentate(level)+"<"+key2+"?"+this.tagEndChar:val2+=this.indentate(level)+"<"+key2+"/"+this.tagEndChar;else if(jObj[key2]instanceof Date)val2+=this.buildTextValNode(jObj[key2],key2,"",level);else if("object"!=typeof jObj[key2]){const attr2=this.isAttribute(key2);if(attr2)attrStr+=this.buildAttrPairStr(attr2,""+jObj[key2]);else if(key2===this.options.textNodeName){let newval=this.options.tagValueProcessor(key2,""+jObj[key2]);val2+=this.replaceEntitiesValue(newval)}else val2+=this.buildTextValNode(jObj[key2],key2,"",level)}else if(Array.isArray(jObj[key2])){const arrLen=jObj[key2].length;let listTagVal="",listTagAttr="";for(let j2=0;j2"+val2+tagEndExp}};Builder.prototype.closeTag=function(key2){let closeTag="";-1!==this.options.unpairedTags.indexOf(key2)?this.options.suppressUnpairedNode||(closeTag="/"):closeTag=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&key2===this.options.commentPropName)return this.indentate(level)+`\x3c!--${val2}--\x3e`+this.newLine;if("?"===key2[0])return this.indentate(level)+"<"+key2+attrStr+"?"+this.tagEndChar;{let textValue=this.options.tagValueProcessor(key2,val2);textValue=this.replaceEntitiesValue(textValue);return""===textValue?this.indentate(level)+"<"+key2+attrStr+this.closeTag(key2)+this.tagEndChar:this.indentate(level)+"<"+key2+attrStr+">"+textValue+"0&&this.options.processEntities)for(let i2=0;i20&&r5[1]||""},e4.getSecondMatch=function(e5,t4){var r5=t4.match(e5);return r5&&r5.length>1&&r5[2]||""},e4.matchAndReturnConst=function(e5,t4,r5){if(e5.test(t4))return r5},e4.getWindowsVersionName=function(e5){switch(e5){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e4.getMacOSVersionName=function(e5){var t4=e5.split(".").splice(0,2).map((function(e6){return parseInt(e6,10)||0}));if(t4.push(0),10===t4[0])switch(t4[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e4.getAndroidVersionName=function(e5){var t4=e5.split(".").splice(0,2).map((function(e6){return parseInt(e6,10)||0}));if(t4.push(0),!(1===t4[0]&&t4[1]<5))return 1===t4[0]&&t4[1]<6?"Cupcake":1===t4[0]&&t4[1]>=6?"Donut":2===t4[0]&&t4[1]<2?"Eclair":2===t4[0]&&2===t4[1]?"Froyo":2===t4[0]&&t4[1]>2?"Gingerbread":3===t4[0]?"Honeycomb":4===t4[0]&&t4[1]<1?"Ice Cream Sandwich":4===t4[0]&&t4[1]<4?"Jelly Bean":4===t4[0]&&t4[1]>=4?"KitKat":5===t4[0]?"Lollipop":6===t4[0]?"Marshmallow":7===t4[0]?"Nougat":8===t4[0]?"Oreo":9===t4[0]?"Pie":void 0},e4.getVersionPrecision=function(e5){return e5.split(".").length},e4.compareVersions=function(t4,r5,n4){void 0===n4&&(n4=!1);var i3=e4.getVersionPrecision(t4),s2=e4.getVersionPrecision(r5),a2=Math.max(i3,s2),o2=0,u2=e4.map([t4,r5],(function(t5){var r6=a2-e4.getVersionPrecision(t5),n5=t5+new Array(r6+1).join(".0");return e4.map(n5.split("."),(function(e5){return new Array(20-e5.length).join("0")+e5})).reverse()}));for(n4&&(o2=a2-Math.min(i3,s2)),a2-=1;a2>=o2;){if(u2[0][a2]>u2[1][a2])return 1;if(u2[0][a2]===u2[1][a2]){if(a2===o2)return 0;a2-=1}else if(u2[0][a2]1?i3-1:0),a2=1;a20){a3=Object.keys(r5);if((u3=o2.default.find(a3,(function(e6){return t5.isOS(e6)})))&&void 0!==(d5=this.satisfies(r5[u3])))return d5;if((c3=o2.default.find(a3,(function(e6){return t5.isPlatform(e6)})))&&void 0!==(f4=this.satisfies(r5[c3])))return f4}if(s3>0){l2=Object.keys(i3);if(void 0!==(h3=o2.default.find(l2,(function(e6){return t5.isBrowser(e6,!0)}))))return this.compareVersion(i3[h3])}},t4.isBrowser=function(e5,t5){void 0===t5&&(t5=!1);var r5=this.getBrowserName().toLowerCase(),n4=e5.toLowerCase(),i3=o2.default.getBrowserTypeByAlias(n4);return t5&&i3&&(n4=i3.toLowerCase()),n4===r5},t4.compareVersion=function(e5){var t5=[0],r5=e5,n4=!1,i3=this.getBrowserVersion();if("string"==typeof i3)return">"===e5[0]||"<"===e5[0]?(r5=e5.substr(1),"="===e5[1]?(n4=!0,r5=e5.substr(2)):t5=[],">"===e5[0]?t5.push(1):t5.push(-1)):"="===e5[0]?r5=e5.substr(1):"~"===e5[0]&&(n4=!0,r5=e5.substr(1)),t5.indexOf(o2.default.compareVersions(i3,r5,n4))>-1},t4.isOS=function(e5){return this.getOSName(!0)===String(e5).toLowerCase()},t4.isPlatform=function(e5){return this.getPlatformType(!0)===String(e5).toLowerCase()},t4.isEngine=function(e5){return this.getEngineName(!0)===String(e5).toLowerCase()},t4.is=function(e5,t5){return void 0===t5&&(t5=!1),this.isBrowser(e5,t5)||this.isOS(e5)||this.isPlatform(e5)},t4.some=function(e5){var t5=this;return void 0===e5&&(e5=[]),e5.some((function(e6){return t5.is(e6)}))},e4}();t3.default=d4,e3.exports=t3.default},92:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3};s2=/version\/(\d+(\.?_?\d+)+)/i,a2=[{test:[/googlebot/i],describe:function(e4){var t4={name:"Googlebot"},r5=i2.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/opera/i],describe:function(e4){var t4={name:"Opera"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/opr\/|opios/i],describe:function(e4){var t4={name:"Opera"},r5=i2.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/SamsungBrowser/i],describe:function(e4){var t4={name:"Samsung Internet for Android"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/Whale/i],describe:function(e4){var t4={name:"NAVER Whale Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/MZBrowser/i],describe:function(e4){var t4={name:"MZ Browser"},r5=i2.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/focus/i],describe:function(e4){var t4={name:"Focus"},r5=i2.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/swing/i],describe:function(e4){var t4={name:"Swing"},r5=i2.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/coast/i],describe:function(e4){var t4={name:"Opera Coast"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e4){var t4={name:"Opera Touch"},r5=i2.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/yabrowser/i],describe:function(e4){var t4={name:"Yandex Browser"},r5=i2.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/ucbrowser/i],describe:function(e4){var t4={name:"UC Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/Maxthon|mxios/i],describe:function(e4){var t4={name:"Maxthon"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/epiphany/i],describe:function(e4){var t4={name:"Epiphany"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/puffin/i],describe:function(e4){var t4={name:"Puffin"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/sleipnir/i],describe:function(e4){var t4={name:"Sleipnir"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/k-meleon/i],describe:function(e4){var t4={name:"K-Meleon"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/micromessenger/i],describe:function(e4){var t4={name:"WeChat"},r5=i2.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/qqbrowser/i],describe:function(e4){var t4={name:/qqbrowserlite/i.test(e4)?"QQ Browser Lite":"QQ Browser"},r5=i2.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/msie|trident/i],describe:function(e4){var t4={name:"Internet Explorer"},r5=i2.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/\sedg\//i],describe:function(e4){var t4={name:"Microsoft Edge"},r5=i2.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/edg([ea]|ios)/i],describe:function(e4){var t4={name:"Microsoft Edge"},r5=i2.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/vivaldi/i],describe:function(e4){var t4={name:"Vivaldi"},r5=i2.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/seamonkey/i],describe:function(e4){var t4={name:"SeaMonkey"},r5=i2.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/sailfish/i],describe:function(e4){var t4={name:"Sailfish"},r5=i2.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/silk/i],describe:function(e4){var t4={name:"Amazon Silk"},r5=i2.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/phantom/i],describe:function(e4){var t4={name:"PhantomJS"},r5=i2.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/slimerjs/i],describe:function(e4){var t4={name:"SlimerJS"},r5=i2.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e4){var t4={name:"BlackBerry"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/(web|hpw)[o0]s/i],describe:function(e4){var t4={name:"WebOS Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/bada/i],describe:function(e4){var t4={name:"Bada"},r5=i2.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/tizen/i],describe:function(e4){var t4={name:"Tizen"},r5=i2.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/qupzilla/i],describe:function(e4){var t4={name:"QupZilla"},r5=i2.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/firefox|iceweasel|fxios/i],describe:function(e4){var t4={name:"Firefox"},r5=i2.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/electron/i],describe:function(e4){var t4={name:"Electron"},r5=i2.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/MiuiBrowser/i],describe:function(e4){var t4={name:"Miui"},r5=i2.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/chromium/i],describe:function(e4){var t4={name:"Chromium"},r5=i2.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/chrome|crios|crmo/i],describe:function(e4){var t4={name:"Chrome"},r5=i2.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/GSA/i],describe:function(e4){var t4={name:"Google Search"},r5=i2.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){var t4=!e4.test(/like android/i),r5=e4.test(/android/i);return t4&&r5},describe:function(e4){var t4={name:"Android Browser"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/playstation 4/i],describe:function(e4){var t4={name:"PlayStation 4"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/safari|applewebkit/i],describe:function(e4){var t4={name:"Safari"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/.*/i],describe:function(e4){var t4=-1!==e4.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i2.default.getFirstMatch(t4,e4),version:i2.default.getSecondMatch(t4,e4)}}}];t3.default=a2,e3.exports=t3.default},93:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:[/Roku\/DVP/],describe:function(e4){var t4=i2.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e4);return{name:s2.OS_MAP.Roku,version:t4}}},{test:[/windows phone/i],describe:function(e4){var t4=i2.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.WindowsPhone,version:t4}}},{test:[/windows /i],describe:function(e4){var t4=i2.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e4),r5=i2.default.getWindowsVersionName(t4);return{name:s2.OS_MAP.Windows,version:t4,versionName:r5}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e4){var t4={name:s2.OS_MAP.iOS},r5=i2.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e4);return r5&&(t4.version=r5),t4}},{test:[/macintosh/i],describe:function(e4){var t4=i2.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e4).replace(/[_\s]/g,"."),r5=i2.default.getMacOSVersionName(t4),n4={name:s2.OS_MAP.MacOS,version:t4};return r5&&(n4.versionName=r5),n4}},{test:[/(ipod|iphone|ipad)/i],describe:function(e4){var t4=i2.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e4).replace(/[_\s]/g,".");return{name:s2.OS_MAP.iOS,version:t4}}},{test:function(e4){var t4=!e4.test(/like android/i),r5=e4.test(/android/i);return t4&&r5},describe:function(e4){var t4=i2.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e4),r5=i2.default.getAndroidVersionName(t4),n4={name:s2.OS_MAP.Android,version:t4};return r5&&(n4.versionName=r5),n4}},{test:[/(web|hpw)[o0]s/i],describe:function(e4){var t4=i2.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e4),r5={name:s2.OS_MAP.WebOS};return t4&&t4.length&&(r5.version=t4),r5}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e4){var t4=i2.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e4)||i2.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e4)||i2.default.getFirstMatch(/\bbb(\d+)/i,e4);return{name:s2.OS_MAP.BlackBerry,version:t4}}},{test:[/bada/i],describe:function(e4){var t4=i2.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.Bada,version:t4}}},{test:[/tizen/i],describe:function(e4){var t4=i2.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.Tizen,version:t4}}},{test:[/linux/i],describe:function(){return{name:s2.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s2.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e4){var t4=i2.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.PlayStation4,version:t4}}}];t3.default=a2,e3.exports=t3.default},94:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e4){var t4=i2.default.getFirstMatch(/(can-l01)/i,e4)&&"Nova",r5={type:s2.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t4&&(r5.model=t4),r5}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet}}},{test:function(e4){var t4=e4.test(/ipod|iphone/i),r5=e4.test(/like (ipod|iphone)/i);return t4&&!r5},describe:function(e4){var t4=i2.default.getFirstMatch(/(ipod|iphone)/i,e4);return{type:s2.PLATFORMS_MAP.mobile,vendor:"Apple",model:t4}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"blackberry"===e4.getBrowserName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e4){return"bada"===e4.getBrowserName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"windows phone"===e4.getBrowserName()},describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e4){var t4=Number(String(e4.getOSVersion()).split(".")[0]);return"android"===e4.getOSName(!0)&&t4>=3},describe:function(){return{type:s2.PLATFORMS_MAP.tablet}}},{test:function(e4){return"android"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"macos"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e4){return"windows"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop}}},{test:function(e4){return"linux"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop}}},{test:function(e4){return"playstation 4"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.tv}}},{test:function(e4){return"roku"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.tv}}}];t3.default=a2,e3.exports=t3.default},95:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:function(e4){return"microsoft edge"===e4.getBrowserName(!0)},describe:function(e4){if(/\sedg\//i.test(e4))return{name:s2.ENGINE_MAP.Blink};var t4=i2.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e4);return{name:s2.ENGINE_MAP.EdgeHTML,version:t4}}},{test:[/trident/i],describe:function(e4){var t4={name:s2.ENGINE_MAP.Trident},r5=i2.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){return e4.test(/presto/i)},describe:function(e4){var t4={name:s2.ENGINE_MAP.Presto},r5=i2.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){var t4=e4.test(/gecko/i),r5=e4.test(/like gecko/i);return t4&&!r5},describe:function(e4){var t4={name:s2.ENGINE_MAP.Gecko},r5=i2.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s2.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e4){var t4={name:s2.ENGINE_MAP.WebKit},r5=i2.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}}];t3.default=a2,e3.exports=t3.default}})},"object"==typeof exports&&"object"==typeof module2?module2.exports=t3():"function"==typeof define&&define.amd?define([],t3):"object"==typeof exports?exports.bowser=t3():e3.bowser=t3();var e3,t3}}),require_qrcode=__commonJS({"node_modules/qrcode-generator/qrcode.js"(exports,module2){var factory,qrcode2=function(){function qrPolynomial(num,shift){var _num,_this;if(void 0===num.length)throw num.length+"/"+shift;_num=function(){for(var _num2,i2,offset=0;offset=7&&setupTypeNumber(test);null==_dataCache&&(_dataCache=createData(_typeNumber,_errorCorrectionLevel,_dataList));mapData(_dataCache,maskPattern)},setupPositionProbePattern=function(row,col){var r4,c3;for(r4=-1;r4<=7;r4+=1)if(!(row+r4<=-1||_moduleCount<=row+r4))for(c3=-1;c3<=7;c3+=1)col+c3<=-1||_moduleCount<=col+c3||(_modules[row+r4][col+c3]=0<=r4&&r4<=6&&(0==c3||6==c3)||0<=c3&&c3<=6&&(0==r4||6==r4)||2<=r4&&r4<=4&&2<=c3&&c3<=4)},setupTimingPattern=function(){var r4,c3;for(r4=8;r4<_moduleCount-8;r4+=1)null==_modules[r4][6]&&(_modules[r4][6]=r4%2==0);for(c3=8;c3<_moduleCount-8;c3+=1)null==_modules[6][c3]&&(_modules[6][c3]=c3%2==0)},setupPositionAdjustPattern=function(){var i2,j2,row,col,r4,c3,pos=QRUtil.getPatternPosition(_typeNumber);for(i2=0;i2>i2&1);_modules[Math.floor(i2/3)][i2%3+_moduleCount-8-3]=mod2}for(i2=0;i2<18;i2+=1){mod2=!test&&1==(bits2>>i2&1);_modules[i2%3+_moduleCount-8-3][Math.floor(i2/3)]=mod2}},setupTypeInfo=function(test,maskPattern){var i2,mod2,data=_errorCorrectionLevel<<3|maskPattern,bits2=QRUtil.getBCHTypeInfo(data);for(i2=0;i2<15;i2+=1){mod2=!test&&1==(bits2>>i2&1);i2<6?_modules[i2][8]=mod2:i2<8?_modules[i2+1][8]=mod2:_modules[_moduleCount-15+i2][8]=mod2}for(i2=0;i2<15;i2+=1){mod2=!test&&1==(bits2>>i2&1);i2<8?_modules[8][_moduleCount-i2-1]=mod2:i2<9?_modules[8][15-i2-1+1]=mod2:_modules[8][15-i2-1]=mod2}_modules[_moduleCount-8][8]=!test},mapData=function(data,maskPattern){var col,c3,dark,inc=-1,row=_moduleCount-1,bitIndex=7,byteIndex=0,maskFunc=QRUtil.getMaskFunction(maskPattern);for(col=_moduleCount-1;col>0;col-=2){6==col&&(col-=1);for(;;){for(c3=0;c3<2;c3+=1)if(null==_modules[row][col-c3]){dark=!1;byteIndex>>bitIndex&1));maskFunc(row,col-c3)&&(dark=!dark);_modules[row][col-c3]=dark;if(-1==(bitIndex-=1)){byteIndex+=1;bitIndex=7}}if((row+=inc)<0||_moduleCount<=row){row-=inc;inc=-inc;break}}}},createData=function(typeNumber2,errorCorrectionLevel2,dataList){var i2,data,totalDataCount,rsBlocks=QRRSBlock.getRSBlocks(typeNumber2,errorCorrectionLevel2),buffer=qrBitBuffer();for(i2=0;i28*totalDataCount)throw"code length overflow. ("+buffer.getLengthInBits()+">"+8*totalDataCount+")";buffer.getLengthInBits()+4<=8*totalDataCount&&buffer.put(0,4);for(;buffer.getLengthInBits()%8!=0;)buffer.putBit(!1);for(;!(buffer.getLengthInBits()>=8*totalDataCount);){buffer.put(236,8);if(buffer.getLengthInBits()>=8*totalDataCount)break;buffer.put(17,8)}return function(buffer,rsBlocks){var r4,dcCount,ecCount,i2,rsPoly,modPoly,modIndex,totalCodeCount,data,index6,offset=0,maxDcCount=0,maxEcCount=0,dcdata=new Array(rsBlocks.length),ecdata=new Array(rsBlocks.length);for(r4=0;r4=0?modPoly.getAt(modIndex):0}}totalCodeCount=0;for(i2=0;i2lostPoint){minLostPoint=lostPoint;pattern=i2}}return pattern}())};_this.createTableTag=function(cellSize,margin){var qrHtml,r4,c3;cellSize=cellSize||2;qrHtml="";qrHtml+='';qrHtml+="";for(r4=0;r4<_this.getModuleCount();r4+=1){qrHtml+="";for(c3=0;c3<_this.getModuleCount();c3+=1){qrHtml+='"}return(qrHtml+="")+"
'}qrHtml+="
"};_this.createSvgTag=function(cellSize,margin,alt,title){var size,c3,r4,mr,qrSvg,rect,opts={};if("object"==typeof arguments[0]){cellSize=(opts=arguments[0]).cellSize;margin=opts.margin;alt=opts.alt;title=opts.title}cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;(alt="string"==typeof alt?{text:alt}:alt||{}).text=alt.text||null;alt.id=alt.text?alt.id||"qrcode-description":null;(title="string"==typeof title?{text:title}:title||{}).text=title.text||null;title.id=title.text?title.id||"qrcode-title":null;size=_this.getModuleCount()*cellSize+2*margin;qrSvg="";rect="l"+cellSize+",0 0,"+cellSize+" -"+cellSize+",0 0,-"+cellSize+"z ";qrSvg+=''+escapeXml(title.text)+"":"";qrSvg+=alt.text?''+escapeXml(alt.text)+"":"";qrSvg+='';qrSvg+='"};_this.createDataURL=function(cellSize,margin){var size,min,max3;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;min=margin;max3=size-margin;return createDataURL(size,size,(function(x2,y2){var c3,r4;if(min<=x2&&x2"};escapeXml=function(s2){var i2,c3,escaped="";for(i2=0;i2":escaped+=">";break;case"&":escaped+="&";break;case'"':escaped+=""";break;default:escaped+=c3;break}return escaped};_createHalfASCII=function(margin){var size,min,max3,y2,x2,r12,r22,p4,blocks,blocksLastLineNoMargin,ascii;min=margin=void 0===margin?2:margin;max3=(size=1*_this.getModuleCount()+2*margin)-margin;blocks={"██":"█","█ ":"▀"," █":"▄"," ":" "};blocksLastLineNoMargin={"██":"▀","█ ":"▀"," █":" "," ":" "};ascii="";for(y2=0;y2=max3?blocksLastLineNoMargin[p4]:blocks[p4]}ascii+="\n"}return size%2&&margin>0?ascii.substring(0,ascii.length-size-1)+Array(size+1).join("▀"):ascii.substring(0,ascii.length-1)};_this.createASCII=function(cellSize,margin){var size,min,max3,y2,x2,r4,p4,white,black,ascii,line;if((cellSize=cellSize||1)<2)return _createHalfASCII(margin);cellSize-=1;min=margin=void 0===margin?2*cellSize:margin;max3=(size=_this.getModuleCount()*cellSize+2*margin)-margin;white=Array(cellSize+1).join("██");black=Array(cellSize+1).join(" ");ascii="";line="";for(y2=0;y2>>8);bytes.push(255&b3)}else bytes.push(unknownChar);return bytes}};QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2};QRUtil=function(){var PATTERN_POSITION_TABLE=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],_this={},getBCHDigit=function(data){for(var digit=0;0!=data;){digit+=1;data>>>=1}return digit};_this.getBCHTypeInfo=function(data){for(var d4=data<<10;getBCHDigit(d4)-getBCHDigit(1335)>=0;)d4^=1335<=0;)d4^=7973<5&&(lostPoint+=3+sameCount-5)}for(row=0;row=256;)n3-=255;return EXP_TABLE[n3]};return _this}();QRRSBlock=(RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],qrRSBlock=function(totalCount,dataCount){var _this2={};_this2.totalCount=totalCount;_this2.dataCount=dataCount;return _this2},_this={getRSBlocks:function(typeNumber,errorCorrectionLevel){var length,list,i2,count,totalCount,dataCount,j2,rsBlock=function(typeNumber,errorCorrectionLevel){switch(errorCorrectionLevel){case QRErrorCorrectionLevel.L:return RS_BLOCK_TABLE[4*(typeNumber-1)+0];case QRErrorCorrectionLevel.M:return RS_BLOCK_TABLE[4*(typeNumber-1)+1];case QRErrorCorrectionLevel.Q:return RS_BLOCK_TABLE[4*(typeNumber-1)+2];case QRErrorCorrectionLevel.H:return RS_BLOCK_TABLE[4*(typeNumber-1)+3];default:return}}(typeNumber,errorCorrectionLevel);if(void 0===rsBlock)throw"bad rs block @ typeNumber:"+typeNumber+"/errorCorrectionLevel:"+errorCorrectionLevel;length=rsBlock.length/3;list=[];for(i2=0;i2>>7-index6%8&1)},put:function(num,length){for(var i2=0;i2>>length-i2-1&1))},getLengthInBits:function(){return _length},putBit:function(bit){var bufIndex=Math.floor(_length/8);_buffer.length<=bufIndex&&_buffer.push(0);bit&&(_buffer[bufIndex]|=128>>>_length%8);_length+=1}};return _this};qrNumber=function(data){var strToNum2,chatToNum,_data2=data,_this={getMode:function(){return 1},getLength:function(buffer){return _data2.length},write:function(buffer){for(var data2=_data2,i2=0;i2+2>>8&255)+(255&c3);buffer.put(c3,13);i2+=2}if(i2>>8)},writeBytes:function(b3,off,len){off=off||0;len=len||b3.length;for(var i2=0;i20&&(s2+=",");s2+=_bytes[i2]}return s2+"]"}};return _this};base64EncodeOutputStream=function(){var _buffer=0,_buflen=0,_length=0,_base64="",_this={},writeEncoded=function(b3){_base64+=String.fromCharCode(encode(63&b3))},encode=function(n3){if(n3<0);else{if(n3<26)return 65+n3;if(n3<52)return n3-26+97;if(n3<62)return n3-52+48;if(62==n3)return 43;if(63==n3)return 47}throw"n:"+n3};_this.writeByte=function(n3){_buffer=_buffer<<8|255&n3;_buflen+=8;_length+=1;for(;_buflen>=6;){writeEncoded(_buffer>>>_buflen-6);_buflen-=6}};_this.flush=function(){var padlen,i2;if(_buflen>0){writeEncoded(_buffer<<6-_buflen);_buffer=0;_buflen=0}if(_length%3!=0){padlen=3-_length%3;for(i2=0;i2=_str.length){if(0==_buflen)return-1;throw"unexpected end of file./"+_buflen}c3=_str.charAt(_pos);_pos+=1;if("="==c3){_buflen=0;return-1}if(!c3.match(/^\s$/)){_buffer=_buffer<<6|decode(c3.charCodeAt(0));_buflen+=6}}n3=_buffer>>>_buflen-8&255;_buflen-=8;return n3}};decode=function(c3){if(65<=c3&&c3<=90)return c3-65;if(97<=c3&&c3<=122)return c3-97+26;if(48<=c3&&c3<=57)return c3-48+52;if(43==c3)return 62;if(47==c3)return 63;throw"c:"+c3};return _this};gifImage=function(width,height){var bitOutputStream,getLZWRaster,lzwTable,_width=width,_height=height,_data2=new Array(width*height),_this={setPixel:function(x2,y2,pixel){_data2[y2*_width+x2]=pixel},write:function(out){var raster,offset;out.writeString("GIF87a");out.writeShort(_width);out.writeShort(_height);out.writeByte(128);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(255);out.writeByte(255);out.writeByte(255);out.writeString(",");out.writeShort(0);out.writeShort(0);out.writeShort(_width);out.writeShort(_height);out.writeByte(0);raster=getLZWRaster(2);out.writeByte(2);offset=0;for(;raster.length-offset>255;){out.writeByte(255);out.writeBytes(raster,offset,255);offset+=255}out.writeByte(raster.length-offset);out.writeBytes(raster,offset,raster.length-offset);out.writeByte(0);out.writeString(";")}};bitOutputStream=function(out){var _out=out,_bitLength=0,_bitBuffer=0;return{write:function(data,length){if(data>>>length!=0)throw"length over";for(;_bitLength+length>=8;){_out.writeByte(255&(data<<_bitLength|_bitBuffer));length-=8-_bitLength;data>>>=8-_bitLength;_bitBuffer=0;_bitLength=0}_bitBuffer|=data<<_bitLength;_bitLength+=length},flush:function(){_bitLength>0&&_out.writeByte(_bitBuffer)}}};getLZWRaster=function(lzwMinCodeSize){var i2,byteOut,bitOut,dataIndex,s2,c3,clearCode=1<>6,128|63&charcode);else if(charcode<55296||charcode>=57344)utf8.push(224|charcode>>12,128|charcode>>6&63,128|63&charcode);else{i2++;charcode=65536+((1023&charcode)<<10|1023&str.charCodeAt(i2));utf8.push(240|charcode>>18,128|charcode>>12&63,128|charcode>>6&63,128|63&charcode)}return utf8}(s2)};factory=function(){return qrcode2},"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports&&(module2.exports=factory())}}),require_events=__commonJS({"node_modules/events/events.js"(exports,module2){"use strict";function EventEmitter2(){EventEmitter2.init.call(this)}function checkListener(listener){if("function"!=typeof listener)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter2.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m3,events,existing,w2;checkListener(listener);if(void 0===(events=target._events)){events=target._events=Object.create(null);target._eventsCount=0}else{if(void 0!==events.newListener){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(void 0===existing){existing=events[type]=listener;++target._eventsCount}else{"function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener);if((m3=_getMaxListeners(target))>0&&existing.length>m3&&!existing.warned){existing.warned=!0;(w2=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning";w2.emitter=target;w2.type=type;w2.count=existing.length;(function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)})(w2)}}return target}function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=!0;return 0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state2={fired:!1,wrapFn:void 0,target,type,listener},wrapped=onceWrapper.bind(state2);wrapped.listener=listener;state2.wrapFn=wrapped;return wrapped}function _listeners2(target,type,unwrap2){var evlistener,events=target._events;return void 0===events||void 0===(evlistener=events[type])?[]:"function"==typeof evlistener?unwrap2?[evlistener.listener||evlistener]:[evlistener]:unwrap2?function unwrapListeners(arr){for(var ret=new Array(arr.length),i2=0;i20&&(er=args[0]);if(er instanceof Error)throw er;(err2=new Error("Unhandled error."+(er?" ("+er.message+")":""))).context=er;throw err2}if(void 0===(handler=events[type]))return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else{listeners=arrayClone(handler,len=handler.length);for(i2=0;i2=0;i2--)if(list[i2]===listener||list[i2].listener===listener){originalListener=list[i2].listener;position=i2;break}if(position<0)return this;0===position?list.shift():function spliceOne(list,index6){for(;index6+1=0;i2--)this.removeListener(type,listeners[i2]);return this};EventEmitter2.prototype.listeners=function listeners(type){return _listeners2(this,type,!0)};EventEmitter2.prototype.rawListeners=function rawListeners(type){return _listeners2(this,type,!1)};EventEmitter2.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount2.call(emitter,type)};EventEmitter2.prototype.listenerCount=listenerCount2;EventEmitter2.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]}}}),require_spark_md5=__commonJS({"node_modules/spark-md5/spark-md5.js"(exports,module2){(function(factory){if("object"==typeof exports)module2.exports=factory();else if("function"==typeof define&&define.amd)define(factory);else{var glob;try{glob=window}catch(e3){glob=self}glob.SparkMD5=factory()}})((function(undefined2){"use strict";function md5cycle(x2,k2){var a2=x2[0],b3=x2[1],c3=x2[2],d4=x2[3];b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[0]-680876936|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[1]-389564586|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[2]+606105819|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[3]-1044525330|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[4]-176418897|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[5]+1200080426|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[6]-1473231341|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[7]-45705983|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[8]+1770035416|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[9]-1958414417|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[10]-42063|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[11]-1990404162|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[12]+1804603682|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[13]-40341101|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[14]-1502002290|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[15]+1236535329|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[1]-165796510|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[6]-1069501632|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[11]+643717713|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[0]-373897302|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[5]-701558691|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[10]+38016083|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[15]-660478335|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[4]-405537848|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[9]+568446438|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[14]-1019803690|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[3]-187363961|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[8]+1163531501|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[13]-1444681467|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[2]-51403784|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[7]+1735328473|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[12]-1926607734|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[5]-378558|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[8]-2022574463|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[11]+1839030562|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[14]-35309556|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[1]-1530992060|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[4]+1272893353|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[7]-155497632|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[10]-1094730640|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[13]+681279174|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[0]-358537222|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[3]-722521979|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[6]+76029189|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[9]-640364487|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[12]-421815835|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[15]+530742520|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[2]-995338651|0)<<23|b3>>>9)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[0]-198630844|0)<<6|a2>>>26)+b3|0)|~c3))+k2[7]+1126891415|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[14]-1416354905|0)<<15|c3>>>17)+d4|0)|~a2))+k2[5]-57434055|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[12]+1700485571|0)<<6|a2>>>26)+b3|0)|~c3))+k2[3]-1894986606|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[10]-1051523|0)<<15|c3>>>17)+d4|0)|~a2))+k2[1]-2054922799|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[8]+1873313359|0)<<6|a2>>>26)+b3|0)|~c3))+k2[15]-30611744|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[6]-1560198380|0)<<15|c3>>>17)+d4|0)|~a2))+k2[13]+1309151649|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[4]-145523070|0)<<6|a2>>>26)+b3|0)|~c3))+k2[11]-1120210379|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[2]+718787259|0)<<15|c3>>>17)+d4|0)|~a2))+k2[9]-343485551|0)<<21|b3>>>11)+c3|0;x2[0]=a2+x2[0]|0;x2[1]=b3+x2[1]|0;x2[2]=c3+x2[2]|0;x2[3]=d4+x2[3]|0}function md5blk(s2){var i2,md5blks=[];for(i2=0;i2<64;i2+=4)md5blks[i2>>2]=s2.charCodeAt(i2)+(s2.charCodeAt(i2+1)<<8)+(s2.charCodeAt(i2+2)<<16)+(s2.charCodeAt(i2+3)<<24);return md5blks}function md5blk_array(a2){var i2,md5blks=[];for(i2=0;i2<64;i2+=4)md5blks[i2>>2]=a2[i2]+(a2[i2+1]<<8)+(a2[i2+2]<<16)+(a2[i2+3]<<24);return md5blks}function md51(s2){var i2,length,tail,tmp,lo,hi,n3=s2.length,state2=[1732584193,-271733879,-1732584194,271733878];for(i2=64;i2<=n3;i2+=64)md5cycle(state2,md5blk(s2.substring(i2-64,i2)));length=(s2=s2.substring(i2-64)).length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2>2]|=s2.charCodeAt(i2)<<(i2%4<<3);tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(state2,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*n3).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}function rhex(n3){var j2,s2="";for(j2=0;j2<4;j2+=1)s2+=hex_chr[n3>>8*j2+4&15]+hex_chr[n3>>8*j2&15];return s2}function hex(x2){var i2;for(i2=0;i2end)return new ArrayBuffer(0);num=end-begin;target=new ArrayBuffer(num);targetArray=new Uint8Array(target);sourceArray=new Uint8Array(this,begin,num);targetArray.set(sourceArray);return target}}();SparkMD5.prototype.append=function(str){this.appendBinary(toUtf82(str));return this};SparkMD5.prototype.appendBinary=function(contents){this._buff+=contents;this._length+=contents.length;var i2,length=this._buff.length;for(i2=64;i2<=length;i2+=64)md5cycle(this._hash,md5blk(this._buff.substring(i2-64,i2)));this._buff=this._buff.substring(i2-64);return this};SparkMD5.prototype.end=function(raw){var i2,ret,buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2>2]|=buff.charCodeAt(i2)<<(i2%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.prototype.reset=function(){this._buff="";this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}};SparkMD5.prototype.setState=function(state2){this._buff=state2.buff;this._length=state2.length;this._hash=state2.hash;return this};SparkMD5.prototype.destroy=function(){delete this._hash;delete this._buff;delete this._length};SparkMD5.prototype._finish=function(tail,length){var tmp,lo,hi,i2=length;tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(this._hash,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*this._length).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(this._hash,tail)};SparkMD5.hash=function(str,raw){return SparkMD5.hashBinary(toUtf82(str),raw)};SparkMD5.hashBinary=function(content,raw){var ret=hex(md51(content));return raw?hexToBinaryString(ret):ret};SparkMD5.ArrayBuffer=function(){this.reset()};SparkMD5.ArrayBuffer.prototype.append=function(arr){var i2,buff=function concatenateArrayBuffers(first,second,returnUInt8Array){var result=new Uint8Array(first.byteLength+second.byteLength);result.set(new Uint8Array(first));result.set(new Uint8Array(second),first.byteLength);return returnUInt8Array?result:result.buffer}(this._buff.buffer,arr,!0),length=buff.length;this._length+=arr.byteLength;for(i2=64;i2<=length;i2+=64)md5cycle(this._hash,md5blk_array(buff.subarray(i2-64,i2)));this._buff=i2-64>2]|=buff[i2]<<(i2%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.ArrayBuffer.prototype.reset=function(){this._buff=new Uint8Array(0);this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.ArrayBuffer.prototype.getState=function(){var state2=SparkMD5.prototype.getState.call(this);state2.buff=function arrayBuffer2Utf8Str(buff){return String.fromCharCode.apply(null,new Uint8Array(buff))}(state2.buff);return state2};SparkMD5.ArrayBuffer.prototype.setState=function(state2){state2.buff=function utf8Str2ArrayBuffer(str,returnUInt8Array){var i2,length=str.length,buff=new ArrayBuffer(length),arr=new Uint8Array(buff);for(i2=0;i2>2]|=a2[i2]<<(i2%4<<3);tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(state2,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*n3).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}(new Uint8Array(arr)),ret=hex(hash2);return raw?hexToBinaryString(ret):ret};return SparkMD5}))}}),require_vuvuzela=__commonJS({"node_modules/vuvuzela/index.js"(exports){"use strict";function pop3(obj,stack2,metaStack){var element2,lastElementIndex,lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}element2=lastMetaElement.element;lastElementIndex=lastMetaElement.index;Array.isArray(element2)?element2.push(obj):lastElementIndex===stack2.length-2?element2[stack2.pop()]=obj:stack2.push(obj)}exports.stringify=function stringify4(input){var res2,next2,obj,val2,i2,arrayPrefix,keys3,k2,key2,value,objPrefix,queue2=[];queue2.push({obj:input});res2="";for(;next2=queue2.pop();){obj=next2.obj;res2+=next2.prefix||"";if(val2=next2.val||"")res2+=val2;else if("object"!=typeof obj)res2+=void 0===obj?null:JSON.stringify(obj);else if(null===obj)res2+="null";else if(Array.isArray(obj)){queue2.push({val:"]"});for(i2=obj.length-1;i2>=0;i2--){arrayPrefix=0===i2?"":",";queue2.push({obj:obj[i2],prefix:arrayPrefix})}queue2.push({val:"["})}else{keys3=[];for(k2 in obj)obj.hasOwnProperty(k2)&&keys3.push(k2);queue2.push({val:"}"});for(i2=keys3.length-1;i2>=0;i2--){value=obj[key2=keys3[i2]];objPrefix=i2>0?",":"";objPrefix+=JSON.stringify(key2)+":";queue2.push({obj:value,prefix:objPrefix})}queue2.push({val:"{"})}}return res2};exports.parse=function(str){for(var collationIndex2,parsedNum,numChar,parsedString,lastCh,numConsecutiveSlashes,ch4,arrayElement,objElement,stack2=[],metaStack=[],i2=0;;)if("}"!==(collationIndex2=str[i2++])&&"]"!==collationIndex2&&void 0!==collationIndex2)switch(collationIndex2){case" ":case"\t":case"\n":case":":case",":break;case"n":i2+=3;pop3(null,stack2,metaStack);break;case"t":i2+=3;pop3(!0,stack2,metaStack);break;case"f":i2+=4;pop3(!1,stack2,metaStack);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":parsedNum="";i2--;for(;;){numChar=str[i2++];if(!/[\d\.\-e\+]/.test(numChar)){i2--;break}parsedNum+=numChar}pop3(parseFloat(parsedNum),stack2,metaStack);break;case'"':parsedString="";lastCh=void 0;numConsecutiveSlashes=0;for(;'"'!==(ch4=str[i2++])||"\\"===lastCh&&numConsecutiveSlashes%2==1;){parsedString+=ch4;"\\"===(lastCh=ch4)?numConsecutiveSlashes++:numConsecutiveSlashes=0}pop3(JSON.parse('"'+parsedString+'"'),stack2,metaStack);break;case"[":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"{":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop3(stack2.pop(),stack2,metaStack)}}}}),require_pouchdb_wrappers=__commonJS({"node_modules/pouchdb-wrappers/index.js"(exports,module2){"use strict";function replacementMethod(base,method){return function(...args){function doMethod(){let callback=null;const minArgs="query"===method?1:0;args.length>minArgs&&"function"==typeof args[args.length-1]&&(callback=args.pop());let prev=base._originals[method].bind(base);for(const handler of base._handlers[method])prev=handler.bind(base,prev);const result=prev(...args);result.then&&callback&&function nodify(promise,callback){promise.then(((...args)=>{callback(null,...args)})).catch((err2=>{callback(err2)}))}(result,callback);return result}return"changes"!==method&&base.taskqueue&&!base.taskqueue.isReady?new Promise(((resolve,reject)=>{base.taskqueue.addTask((error=>{error?reject(error):resolve()}))})).then(doMethod):doMethod()}}var toExport={install:function installWrappers(base,handlers2={}){if(!base._originals||!base._handlers){base._originals={};base._handlers={}}for(const[method,handler]of Object.entries(handlers2)){if(!(method in base))throw new Error(`Method '${method}' does not exist on given base, so it cannot be wrapped.`);method in base._originals||(base._originals[method]=base[method]);if(method in base._handlers)base._handlers[method].unshift(handler);else{base._handlers[method]=[handler];base[method]=replacementMethod(base,method)}}},uninstall:function uninstallWrappers(base,handlers2){if(!base._originals||!base._handlers)throw new Error("No wrapper methods installed, so no methods can be uninstalled.");for(const[method,handler]of Object.entries(handlers2)){const errorMessage=`Wrapper method for '${method}' not installed: ${handler.toString()}`;if(!(method in base._handlers))throw new Error(errorMessage);const i2=base._handlers[method].indexOf(handler);if(-1===i2)throw new Error(errorMessage);base._handlers[method].splice(i2,1)}}};try{module2.exports=toExport}catch(e3){}try{window.PouchDBWrappers=toExport}catch(e3){}}}),require_transform_pouch=__commonJS({"node_modules/transform-pouch/index.js"(exports,module2){"use strict";function isntInternalKey(key2){return"_"!==key2[0]}function isUntransformable(doc){return!("string"!=typeof doc._id||!/^_local/.test(doc._id))||!!doc._deleted&&0===Object.keys(doc).filter(isntInternalKey).length}function transform2(config){const incoming=function(doc){return!isUntransformable(doc)&&config.incoming?config.incoming(doc):doc},outgoing=function(doc){return!isUntransformable(doc)&&config.outgoing?config.outgoing(doc):doc},handlers2={async get(orig,...args){const response=await orig(...args);if(Array.isArray(response)){await Promise.all(response.map((async row=>{row.ok&&(row.ok=await outgoing(row.ok))})));return response}return outgoing(response)},async bulkDocs(orig,docs,...args){docs.docs?docs.docs=await Promise.all(docs.docs.map(incoming)):docs=await Promise.all(docs.map(incoming));return orig(docs,...args)},async allDocs(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map((async row=>{row.doc&&(row.doc=await outgoing(row.doc))})));return response},async bulkGet(orig,...args){const mapDoc=async doc=>doc.ok?{ok:await outgoing(doc.ok)}:doc;let{results,...res2}=await orig(...args);results=await Promise.all(results.map((async result=>{const{id,docs}=result;return id&&docs&&Array.isArray(docs)?{id,docs:await Promise.all(docs.map(mapDoc))}:result})));return{results,...res2}},changes(orig,...args){async function modifyChange(change){if(change.doc){change.doc=await outgoing(change.doc);return change}return change}async function modifyChanges(res2){if(res2.results){res2.results=await Promise.all(res2.results.map(modifyChange));return res2}return res2}const changes3=orig(...args),{on:origOn,then:origThen}=changes3;return Object.assign(changes3,{on(event2,listener){const origListener=listener;"change"===event2?listener=async change=>{origListener(await modifyChange(change))}:"complete"===event2&&(listener=async res2=>{origListener(await modifyChanges(res2))});return origOn.call(changes3,event2,listener)},then:(resolve,reject)=>origThen.call(changes3,modifyChanges).then(resolve,reject)})}};if("http"===this.type()){handlers2.put=async function(orig,doc,...args){return orig(doc=await incoming(doc),...args)};handlers2.query=async function(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map((async row=>{row.doc&&(row.doc=await outgoing(row.doc))})));return response}}wrappers.install(this,handlers2)}var wrappers=require_pouchdb_wrappers();module2.exports={transform:transform2,filter:transform2};"undefined"!=typeof window&&window.PouchDB&&window.PouchDB.plugin(exports)}}),main_exports={}; +/*! Bundled license information: + +@noble/secp256k1/lib/esm/index.js: + (*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *) +*/__export(main_exports,{default:()=>ObsidianLiveSyncPlugin});module.exports=__toCommonJS(main_exports);LEVEL_INFO=LOG_LEVEL_INFO=32;LOG_LEVEL_NOTICE=64;LOG_LEVEL_VERBOSE=16;defaultLoggerEnv_minLogLevel=LOG_LEVEL_INFO;_logger=function defaultLogger2(message,level=LEVEL_INFO,key2){if(level{AutoAccepting2[AutoAccepting2.NONE=0]="NONE";AutoAccepting2[AutoAccepting2.ALL=1]="ALL";return AutoAccepting2})(AutoAccepting||{});P2P_DEFAULT_SETTINGS={P2P_Enabled:!1,P2P_AutoAccepting:0,P2P_AppID:"self-hosted-livesync",P2P_roomID:"",P2P_passphrase:"",P2P_relays:"wss://exp-relay.vrtmrz.net/",P2P_AutoBroadcast:!1,P2P_AutoStart:!1,P2P_AutoSyncPeers:"",P2P_AutoWatchPeers:"",P2P_SyncOnReplication:"",P2P_RebuildFrom:"",P2P_AutoAcceptingPeers:"",P2P_AutoDenyingPeers:"",P2P_IsHeadless:!1};ChunkAlgorithmNames={v1:"V1: Legacy",v2:"V2: Simple (Default)","v2-segmenter":"V2.5: Lexical chunks","v3-rabin-karp":"V3: Fine deduplication"};ChunkAlgorithms_V1="v1",ChunkAlgorithms_V2="v2",ChunkAlgorithms_V2Segmenter="v2-segmenter",ChunkAlgorithms_RabinKarp="v3-rabin-karp";DEFAULT_SETTINGS={remoteType:REMOTE_COUCHDB,useCustomRequestHandler:!1,couchDB_URI:"",couchDB_USER:"",couchDB_PASSWORD:"",couchDB_DBNAME:"",liveSync:!1,syncOnSave:!1,syncOnStart:!1,savingDelay:200,lessInformationInLog:!1,gcDelay:300,versionUpFlash:"",minimumChunkSize:20,longLineThreshold:250,showVerboseLog:!1,suspendFileWatching:!1,trashInsteadDelete:!0,periodicReplication:!1,periodicReplicationInterval:60,syncOnFileOpen:!1,encrypt:!1,passphrase:"",usePathObfuscation:!1,doNotDeleteFolder:!1,resolveConflictsByNewerFile:!1,batchSave:!1,batchSaveMinimumDelay:5,batchSaveMaximumDelay:60,deviceAndVaultName:"",usePluginSettings:!1,showOwnPlugins:!1,showStatusOnEditor:!0,showStatusOnStatusbar:!0,showOnlyIconsOnEditor:!1,hideFileWarningNotice:!1,usePluginSync:!1,autoSweepPlugins:!1,autoSweepPluginsPeriodic:!1,notifyPluginOrSettingUpdated:!1,checkIntegrityOnSave:!1,batch_size:25,batches_limit:25,useHistory:!1,disableRequestURI:!1,skipOlderFilesOnSync:!0,checkConflictOnlyOnOpen:!1,showMergeDialogOnlyOnActive:!1,syncInternalFiles:!1,syncInternalFilesBeforeReplication:!1,syncInternalFilesIgnorePatterns:"\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",syncInternalFilesTargetPatterns:"",syncInternalFilesInterval:60,additionalSuffixOfDatabaseName:"",ignoreVersionCheck:!1,lastReadUpdates:0,deleteMetadataOfDeletedFiles:!1,syncIgnoreRegEx:"",syncOnlyRegEx:"",customChunkSize:0,readChunksOnline:!0,watchInternalFileChanges:!0,automaticallyDeleteMetadataOfDeletedFiles:0,disableMarkdownAutoMerge:!1,writeDocumentsIfConflicted:!1,useDynamicIterationCount:!1,syncAfterMerge:!1,configPassphraseStore:"",encryptedPassphrase:"",encryptedCouchDBConnection:"",permitEmptyPassphrase:!1,useIndexedDBAdapter:!0,useTimeouts:!1,writeLogToTheFile:!1,doNotPaceReplication:!1,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,hashAlg:"xxhash64",suspendParseReplicationResult:!1,doNotSuspendOnFetching:!1,useIgnoreFiles:!1,ignoreFiles:".gitignore",syncOnEditorSave:!1,pluginSyncExtendedSetting:{},syncMaxSizeInMB:50,settingSyncFile:"",writeCredentialsForSettingSync:!1,notifyAllSettingSyncFile:!1,isConfigured:void 0,settingVersion:10,enableCompression:!1,accessKey:"",bucket:"",endpoint:"",region:"auto",secretKey:"",useEden:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,disableCheckingConfigMismatch:!1,displayLanguage:"",enableChunkSplitterV2:!1,disableWorkerForGeneratingChunks:!1,processSmallFilesInUIThread:!1,notifyThresholdOfRemoteStorageSize:-1,usePluginSyncV2:!1,usePluginEtc:!1,handleFilenameCaseSensitive:void 0,doNotUseFixedRevisionForChunks:!0,showLongerLogInsideEditor:!1,sendChunksBulk:!1,sendChunksBulkMaxSize:1,useSegmenter:!1,useAdvancedMode:!1,usePowerUserMode:!1,useEdgeCaseMode:!1,enableDebugTools:!1,suppressNotifyHiddenFilesChange:!1,syncMinimumInterval:2e3,...P2P_DEFAULT_SETTINGS,doctorProcessedVersion:"",bucketCustomHeaders:"",couchDB_CustomHeaders:"",useJWT:!1,jwtAlgorithm:"",jwtKey:"",jwtKid:"",jwtSub:"",jwtExpDuration:5,useRequestAPI:!1,bucketPrefix:"",chunkSplitterVersion:""};KeyIndexOfSettings={remoteType:0,useCustomRequestHandler:1,couchDB_URI:2,couchDB_USER:3,couchDB_PASSWORD:4,couchDB_DBNAME:5,minimumChunkSize:6,longLineThreshold:7,encrypt:8,passphrase:9,usePathObfuscation:10,checkIntegrityOnSave:11,batch_size:12,batches_limit:13,useHistory:14,disableRequestURI:15,checkConflictOnlyOnOpen:16,showMergeDialogOnlyOnActive:17,additionalSuffixOfDatabaseName:18,ignoreVersionCheck:19,deleteMetadataOfDeletedFiles:20,customChunkSize:21,readChunksOnline:22,automaticallyDeleteMetadataOfDeletedFiles:23,useDynamicIterationCount:24,permitEmptyPassphrase:25,useTimeouts:26,doNotPaceReplication:27,hashCacheMaxCount:28,hashCacheMaxAmount:29,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:31,hashAlg:32,enableCompression:33,accessKey:34,bucket:35,endpoint:36,region:37,secretKey:38,useEden:39,maxChunksInEden:40,maxTotalLengthInEden:41,maxAgeInEden:42,disableCheckingConfigMismatch:43,handleFilenameCaseSensitive:44,doNotUseFixedRevisionForChunks:45,sendChunksBulk:46,sendChunksBulkMaxSize:47,useSegmenter:48,liveSync:49,syncOnSave:50,syncOnStart:51,syncOnFileOpen:52,syncOnEditorSave:53,syncMinimumInterval:54,showVerboseLog:55,lessInformationInLog:56,showLongerLogInsideEditor:57,showStatusOnEditor:58,showStatusOnStatusbar:59,showOnlyIconsOnEditor:60,displayLanguage:61,trashInsteadDelete:62,doNotDeleteFolder:63,batchSave:64,batchSaveMinimumDelay:64,batchSaveMaximumDelay:65,syncMaxSizeInMB:66,useIgnoreFiles:67,ignoreFiles:68,syncOnlyRegEx:69,syncIgnoreRegEx:70,syncAfterMerge:71,resolveConflictsByNewerFile:72,writeDocumentsIfConflicted:73,disableMarkdownAutoMerge:74,configPassphraseStore:75,encryptedPassphrase:76,encryptedCouchDBConnection:77,periodicReplication:78,periodicReplicationInterval:79,syncInternalFiles:80,syncInternalFilesBeforeReplication:81,syncInternalFilesInterval:82,syncInternalFilesIgnorePatterns:83,watchInternalFileChanges:84,suppressNotifyHiddenFilesChange:85,usePluginSync:86,usePluginSettings:87,showOwnPlugins:88,autoSweepPlugins:89,autoSweepPluginsPeriodic:90,notifyPluginOrSettingUpdated:91,deviceAndVaultName:92,usePluginSyncV2:93,usePluginEtc:94,pluginSyncExtendedSetting:95,useAdvancedMode:96,usePowerUserMode:97,useEdgeCaseMode:98,notifyThresholdOfRemoteStorageSize:99,disableWorkerForGeneratingChunks:100,processSmallFilesInUIThread:101,enableChunkSplitterV2:102,savingDelay:103,gcDelay:104,skipOlderFilesOnSync:105,useIndexedDBAdapter:106,enableDebugTools:107,writeLogToTheFile:108,settingSyncFile:109,writeCredentialsForSettingSync:110,notifyAllSettingSyncFile:111,suspendFileWatching:112,suspendParseReplicationResult:113,doNotSuspendOnFetching:114,versionUpFlash:115,settingVersion:116,isConfigured:117,lastReadUpdates:118,doctorProcessedVersion:119,P2P_Enabled:120,P2P_relays:121,P2P_roomID:122,P2P_passphrase:123,P2P_AutoAccepting:124,P2P_AutoStart:125,P2P_AutoBroadcast:126,P2P_AutoSyncPeers:127,P2P_AutoWatchPeers:128,P2P_SyncOnReplication:129,P2P_AppID:130,P2P_RebuildFrom:131,bucketCustomHeaders:132,couchDB_CustomHeaders:133,useJWT:134,jwtAlgorithm:135,jwtKey:136,jwtKid:137,jwtSub:138,jwtExpDuration:139,P2P_AutoAcceptingPeers:140,P2P_AutoDenyingPeers:141,P2P_IsHeadless:-1,syncInternalFilesTargetPatterns:142,useRequestAPI:143,hideFileWarningNotice:144,bucketPrefix:145,chunkSplitterVersion:146};PREFERRED_BASE={syncMaxSizeInMB:50,chunkSplitterVersion:"v3-rabin-karp",doNotUseFixedRevisionForChunks:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1};PREFERRED_SETTING_CLOUDANT={...PREFERRED_BASE,customChunkSize:0,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:100,minimumIntervalOfReadChunksOnline:333};PREFERRED_SETTING_SELF_HOSTED={...PREFERRED_BASE,customChunkSize:50,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};PREFERRED_JOURNAL_SYNC={...PREFERRED_BASE,customChunkSize:10,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};TweakValuesShouldMatchedTemplate={minimumChunkSize:20,longLineThreshold:250,encrypt:!1,usePathObfuscation:!1,enableCompression:!1,useEden:!1,customChunkSize:0,useDynamicIterationCount:!1,hashAlg:"xxhash64",enableChunkSplitterV2:!0,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,usePluginSyncV2:!1,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!0,useSegmenter:!1};IncompatibleChanges=["encrypt","usePathObfuscation","useDynamicIterationCount","handleFilenameCaseSensitive"];CompatibleButLossyChanges=["hashAlg"];IncompatibleChangesInSpecificPattern=[{key:"doNotUseFixedRevisionForChunks",from:!0,to:!1,isRecommendation:!0},{key:"doNotUseFixedRevisionForChunks",to:!0,isRecommendation:!1}];TweakValuesDefault={usePluginSyncV2:!1};configurationNames={minimumChunkSize:{name:"Minimum Chunk Size (Not Configurable from the UI Now)."},longLineThreshold:{name:"Longest chunk line threshold value (Not Configurable from the UI Now)."},encrypt:{name:"End-to-End Encryption",desc:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended."},usePathObfuscation:{name:"Path Obfuscation"},enableCompression:{name:"Data Compression",status:"EXPERIMENTAL"},useEden:{name:"Incubate Chunks in Document",desc:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",status:"BETA"},customChunkSize:{name:"Enhance chunk size"},useDynamicIterationCount:{name:"Use dynamic iteration count",status:"EXPERIMENTAL"},hashAlg:{name:"The Hash algorithm for chunk IDs",status:"EXPERIMENTAL"},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},usePluginSyncV2:{name:"Per-file-saved customization sync",desc:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Compute revisions for chunks (Previous behaviour)",desc:"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)"},useSegmenter:{name:"Use Segmented-splitter",desc:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature."},useJWT:{name:"Use JWT instead of Basic Authentication",desc:"If this enabled, JWT will be used for authentication."},jwtAlgorithm:{name:"Algorithm",desc:"The algorithm used for JWT authentication."},jwtKey:{name:"Keypair or pre-shared key",desc:"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication."},jwtKid:{name:"Key ID",desc:"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`."},jwtExpDuration:{name:"Rotation Duration",desc:"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration."},jwtSub:{name:"Subject (whoami)",desc:"The subject for JWT authentication. Mostly username."},bucketCustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"},couchDB_CustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"}};LEVEL_ADVANCED="ADVANCED";LEVEL_POWER_USER="POWER_USER";LEVEL_EDGE_CASE="EDGE_CASE";TweakValuesTemplate={useIgnoreFiles:!1,useCustomRequestHandler:!1,batch_size:25,batches_limit:25,useIndexedDBAdapter:!0,useTimeouts:!1,readChunksOnline:!0,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,ignoreFiles:".gitignore",syncMaxSizeInMB:50,enableChunkSplitterV2:!0,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!1,...TweakValuesShouldMatchedTemplate};DEVICE_ID_PREFERRED="PREFERRED";PREFIXMD_LOGFILE="livesync_log_";PREFIXMD_LOGFILE_UC="LIVESYNC_LOG_";FLAGMD_REDFLAG="redflag.md";FLAGMD_REDFLAG2="redflag2.md";FLAGMD_REDFLAG2_HR="flag_rebuild.md";FLAGMD_REDFLAG3="redflag3.md";FLAGMD_REDFLAG3_HR="flag_fetch.md";SYNCINFO_ID="syncinfo";PREFIX_OBFUSCATED="f:";PREFIX_ENCRYPTED_CHUNK="h:+";import_obsidian=require("obsidian");import_obsidian2=require("obsidian");import_diff_match_patch=__toESM(require_diff_match_patch(),1);normalizePath=import_obsidian2.normalizePath;PSCHeader="ps:";ICHeaderLength=(ICHeader="i:").length;ICXHeader="ix:";configURIBase="obsidian://setuplivesync?settings=";LRUCache=class{constructor(maxCache,maxCacheLength,forwardOnly=!1){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"revCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"maxCache",{enumerable:!0,configurable:!0,writable:!0,value:200});Object.defineProperty(this,"maxCachedLength",{enumerable:!0,configurable:!0,writable:!0,value:5e7});Object.defineProperty(this,"cachedLength",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"enableReversed",{enumerable:!0,configurable:!0,writable:!0,value:!0});this.maxCache=maxCache||200;this.maxCachedLength=1e6*(maxCacheLength||1);this.enableReversed=!forwardOnly;Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`,LOG_LEVEL_VERBOSE)}clear(){this.cache.clear();this.revCache.clear()}has(key2){return this.cache.has(key2)}get(key2){const v2=this.cache.get(key2);if(v2){this.cache.delete(key2);this.cache.set(key2,v2);if(this.enableReversed){this.revCache.delete(v2);this.revCache.set(v2,key2)}}return v2}revGet(value){const key2=this.revCache.get(value);if(key2){this.cache.delete(key2);this.revCache.delete(value);this.cache.set(key2,value);this.revCache.set(value,key2)}return key2}set(key2,value){this.cache.set(key2,value);this.enableReversed&&this.revCache.set(value,key2);this.cachedLength+=`${value}`.length;if(this.cache.size>this.maxCache||this.cachedLength>this.maxCachedLength)for(const[key3,value2]of this.cache){this.cache.delete(key3);this.enableReversed&&this.revCache.delete(value2);this.cachedLength-=`${value2}`.length;if(this.cache.size<=this.maxCache&&this.cachedLength<=this.maxCachedLength)break}}};balanced=(a2,b3,str)=>{const ma=a2 instanceof RegExp?maybeMatch(a2,str):a2,mb=b3 instanceof RegExp?maybeMatch(b3,str):b3,r4=null!==ma&&null!=mb&&range(ma,mb,str);return r4&&{start:r4[0],end:r4[1],pre:str.slice(0,r4[0]),body:str.slice(r4[0]+ma.length,r4[1]),post:str.slice(r4[1]+mb.length)}};maybeMatch=(reg,str)=>{const m3=str.match(reg);return m3?m3[0]:null};range=(a2,b3,str)=>{let begs,beg,left,right,result,ai2=str.indexOf(a2),bi2=str.indexOf(b3,ai2+1),i2=ai2;if(ai2>=0&&bi2>0){if(a2===b3)return[ai2,bi2];begs=[];left=str.length;for(;i2>=0&&!result;){if(i2===ai2){begs.push(i2);ai2=str.indexOf(a2,i2+1)}else if(1===begs.length){const r4=begs.pop();void 0!==r4&&(result=[r4,bi2])}else{beg=begs.pop();if(void 0!==beg&&beg=0?ai2:bi2}begs.length&&void 0!==right&&(result=[left,right])}return result};escSlash="\0SLASH"+Math.random()+"\0";escOpen="\0OPEN"+Math.random()+"\0";escClose="\0CLOSE"+Math.random()+"\0";escComma="\0COMMA"+Math.random()+"\0";escPeriod="\0PERIOD"+Math.random()+"\0";escSlashPattern=new RegExp(escSlash,"g");escOpenPattern=new RegExp(escOpen,"g");escClosePattern=new RegExp(escClose,"g");escCommaPattern=new RegExp(escComma,"g");escPeriodPattern=new RegExp(escPeriod,"g");slashPattern=/\\\\/g;openPattern=/\\{/g;closePattern=/\\}/g;commaPattern=/\\,/g;periodPattern=/\\./g;assertValidPattern=pattern=>{if("string"!=typeof pattern)throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]};braceEscape=s2=>s2.replace(/[[\]\\-]/g,"\\$&");regexpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");rangesToString=ranges=>ranges.join("");parseClass=(glob,position)=>{const pos=position;if("["!==glob.charAt(pos))throw new Error("not in a brace expression");const ranges=[],negs=[];let i2=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate3=!1,endPos=pos,rangeStart="";WHILE:for(;i2rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c3)):c3===rangeStart&&ranges.push(braceEscape(c3));rangeStart="";i2++}else if(glob.startsWith("-]",i2+1)){ranges.push(braceEscape(c3+"-"));i2+=2}else if(glob.startsWith("-",i2+1)){rangeStart=c3;i2+=2}else{ranges.push(braceEscape(c3));i2++}}else{escaping=!0;i2++}}else{negate3=!0;i2++}}if(endPoswindowsPathsNoEscape?s2.replace(/\[([^\/\\])\]/g,"$1"):s2.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");types=new Set(["!","?","+","*","@"]);isExtglobType=c3=>types.has(c3);addPatternStart=new Set(["[","."]);justDots=new Set(["..","."]);reSpecials=new Set("().*{}+?[]^$\\!");regExpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");_AST=class _AST{constructor(type,parent,options={}){__privateAdd(this,_AST_instances);__publicField(this,"type");__privateAdd(this,_root);__privateAdd(this,_hasMagic);__privateAdd(this,_uflag,!1);__privateAdd(this,_parts,[]);__privateAdd(this,_parent);__privateAdd(this,_parentIndex);__privateAdd(this,_negs);__privateAdd(this,_filledNegs,!1);__privateAdd(this,_options);__privateAdd(this,_toString);__privateAdd(this,_emptyExt,!1);this.type=type;type&&__privateSet(this,_hasMagic,!0);__privateSet(this,_parent,parent);__privateSet(this,_root,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_root):this);__privateSet(this,_options,__privateGet(this,_root)===this?options:__privateGet(__privateGet(this,_root),_options));__privateSet(this,_negs,__privateGet(this,_root)===this?[]:__privateGet(__privateGet(this,_root),_negs));"!"!==type||__privateGet(__privateGet(this,_root),_filledNegs)||__privateGet(this,_negs).push(this);__privateSet(this,_parentIndex,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0)}get hasMagic(){if(void 0!==__privateGet(this,_hasMagic))return __privateGet(this,_hasMagic);for(const p4 of __privateGet(this,_parts))if("string"!=typeof p4&&(p4.type||p4.hasMagic))return __privateSet(this,_hasMagic,!0);return __privateGet(this,_hasMagic)}toString(){return void 0!==__privateGet(this,_toString)?__privateGet(this,_toString):this.type?__privateSet(this,_toString,this.type+"("+__privateGet(this,_parts).map((p4=>String(p4))).join("|")+")"):__privateSet(this,_toString,__privateGet(this,_parts).map((p4=>String(p4))).join(""))}push(...parts){for(const p4 of parts)if(""!==p4){if("string"!=typeof p4&&!(p4 instanceof _AST&&__privateGet(p4,_parent)===this))throw new Error("invalid part: "+p4);__privateGet(this,_parts).push(p4)}}toJSON(){var _a8;const ret=null===this.type?__privateGet(this,_parts).slice().map((p4=>"string"==typeof p4?p4:p4.toJSON())):[this.type,...__privateGet(this,_parts).map((p4=>p4.toJSON()))];this.isStart()&&!this.type&&ret.unshift([]);this.isEnd()&&(this===__privateGet(this,_root)||__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type))&&ret.push({});return ret}isStart(){var _a8;if(__privateGet(this,_root)===this)return!0;if(!(null==(_a8=__privateGet(this,_parent))?void 0:_a8.isStart()))return!1;if(0===__privateGet(this,_parentIndex))return!0;const p4=__privateGet(this,_parent);for(let i2=0;i2<__privateGet(this,_parentIndex);i2++){const pp=__privateGet(p4,_parts)[i2];if(!(pp instanceof _AST&&"!"===pp.type))return!1}return!0}isEnd(){var _a8,_b4,_c3;if(__privateGet(this,_root)===this)return!0;if("!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type))return!0;if(!(null==(_b4=__privateGet(this,_parent))?void 0:_b4.isEnd()))return!1;if(!this.type)return null==(_c3=__privateGet(this,_parent))?void 0:_c3.isEnd();const pl=__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0;return __privateGet(this,_parentIndex)===pl-1}copyIn(part){"string"==typeof part?this.push(part):this.push(part.clone(this))}clone(parent){const c3=new _AST(this.type,parent);for(const p4 of __privateGet(this,_parts))c3.copyIn(p4);return c3}static fromGlob(pattern,options={}){var _a8;const ast=new _AST(null,void 0,options);__privateMethod(_a8=_AST,_AST_static,parseAST_fn).call(_a8,pattern,ast,0,options);return ast}toMMPattern(){if(this!==__privateGet(this,_root))return __privateGet(this,_root).toMMPattern();const glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource();if(!(hasMagic||__privateGet(this,_hasMagic)||__privateGet(this,_options).nocase&&!__privateGet(this,_options).nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase()))return body;const flags=(__privateGet(this,_options).nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags),{_src:re,_glob:glob})}get options(){return __privateGet(this,_options)}toRegExpSource(allowDot){var _a8;const dot=null!=allowDot?allowDot:!!__privateGet(this,_options).dot;__privateGet(this,_root)===this&&__privateMethod(this,_AST_instances,fillNegs_fn).call(this);if(!this.type){const noEmpty=this.isStart()&&this.isEnd(),src=__privateGet(this,_parts).map((p4=>{var _a9;const[re,_,hasMagic,uflag]="string"==typeof p4?__privateMethod(_a9=_AST,_AST_static,parseGlob_fn).call(_a9,p4,__privateGet(this,_hasMagic),noEmpty):p4.toRegExpSource(allowDot);__privateSet(this,_hasMagic,__privateGet(this,_hasMagic)||hasMagic);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re})).join("");let start2="";if(this.isStart()&&"string"==typeof __privateGet(this,_parts)[0]&&(1!==__privateGet(this,_parts).length||!justDots.has(__privateGet(this,_parts)[0]))){const aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?"(?!(?:^|/)\\.\\.?(?:$|/))":needNoDot?"(?!\\.)":""}let end="";this.isEnd()&&__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type)&&(end="(?:$|\\/)");return[start2+src+end,unescape2(src),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}const repeated="*"===this.type||"+"===this.type,start="!"===this.type?"(?:(?!(?:":"(?:";let body=__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,dot);if(this.isStart()&&this.isEnd()&&!body&&"!"!==this.type){const s2=this.toString();__privateSet(this,_parts,[s2]);this.type=null;__privateSet(this,_hasMagic,void 0);return[s2,unescape2(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot?"":__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,!0);bodyDotAllowed===body&&(bodyDotAllowed="");bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";final="!"===this.type&&__privateGet(this,_emptyExt)?(this.isStart()&&!dot?"(?!\\.)":"")+"[^/]+?":start+body+("!"===this.type?"))"+(!this.isStart()||dot||allowDot?"":"(?!\\.)")+"[^/]*?)":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&bodyDotAllowed?")":"*"===this.type&&bodyDotAllowed?")?":`)${this.type}`);return[final,unescape2(body),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}};_root=new WeakMap;_hasMagic=new WeakMap;_uflag=new WeakMap;_parts=new WeakMap;_parent=new WeakMap;_parentIndex=new WeakMap;_negs=new WeakMap;_filledNegs=new WeakMap;_options=new WeakMap;_toString=new WeakMap;_emptyExt=new WeakMap;_AST_instances=new WeakSet;fillNegs_fn=function(){if(this!==__privateGet(this,_root))throw new Error("should only call on root");if(__privateGet(this,_filledNegs))return this;this.toString();__privateSet(this,_filledNegs,!0);let n3;for(;n3=__privateGet(this,_negs).pop();){if("!"!==n3.type)continue;let p4=n3,pp=__privateGet(p4,_parent);for(;pp;){for(let i2=__privateGet(p4,_parentIndex)+1;!pp.type&&i2<__privateGet(pp,_parts).length;i2++)for(const part of __privateGet(n3,_parts)){if("string"==typeof part)throw new Error("string part in extglob AST??");part.copyIn(__privateGet(pp,_parts)[i2])}p4=pp;pp=__privateGet(p4,_parent)}}return this};_AST_static=new WeakSet;parseAST_fn=function(str,ast,pos,opt){var _a8,_b4;let escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(null===ast.type){let i3=pos,acc2="";for(;i3{if("string"==typeof p4)throw new Error("string type in extglob ast??");const[re,_,_hasMagic2,uflag]=p4.toRegExpSource(dot);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re})).filter((p4=>!(this.isStart()&&this.isEnd()&&!p4))).join("|")};parseGlob_fn=function(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1;for(let i2=0;i2windowsPathsNoEscape?s2.replace(/[?*()[\]]/g,"[$&]"):s2.replace(/[?*()[\]\\]/g,"\\$&");minimatch=(p4,pattern,options={})=>{assertValidPattern(pattern);return!(!options.nocomment&&"#"===pattern.charAt(0))&&new Minimatch(pattern,options).match(p4)};starDotExtRE=/^\*+([^+@!?\*\[\(]*)$/;starDotExtTest=ext2=>f4=>!f4.startsWith(".")&&f4.endsWith(ext2);starDotExtTestDot=ext2=>f4=>f4.endsWith(ext2);starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f4=>!f4.startsWith(".")&&f4.toLowerCase().endsWith(ext2)};starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f4=>f4.toLowerCase().endsWith(ext2)};starDotStarRE=/^\*+\.\*+$/;starDotStarTest=f4=>!f4.startsWith(".")&&f4.includes(".");starDotStarTestDot=f4=>"."!==f4&&".."!==f4&&f4.includes(".");dotStarRE=/^\.\*+$/;dotStarTest=f4=>"."!==f4&&".."!==f4&&f4.startsWith(".");starRE=/^\*+$/;starTest=f4=>0!==f4.length&&!f4.startsWith(".");starTestDot=f4=>0!==f4.length&&"."!==f4&&".."!==f4;qmarksRE=/^\?+([^+@!?\*\[\(]*)?$/;qmarksTestNocase=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestNocaseDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTest=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTestNoExt=([$0])=>{const len=$0.length;return f4=>f4.length===len&&!f4.startsWith(".")};qmarksTestNoExtDot=([$0])=>{const len=$0.length;return f4=>f4.length===len&&"."!==f4&&".."!==f4};path_posix={sep:"/"};sep="win32"===(defaultPlatform="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix")?"\\":path_posix.sep;minimatch.sep=sep;GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;filter=(pattern,options={})=>p4=>minimatch(p4,pattern,options);minimatch.filter=filter;ext=(a2,b3={})=>Object.assign({},a2,b3);defaults=def=>{if(!def||"object"!=typeof def||!Object.keys(def).length)return minimatch;const orig=minimatch;return Object.assign(((p4,pattern,options={})=>orig(p4,pattern,ext(def,options))),{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s2,options={})=>orig.unescape(s2,ext(def,options)),escape:(s2,options={})=>orig.escape(s2,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;braceExpand=(pattern,options={})=>{assertValidPattern(pattern);return options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)?[pattern]:expand(pattern)};minimatch.braceExpand=braceExpand;makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;match=(list,pattern,options={})=>{const mm=new Minimatch(pattern,options);list=list.filter((f4=>mm.match(f4)));mm.options.nonull&&!list.length&&list.push(pattern);return list};minimatch.match=match;globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;regExpEscape2=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");Minimatch=class{constructor(pattern,options={}){__publicField(this,"options");__publicField(this,"set");__publicField(this,"pattern");__publicField(this,"windowsPathsNoEscape");__publicField(this,"nonegate");__publicField(this,"negate");__publicField(this,"comment");__publicField(this,"empty");__publicField(this,"preserveMultipleSlashes");__publicField(this,"partial");__publicField(this,"globSet");__publicField(this,"globParts");__publicField(this,"nocase");__publicField(this,"isWindows");__publicField(this,"platform");__publicField(this,"windowsNoMagicRoot");__publicField(this,"regexp");assertValidPattern(pattern);options=options||{};this.options=options;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows="win32"===this.platform;this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||!1===options.allowWindowsEscape;this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/"));this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=!1;this.nonegate=!!options.nonegate;this.comment=!1;this.empty=!1;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=void 0!==options.windowsNoMagicRoot?options.windowsNoMagicRoot:!(!this.isWindows||!this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const pattern of this.set)for(const part of pattern)if("string"!=typeof part)return!0;return!1}debug(..._){}make(){const pattern=this.pattern,options=this.options;if(!options.nocomment&&"#"===pattern.charAt(0)){this.comment=!0;return}if(!pattern){this.empty=!0;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];options.debug&&(this.debug=(...args)=>console.error(...args));this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map((s2=>this.slashSplit(s2)));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set2=this.globParts.map(((s2,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=!(""!==s2[0]||""!==s2[1]||"?"!==s2[2]&&globMagic.test(s2[2])||globMagic.test(s2[3])),isDrive=/^[a-z]:/i.test(s2[0]);if(isUNC)return[...s2.slice(0,4),...s2.slice(4).map((ss=>this.parse(ss)))];if(isDrive)return[s2[0],...s2.slice(1).map((ss=>this.parse(ss)))]}return s2.map((ss=>this.parse(ss)))}));this.debug(this.pattern,set2);this.set=set2.filter((s2=>-1===s2.indexOf(!1)));if(this.isWindows)for(let i2=0;i2=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else globParts=optimizationLevel>=1?this.levelOneOptimize(globParts):this.adjascentGlobstarOptimize(globParts);return globParts}adjascentGlobstarOptimize(globParts){return globParts.map((parts=>{let gs=-1;for(;-1!==(gs=parts.indexOf("**",gs+1));){let i2=gs;for(;"**"===parts[i2+1];)i2++;i2!==gs&&parts.splice(gs,i2-gs)}return parts}))}levelOneOptimize(globParts){return globParts.map((parts=>0===(parts=parts.reduce(((set2,part)=>{const prev=set2[set2.length-1];if("**"===part&&"**"===prev)return set2;if(".."===part&&prev&&".."!==prev&&"."!==prev&&"**"!==prev){set2.pop();return set2}set2.push(part);return set2}),[])).length?[""]:parts))}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let didSomething=!1;do{didSomething=!1;if(!this.preserveMultipleSlashes){for(let i2=1;i2gs&&parts.splice(gs+1,gss-gs);let next2=parts[gs+1];const p4=parts[gs+2],p22=parts[gs+3];if(".."!==next2)continue;if(!p4||"."===p4||".."===p4||!p22||"."===p22||".."===p22)continue;didSomething=!0;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i2=1;i2gs.length))}partsMatch(a2,b3,emptyGSMatch=!1){let ai2=0,bi2=0,result=[],which="";for(;ai2fdi?pattern=pattern.slice(pdi):fdi>pdi&&(file=file.slice(fdi))}}}const{optimizationLevel=1}=this.options;optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file));this.debug("matchOne",this,{file,pattern});this.debug("matchOne",file.length,pattern.length);for(fi=0,pi=0,fl2=file.length,pl=pattern.length;fi>> no match, partial?",file,fr,pattern,pr);if(fr===fl2)return!0}return!1}let hit;if("string"==typeof p4){hit=f4===p4;this.debug("string match",p4,f4,hit)}else{hit=p4.test(f4);this.debug("pattern match",p4,f4,hit)}if(!hit)return!1}if(fi===fl2&&pi===pl)return!0;if(fi===fl2)return partial;if(pi===pl)return fi===fl2-1&&""===file[fi];throw new Error("wtf?")}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if("**"===pattern)return GLOBSTAR;if(""===pattern)return"";let m3,fastTest=null;(m3=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m3=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m3[1]):(m3=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m3):(m3=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m3=pattern.match(dotStarRE))&&(fastTest=dotStarTest);const re=AST.fromGlob(pattern,this.options).toMMPattern();fastTest&&"object"==typeof re&&Reflect.defineProperty(re,"test",{value:fastTest});return re}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const set2=this.set;if(!set2.length){this.regexp=!1;return this.regexp}const options=this.options,twoStar=options.noglobstar?"[^/]*?":options.dot?"(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?":"(?:(?!(?:\\/|^)\\.).)*?",flags=new Set(options.nocase?["i"]:[]);let re=set2.map((pattern=>{const pp=pattern.map((p4=>{if(p4 instanceof RegExp)for(const f4 of p4.flags.split(""))flags.add(f4);return"string"==typeof p4?regExpEscape2(p4):p4===GLOBSTAR?GLOBSTAR:p4._src}));pp.forEach(((p4,i2)=>{const next2=pp[i2+1],prev=pp[i2-1];if(p4===GLOBSTAR&&prev!==GLOBSTAR)if(void 0===prev)void 0!==next2&&next2!==GLOBSTAR?pp[i2+1]="(?:\\/|"+twoStar+"\\/)?"+next2:pp[i2]=twoStar;else if(void 0===next2)pp[i2-1]=prev+"(?:\\/|"+twoStar+")?";else if(next2!==GLOBSTAR){pp[i2-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next2;pp[i2+1]=GLOBSTAR}}));return pp.filter((p4=>p4!==GLOBSTAR)).join("/")})).join("|");const[open,close]=set2.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";this.negate&&(re="^(?!"+re+").+$");try{this.regexp=new RegExp(re,[...flags].join(""))}catch(ex){this.regexp=!1}return this.regexp}slashSplit(p4){return this.preserveMultipleSlashes?p4.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(p4)?["",...p4.split(/\/+/)]:p4.split(/\/+/)}match(f4,partial=this.partial){this.debug("match",f4,this.pattern);if(this.comment)return!1;if(this.empty)return""===f4;if("/"===f4&&partial)return!0;const options=this.options;this.isWindows&&(f4=f4.split("\\").join("/"));const ff2=this.slashSplit(f4);this.debug(this.pattern,"split",ff2);const set2=this.set;this.debug(this.pattern,"set",set2);let filename=ff2[ff2.length-1];if(!filename)for(let i2=ff2.length-2;!filename&&i2>=0;i2--)filename=ff2[i2];for(let i2=0;i2{table[i2]=e3;revTable[e3]=i2}));revMap={};numMap={};for(let i2=0;i2<256;i2++){revMap[`00${i2.toString(16)}`.slice(-2)]=i2;numMap[i2]=`00${i2.toString(16)}`.slice(-2)}_hashString=function memorizeFuncWithLRUCache(func){const cache2=new LRUCache(100,1e5,!0);return key2=>{if(cache2.has(key2))return cache2.get(key2);const value=func(key2);cache2.set(key2,value);return value}}((async key2=>{const buff=writeString(key2),webcrypto5=await getWebCrypto();let digest=await webcrypto5.subtle.digest("SHA-256",buff);const len=key2.length;for(let i2=0;i2new Promise((res2=>{setTimeout((()=>{res2(result)}),ms)}));UNRESOLVED=Symbol("UNRESOLVED");promiseWithResolver="withResolvers"in Promise?function nativePromiseWithResolvers(){const p4=Promise.withResolvers(),{promise,resolve,reject}=p4;return{promise,resolve,reject}}:function polyfillPromiseWithResolvers(){let resolve,reject;return{promise:new Promise(((res2,rej)=>{resolve=res2;reject=rej})),resolve,reject}};noop=()=>{};TIMED_OUT_SIGNAL=Symbol("timed out");webcrypto2=globalThis.crypto;SALT=(new TextEncoder).encode("fancySyncForYou!");previousPassphrase="";_nonceV3=new Uint32Array(1);bufV3=new Uint8Array(12);previousDecryptionPassphrase="";KeyBuffs=new Map;decKeyBuffs=new Map;KEY_RECYCLE_COUNT=100;nonceBuffer=new Uint32Array(1);webcrypto3=globalThis.crypto;keyGCCount=5*KEY_RECYCLE_COUNT;decKeyIdx=0;decKeyMin=0;FallbackWeakRef="WeakRef"in globalThis?globalThis.WeakRef:(_a=class WeakRef{constructor(target){Object.defineProperty(this,"__target",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this.__target=target}deref(){return this.__target}},Object.defineProperty(_a,"__",{enumerable:!0,configurable:!0,writable:!0,value:console.warn("WeakRef is not supported in this environment. Using a fallback implementation. This may cause memory leaks. Please consider upgrading your browser or Node.js version. If you are on Android, please consider changing your WebView engine to a newer version. It is on the Developer Settings.")}),_a);EventHub=class{constructor(emitter){Object.defineProperty(this,"_emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});Object.defineProperty(this,"_allAssigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});this._emitter=null!=emitter?emitter:new EventTarget}_issueSignal(key2,callback){var _a8;let assigned=this._assigned.get(key2);void 0===assigned&&(assigned=new WeakMap);const controllerRef=assigned.get(callback);let controller=null==controllerRef?void 0:controllerRef.deref();if(!controller||controller.signal.aborted){controller=new AbortController;const refController=new FallbackWeakRef(controller);controller.signal.addEventListener("abort",(()=>{var _a9,_b4;null==(_a9=this._assigned.get(key2))||_a9.delete(callback);null==(_b4=this._allAssigned.get(key2))||_b4.delete(refController)}),{once:!0});assigned.set(callback,refController);this._assigned.set(key2,assigned);const allAssigned=null!=(_a8=this._allAssigned.get(key2))?_a8:new Set;allAssigned.add(refController);this._allAssigned.set(key2,allAssigned);return controller}return controller}emitEvent(event2,data){this._emitter.dispatchEvent(new CustomEvent(`${event2.toString()}`,{detail:null!=data?data:void 0}))}on(event2,callback,options){const key2=event2,controller=this._issueSignal(key2,callback);this._emitter.addEventListener(key2,(e3=>{callback(e3,e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)}),{...options,signal:controller.signal});return()=>this.off(event2,callback)}off(event2,callback){var _a8,_b4;const key2=event2;if(callback){const w2=null==(_a8=this._assigned.get(key2))?void 0:_a8.get(callback),controller=null==w2?void 0:w2.deref();null==controller||controller.abort()}else null==(_b4=this._allAssigned.get(key2))||_b4.forEach((w2=>{const controller=w2.deref();null==controller||controller.abort()}))}offAll(){for(const[key2]of this._allAssigned)this.off(key2)}onEvent(event2,callback,options){const key2=event2,controller=this._issueSignal(key2,callback);this._emitter.addEventListener(key2,(e3=>{callback(e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)}),{...options,signal:controller.signal});return()=>this.off(event2,callback)}once(event2,callback){return this.on(event2,callback,{once:!0})}onceEvent(event2,callback){return this.on(event2,((_,data)=>callback(data)),{once:!0})}waitFor(event2){return new Promise((resolve=>{this.onceEvent(event2,(data=>{resolve(data)}))}))}};InterceptiveEventTarget=class extends EventTarget{constructor(onBeforeDispatch,onAfterDispatch){super();Object.defineProperty(this,"_onBeforeDispatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_onAfterDispatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._onBeforeDispatch=onBeforeDispatch;this._onAfterDispatch=onAfterDispatch}dispatchEvent(event2){if(!event2.cancelable)return super.dispatchEvent(event2);if(this._onBeforeDispatch&&!this._onBeforeDispatch(event2))return!1;const result=super.dispatchEvent(event2);return result&&this._onAfterDispatch?this._onAfterDispatch(event2):result}};WrappedEvent=class extends CustomEvent{constructor(event2){super("wrappedEvent.event.globalChannel",{detail:{originalEvent:event2}})}};new class extends InterceptiveEventTarget{constructor(){super();globalThis.addEventListener("wrappedEvent.event.globalChannel",(event2=>{this.dispatchEvent(event2)}),{once:!0});this._onAfterDispatch=event2=>{event2 instanceof WrappedEvent?super.dispatchEvent(event2.detail.originalEvent):globalThis.dispatchEvent(new WrappedEvent(event2));return!0}}};eventHub=new EventHub;APIBase=class{constructor(){this._isReady=!1;this._isDisposed=!1}get isReady(){return this._isReady}get isDisposed(){return this._isDisposed}async applyOptions(options){var _a8,_b4,_c3,_d2;if(this.isDisposed)throw new Error("Cannot apply options to a disposed API");this.isReady&&await(null==(_a8=this.__teardownCurrentOptions)?void 0:_a8.call(this));await(null==(_b4=this.onApplyOptions)?void 0:_b4.call(this,options));this._options?this._options={...this._options,...options}:this._options=options;await(null==(_c3=this.onOptionsApplied)?void 0:_c3.call(this));await(null==(_d2=this.onReady)?void 0:_d2.call(this))}async init(options){var _a8;await this.applyOptions(options);await(null==(_a8=this.onInit)?void 0:_a8.call(this));return this}async __teardownCurrentOptions(){var _a8,_b4;await(null==(_a8=this.onDisposeCurrentOptions)?void 0:_a8.call(this));await(null==(_b4=this.tearDownCurrentOptions)?void 0:_b4.call(this))}reload(options){return this.applyOptions(options)}async dispose(){var _a8,_b4;await(null==(_a8=this.onDisposeCurrentOptions)?void 0:_a8.call(this));await(null==(_b4=this.onDisposed)?void 0:_b4.call(this))}};tasks=new Map;maxConcurrency=~~((navigator.hardwareConcurrency||8)/2);roundRobinIdx=0;workers=Array.from({length:maxConcurrency},(()=>({worker:function inlineWorker(scriptText){let blob=new Blob([scriptText],{type:"text/javascript"}),url=URL.createObjectURL(blob),worker=new Worker(url);URL.revokeObjectURL(url);return worker}('var M=(t,e)=>(e=Symbol[t])?e:Symbol.for("Symbol."+t),Lt=t=>{throw TypeError(t)};var L=function(t,e){this[0]=t,this[1]=e},K=(t,e,r)=>{var n=(a,s,c,l)=>{try{var f=r[a](s),y=(s=f.value)instanceof L,b=f.done;Promise.resolve(y?s[0]:s).then(g=>y?n(a==="return"?a:"next",s[1]?{done:g.done,value:g.value}:g,c,l):c({value:g,done:b})).catch(g=>n("throw",g,c,l))}catch(g){l(g)}},o=a=>i[a]=s=>new Promise((c,l)=>n(a,s,c,l)),i={};return r=r.apply(t,e),i[M("asyncIterator")]=()=>i,o("next"),o("throw"),o("return"),i},A=t=>{var e=t[M("asyncIterator")],r=!1,n,o={};return e==null?(e=t[M("iterator")](),n=i=>o[i]=a=>e[i](a)):(e=e.call(t),n=i=>o[i]=a=>{if(r){if(r=!1,i==="throw")throw a;return a}return r=!0,{done:!1,value:new L(new Promise(s=>{var c=e[i](a);c instanceof Object||Lt("Object expected"),s(c)}),1)}}),o[M("iterator")]=()=>o,n("next"),"throw"in e?n("throw"):o.throw=i=>{throw i},"return"in e&&n("return"),o},j=(t,e,r)=>(e=t[M("asyncIterator")])?e.call(t):(t=t[M("iterator")](),e={},r=(n,o)=>(o=t[n])&&(e[n]=i=>new Promise((a,s,c)=>(i=o.call(t,i),c=i.done,Promise.resolve(i.value).then(l=>a({value:l,done:c}),s)))),r("next"),r("return"),e);var St={minLogLevel:32},Tt=function(e,r=32,n){if(rP(i)),r=e.reduce((i,a)=>i+a.byteLength,0),n=new Uint8Array(r),o=0;return e.forEach(i=>{n.set(new Uint8Array(i),o),o+=i.byteLength}),n.buffer}function P(t){try{let e=globalThis.atob(t),r=e.length,n=new Uint8Array(r);for(let o=0;o{let n=new Blob([t],{type:"application/octet-binary"}),o=new FileReader;o.onload=function(i){var c,l;let a=((l=(c=i.target)==null?void 0:c.result)==null?void 0:l.toString())||"";if(t.byteLength!=0&&(a==""||a=="data:"))return r(new TypeError("Could not parse the encoded string"));let s=a.substring(a.indexOf(",")+1);e(s)},o.readAsDataURL(n)})}async function B(t){let e=t instanceof Uint8Array?t:new Uint8Array(t);return e.byteLength128)return Ct.encode(t);let e=new Uint8Array(t.length*4),r=t.length,n=0,o=0,i=0;for(;i>>6,e[n++]=128|o&63):o<55296||o>57343?(e[n++]=224|o>>>12,e[n++]=128|o>>>6&63,e[n++]=128|o&63):(o=(o-55296<<10|t.charCodeAt(i++)-56320)+65536,e[n++]=240|o>>>18,e[n++]=128|o>>>12&63,e[n++]=128|o>>>6&63,e[n++]=128|o&63);return e.slice(0,n)}function E(t){let e=t.length;if(e>128)return Mt.decode(t);let r=0,n=e,o="";for(;r>>10)+55296,(c&1023)+56320))}}o+=String.fromCharCode(...i)}return o}function*it(t,e){for(let r=t;r<=e;r++)yield r}var ce=1024*1024*30,Ut={},st={};[...it(192,447)].forEach((t,e)=>{Ut[e]=t,st[t]=e});function z(t){if(t.length==1)return I(t[0]);let e=t.map(i=>I(i)),r=e.reduce((i,a)=>i+a.byteLength,0),n=new Uint8Array(r),o=0;return e.forEach(i=>{n.set(new Uint8Array(i),o),o+=i.byteLength}),n.buffer}function I(t){let e=new Uint8Array(t.length),r=t.length;for(let n=0;n=38&&o<=126&&o!=58?e[n]=o:e[n]=st[o]}return e.buffer}var at={},ct={};for(let t=0;t<256;t++)at[`00${t.toString(16)}`.slice(-2)]=t,ct[t]=`00${t.toString(16)}`.slice(-2);function S(t){let e=t.length/2,r=new Uint8Array(e);for(let n=0;nct[e]).join("")}function J(t){if(t.length==0)return new Uint8Array().buffer;if(typeof t=="string"){if(t[0]==="%")return I(t.substring(1))}else if(t[0][0]==="%"){let[e,...r]=t;return z([e.substring(1),...r])}return O(t)}function N(t){return t.type==="text/plain"}function*kt(t,e){let r="";t:do{let n=t.shift();if(typeof n=="undefined"){yield r;break t}if(n.startsWith("```")||n.startsWith(" ```")||n.startsWith(" ```")||n.startsWith(" ```")){yield r,r=n+(t.length!=0?`\n`:"");e:do{let s=t.shift();if(typeof s=="undefined")break e;r+=s+(t.length!=0?`\n`:"")}while(t.length>0&&!(t[0].startsWith("```")||t[0].startsWith(" ```")||t[0].startsWith(" ```")||t[0].startsWith(" ```")));let o=r.endsWith("="),i=r.length>2048,a=t.shift();if(typeof a!="undefined"&&(r+=a,r+=t.length!=0?`\n`:""),!o&&!i){let s=/(.*?[;,:<])/g,c=r.split(s).filter(l=>l!="");for(let l of c)yield l}else yield r;r=""}else r+=n+(t.length!=0?`\n`:""),(r.length>=e||t.length==0||t[0]=="#"||r[0]=="#")&&(yield r,r="")}while(t.length>0)}var ft=10,ut="Segmenter"in Intl?new Intl.Segmenter(navigator.language,{granularity:"sentence"}):void 0;function*V(t,e){let r=t;do{let n=e,o=r.substring(0,n);r=r.substring(n),yield o}while(r!="")}function*lt(t,e,r){let n=ut.segment(t),o="",i="";for(let a of n){let s=a.segment;o==s||i.length0&&(yield*A(V(i,e))),i=s)}i.length>0&&(yield*A(V(i,e)))}function*Kt(t){for(let e of t){let r=-1,n=-1;do{if(n=e.indexOf(`\n`,r),n==-1){yield e.substring(r);break}for(;e[n]==`\n`;)n++;yield e.substring(r,n),r=n}while(n!=-1)}}function Pt(t,e,r){let o=Kt(typeof t=="string"?[t]:t),i=0,a=!1,s=!1;return function*(){let c=[];for(let l of o)l.startsWith("````")?i==0?(i=4,s=!0):i==4&&(i=0,a=!0):l.startsWith("```")&&(i==0?(i=3,s=!0):i==3&&(i=0,a=!0)),s&&(c.length>0&&(yield*A(lt(c.join(""),e,r)),c.length=0),s=!1),c.push(l),a&&(c.length>0&&(yield*A(V(c.join(""),e)),c.length=0),a=!1);c.length>0&&(i==0?yield*A(lt(c.join(""),e,r)):yield*A(V(c.join(""),e)))}}function It(t,e,r){return function*(){yield*A(V(t,e))}}function Nt(t,e,r,n,o){return!o||!ut?Dt(t,e,r,n):r?Pt(t,e,n):It(t,e,n)}function Dt(t,e,r,n){let o=typeof t=="string"?[t]:t;return function*(){for(let a of o)if(r){let s=a.split(`\n`),c=kt(s,n);for(let l of c){let f=l;do{let y=e;f.charCodeAt(y-1)!=f.codePointAt(y-1)&&y++,yield f.substring(0,y),f=f.substring(y)}while(f!="")}}else{let s=a;do{let c=e,l=s.substring(0,c);s=s.substring(c),yield l}while(s!="")}}}function*Ft(t,e,r=25,n){let o="",i=!1,a=e.length;for(let s of t){let c=s.length;if(n&&c>n){yield o+s,i=!1,o="";continue}let l=-1,f=0;t:do{if(l=s.indexOf(e,f),l==-1)break t;o+=s.slice(f,l)+e,o.length>r?(yield o,o="",i=!1):i=!0,f=l+a}while(le){let n=0;do{let o=n+e;if(o>r){yield t.substring(n);break}for(;t.charCodeAt(o-1)!=t.codePointAt(o-1);)o++;yield t.substring(n,o),n=o}while(nHt;)u+=n;let m=Wt([g]),h=Ft(m,`\n`,u),d=Rt(h,e);return function*(){yield*A(d)}}let a=!1,s=0;o&&o.endsWith(".pdf")?s=47:o&&o.endsWith(".json")&&(a=!0,s=44);let f=Math.max(a?100:1e5,Math.min(1e8,t.size)),y=1,b=f;for(;b>10;)b/=12.5,y++;return n=Math.floor(10**(y-1)),function(){return K(this,null,function*(){let T=t.size,u=0,m=new Uint8Array(yield new L(t.arrayBuffer()));do{let h=u+n,d=u+e,p,w=m.indexOf(s,h);w==-1&&(w=m.indexOf(ft,h)),w==-1?p=d:p=w10;)b/=12.5,y++;return n=Math.floor(10**(y-1)),function(){return K(this,null,function*(){let T=t.size,u=0;do{let m=e,h=new Uint8Array(yield new L(t.slice(u,u+e).arrayBuffer())),d=h.indexOf(a,n);m=d==-1?e:Math.min(e,d),d==-1&&(d=h.indexOf(ft,n));let p=h.slice(0,m);u+=p.length,yield yield new L(B(p))}while(u=w+b){let k=h[d-b],Et=Math.imul(k,m);p=p-Et|0,p=Math.imul(p,u),p=p+nt|0}else p=Math.imul(p,u),p=p+nt|0;let rt=d-w+1,Y=!1;if(rt>=y&&(p>>>0)%g===T&&(Y=!0),rt>=f&&(Y=!0),Y){let k=!0;H&&d+10)return[n.key,n.salt];n.count--}let o=15-t.length,i=e?(o>0?o:0)*1e3+121-o:1e5,a=new TextEncoder().encode(t),s=await x.subtle.digest({name:"SHA-256"},a),c=await x.subtle.importKey("raw",s,{name:"PBKDF2"},!1,["deriveKey"]),l=x.getRandomValues(new Uint8Array(16)),f=await x.subtle.deriveKey({name:"PBKDF2",salt:l,iterations:i,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!1,["encrypt"]);return mt.set(r,{key:f,salt:l,count:Z}),[f,l]}var Q=Z*5,W=0,At=0;async function xt(t,e,r){if(Q--,Q<0){Q=Z;let y=(W-At)/2;for(let[b,g]of F)g.count0?i:0)*1e3+121-i:1e5,s=new TextEncoder().encode(t),c=await x.subtle.digest({name:"SHA-256"},s),l=await x.subtle.importKey("raw",c,{name:"PBKDF2"},!1,["deriveKey"]),f=await x.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:a,hash:"SHA-256"},l,{name:"AES-GCM",length:256},!1,["decrypt"]);return F.set(n,{key:f,salt:e,count:0}),[f,e]}function Bt(t){return R!=null&&!t||(R=x.getRandomValues(new Uint8Array(12))),R}function Jt(){return q[0]++,q[0]>1e4&&Bt(!0),q}async function tt(t,e,r){let[n,o]=await zt(e,r),i=Bt(),a=Jt(),s=new Uint8Array([...i,...new Uint8Array(a.buffer)]),c=v(t),l=await x.subtle.encrypt({name:"AES-GCM",iv:s},n,c),f=""+await B(new Uint8Array(l));return`%${C(s)}${C(o)}${f}`}async function Xt(t,e,r){try{let n=t.substring(1,33),o=t.substring(33,65),i=t.substring(65),[a]=await xt(e,S(o),r),s=S(n),c=J(i),l=await x.subtle.decrypt({name:"AES-GCM",iv:s},a,c);return E(new Uint8Array(l))}catch(n){throw _("Couldn\'t decode! You should wrong the passphrases (V2)",16),_(n,16),n}}async function et(t,e,r){try{if(t[0]=="%")return t[1]==="~"?X(t,e):Xt(t,e,r);if(!t.startsWith("[")||!t.endsWith("]"))throw new Error("Encrypted data corrupted!");let n=t.substring(1,t.length-1).split(",").map(u=>u[0]==\'"\'?u.substring(1,u.length-1):u),[o,i,a]=n,[s]=await xt(e,S(a),r),c=S(i),l=atob(o),f=l.length,y=new Uint8Array(f);for(let u=f;u>=0;--u)y[u]=l.charCodeAt(u);let b=await x.subtle.decrypt({name:"AES-GCM",iv:c},s,y),g=E(new Uint8Array(b));return JSON.parse(g)}catch(n){throw _("Couldn\'t decode! You should wrong the passphrases",16),_(n,16),n}}var Re=new Uint8Array([83,97,108,116,101,100,95,95]);async function Zt(t){let e=t.key,r=t.dataSrc,n=t.pieceSize,o=t.plainSplit,i=t.minimumChunkSize,a=t.filename,s=t.useSegmenter,l=await(t.splitVersion==3?gt:t.splitVersion==2?dt:pt)(r,n,o,i,a,s),f=!1;try{for(var y=j(l()),b,g,T;b=!(g=await y.next()).done;b=!1){let u=g.value;f=!0,self.postMessage({key:e,result:u})}}catch(g){T=[g]}finally{try{b&&(g=y.return)&&await g.call(y)}finally{if(T)throw T[0]}}f||self.postMessage({key:e,result:""}),self.postMessage({key:e,result:null})}async function te(t){let e=t.key,{type:r,input:n,passphrase:o,autoCalculateIterations:i}=t;try{if(r=="encrypt"){let a=await tt(n,o,i);self.postMessage({key:e,result:a})}else if(r=="decrypt"){let a=await et(n,o,i);self.postMessage({key:e,result:a})}}catch(a){self.postMessage({key:e,error:a})}}self.onmessage=t=>{let e=t.data.data;if(e.type==="split")return Zt(e);if(e.type==="encrypt"||e.type==="decrypt")return te(e);self.postMessage({key:e.key,error:new Error("Invalid type")})};\n'),processing:0})));for(const inst of workers){inst.worker.onmessage=({data})=>{const key2=data.key,process2=tasks.get(key2);process2?"split"===process2.type?handleTaskSplit(process2,data):"encrypt"===process2.type||"decrypt"===process2.type?handleTaskEncrypt(process2,data):info("Invalid response type"+process2):info(`Invalid key ${key2} of background processing`,8)};inst.worker.onerror=()=>{inst.worker.terminate();workers.splice(workers.indexOf(inst),1)}}key=0;eventHub.on("platform-unloaded",(()=>{(function terminateWorker(){for(const inst of workers)inst.worker.terminate()})()}));serializedMap=new Map;queueCount=new Map;waitingProcessMap=new Map;shareSerializedMap=new Map;skipDuplicatedMap=new Map;Symbol("SKIPPED");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:promiseWithResolver()});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=promiseWithResolver());return await this._lockFull.promise}return READY_POST_SIGNAL}_notifyFree(){var _a8;null==(_a8=this._lockFull)||_a8.resolve(READY_POST_SIGNAL);this._lockFull=void 0}async _waitForReady(){for(;this.isRunningOut;){this._lockReady||(this._lockReady=promiseWithResolver());return await this._lockReady.promise}return READY_PICK_SIGNAL}_notifyReady(){var _a8;null==(_a8=this._lockReady)||_a8.resolve(READY_PICK_SIGNAL);this._lockReady=void 0}__onPosted(){super.__onPosted();this._notifyReady()}__onPicked(){super.__onPicked();this._notifyFree()}dispose(){super.dispose();if(this._lockFull){this._lockFull.reject(new Error(DISPOSE_ERROR));this._lockFull=void 0}if(this._lockReady){this._lockReady.reject(new Error(DISPOSE_ERROR));this._lockReady=void 0}}async post(item,timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return!1;if(this.tryPost(item))return!0;let p4;const tasks3=[this._waitForFree(),...timeout?[(p4=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p4||p4.cancel();if(r4!==READY_POST_SIGNAL)return!1}while(!this._isDisposed);return!1}async pick(timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return NOT_AVAILABLE;const item=this.tryPick();if(item!==NOT_AVAILABLE)return item;let p4;const tasks3=[this._waitForReady(),...timeout?[(p4=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p4||p4.cancel();if(r4!==READY_PICK_SIGNAL)return NOT_AVAILABLE}while(!this.isDisposed);return NOT_AVAILABLE}};InboxWithEvent=class extends Inbox{constructor(capacity,onProgress){super(capacity);Object.defineProperty(this,"_callback",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processed",{enumerable:!0,configurable:!0,writable:!0,value:0});this._callback=onProgress}__onProgress(){var _a8;this._processed++;const event2=new CustomEvent("progress",{detail:this.state});null==(_a8=this._callback)||_a8.call(this,event2.detail)}setOnProgress(callback){this._callback=callback}};(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:promiseWithResolver()});Object.defineProperty(this,"_onProgress",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{name,assigned}=params;this._inbox=assigned;this._name=null!=name?name:this.constructor.name;yieldMicrotask().then((()=>this._mainLoop()));this._inbox.onDisposed.then((()=>this.dispose()))}get stateDetail(){const hasStarted=0!=this._totalFetched,hasAnyUnprocessed=this._totalFetched!=this._totalProcessed,isBusy=0!=this._inbox.state.size||hasAnyUnprocessed;return{totalFetched:this._totalFetched,inboxDetail:this._inbox.state,totalProcessed:this._totalProcessed,state:this._state,hasStarted,isBusy}}onProgress(){var _a8;try{null==(_a8=this._onProgress)||_a8.call(this,this.stateDetail)}catch(e3){}}setOnProgress(callback){this._onProgress=callback}async _mainLoop(){var _a8;this._state=ClerkState.STALLED;this.onProgress();await yieldMicrotask();do{this._state=ClerkState.IDLE;this.onProgress();try{const item=await this._inbox.pick(void 0,[this._disposePromise.promise]);if(item===SENTINEL_FLUSH||item===SENTINEL_FINISHED){await(null==(_a8=this._onSentinel)?void 0:_a8.call(this,item));continue}if(item===NOT_AVAILABLE){if(this._inbox.isDisposed){this._state=ClerkState.DISPOSED;break}continue}this._totalFetched++;this._state=ClerkState.WORKING;this.onProgress();try{await this._onPick(item);this._totalSuccess++}catch(ex){this._totalFailed++;Logger("Error on processing job on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}this._totalProcessed++;this.onProgress()}catch(ex){if(ex instanceof Error&&ex.message!==DISPOSE_ERROR){Logger("Error on picking item on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}}}while(!this._inbox.isDisposed&&!this._disposed);this._state=ClerkState.IDLE;this._disposed?this._state=ClerkState.DISPOSED:this.dispose();this.onProgress()}dispose(){this._disposePromise.resolve();this._disposed=!0;this._state=ClerkState.DISPOSED}get onDisposed(){return this._disposePromise.promise}};Clerk=class extends ClerkBase{async _onPick(item){return await this._job(item)}constructor(params){super(params);Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._job=params.job}};ClerkGroup=class{constructor(params){var _a8;Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_nameBase",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_hiredCount",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_instantiate",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{assigned,job,instantiate,initialMemberCount}=params;this._assigned=assigned;this._instantiate=instantiate;this._job=job;this._nameBase=null!=(_a8=params.name)?_a8:this.constructor.name;this._clerks=[];for(let i2=0;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()))}};Porter=class extends ClerkBase{async _flush(){this._timeoutTimer=void 0;if(this._buffer.length>0){const previous=this._outgoing.tryCancelPost();if(previous!==NOT_AVAILABLE)if(previous.length>=this._maxSize)this._outgoing.tryPost(previous);else{this._buffer=[...previous,...this._buffer];const filling=this._buffer.splice(0,this._maxSize);if(!1===this._outgoing.tryPost(filling))throw new Error("This should not happen")}const postingItems=this._buffer.splice(0,this._maxSize);if(postingItems.length>0){await this._outgoing.post(postingItems);this.onProgress()}}}get stateDetail(){const stateDetail=super.stateDetail;stateDetail.totalProcessed=this._totalProcessed-this._buffer.length;stateDetail.isBusy=stateDetail.isBusy||!!this._timeoutTimer||this._buffer.length>0;return stateDetail}async _onSentinel(item){(item===SENTINEL_FLUSH||item===SENTINEL_FINISHED)&&await this._flush()}async _onPick(item){this._buffer.push(item);this._buffer.length>=this._maxSize?await this._flush():this._timeout&&(this._timeoutTimer||(this._timeoutTimer=setTimeout((()=>{this._flush()}),this._timeout)))}flush(){return this._flush()}async changeParams(params){let anyChanged=!1;if(null!=params.timeout&&this._timeout!==params.timeout){this._timeout=params.timeout;anyChanged=!0}if(null!=params.maxSize&&this._maxSize!==params.maxSize){this._maxSize=params.maxSize;anyChanged=!0}anyChanged&&await this.flush()}constructor(params){super({assigned:params.from});Object.defineProperty(this,"_outgoing",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_timeoutTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_flushing",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()});Object.defineProperty(this,"_separateChunk",{enumerable:!0,configurable:!0,writable:!0,value:!1});this._outgoing=params.to;this._timeout=params.timeout;this._maxSize=params.maxSize}dispose(){this._timeoutTimer&&clearTimeout(this._timeoutTimer);super.dispose()}};Notifier=class{constructor(){Object.defineProperty(this,"_p",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolver()});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=promiseWithResolver()}}get nextNotify(){this.isUsed=!0;return this._p.promise}};allRunningProcessors=new Set([]);QueueProcessor=class{get nowProcessing(){return this.processingEntities}get totalNowProcessing(){var _a8;return this.nowProcessing+((null==(_a8=this._pipeTo)?void 0:_a8.totalNowProcessing)||0)}get remaining(){return this._queue.length+this.processingEntities+this.waitingEntries}get totalRemaining(){var _a8;return this.remaining+((null==(_a8=this._pipeTo)?void 0:_a8.totalRemaining)||0)}updateStatus(setFunc){setFunc();this._updateReactiveSource()}suspend(){this._isSuspended=!0;this._hub.emitEvent("tickSuspended");return this}resume(){this._isSuspended=!1;this._hub.emitEvent("tickResumed");return this}resumePipeLine(){var _a8;null==(_a8=this._pipeTo)||_a8.resumePipeLine();this.resume();return this}startPipeline(){this.root.resumePipeLine();return this}get root(){return void 0===this._root?this:this._root}_initEventHub(){this._hub.onEvent("tickResumed",(()=>this._run()))}async _waitFor(keys3,timeout){const items=keys3.map((key2=>{const p4=promiseWithResolver(),releaser=this._hub.onEvent(key2,(()=>{p4.resolve(key2)}));p4.promise=p4.promise.finally((()=>{releaser()}));return p4})),timer=timeout?cancelableDelay(timeout):void 0,tasks3=[...items.map((i2=>i2.promise)),...timer?[timer.promise]:[]],ret=await Promise.race(tasks3);items.forEach((i2=>i2.resolve(void 0)));return ret}_triggerTickDelay(){this._delayTimer||(this._delayTimer=setTimeout((()=>{this._hub.emitEvent("tickDelayTimeout");this._delayTimer=void 0})))}_clearTickDelay(){if(this._delayTimer){clearTimeout(this._delayTimer);this._delayTimer=void 0}}_notifyIfIdle(){return this.root.__notifyIfIdle()}__notifyIfIdle(){0!=this._processCount||this._canCollectBatch()||this._hub.emitEvent("idle");this._pipeTo&&this._pipeTo.__notifyIfIdle()}_onTick(){if(this._canCollectBatch())if(this._nextProcessNeedsImmediate){this._clearTickDelay();this._nextProcessNeedsImmediate=!1;this._hub.emitEvent("tickImmediate")}else if(this._queue.length>this.yieldThreshold){this._clearTickDelay();this._hub.emitEvent("yielded")}else{if(!this.delay){this._clearTickDelay();this._hub.emitEvent("tickDelayTimeout");return}this._delayTimer||this._triggerTickDelay()}else{this._notifyIfIdle();this._clearTickDelay();this._hub.emitEvent("tickEmpty")}}constructor(processor,params,items,enqueueProcessor){var _a8,_b4,_c3,_d2,_e2,_f,_g;Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_processor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_enqueueProcessor",{enumerable:!0,configurable:!0,writable:!0,value:(queue2,entity)=>(queue2.push(entity),queue2)});Object.defineProperty(this,"_isSuspended",{enumerable:!0,configurable:!0,writable:!0,value:!0});Object.defineProperty(this,"_nextProcessNeedsImmediate",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_pipeTo",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_root",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_remainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_totalRemainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingEntitiesReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_keepResultUntilDownstreamConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_keptResult",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_runOnUpdateBatch",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}});Object.defineProperty(this,"concurrentLimit",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"yieldThreshold",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"delay",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"maintainDelay",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"processingEntities",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"waitingEntries",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_hub",{enumerable:!0,configurable:!0,writable:!0,value:new EventHub});Object.defineProperty(this,"_delayTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_intervalPaceMaker",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingBatches",{enumerable:!0,configurable:!0,writable:!0,value:new Set});Object.defineProperty(this,"addProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.add(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"deleteProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.delete(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"_processing",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_collected",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processCount",{enumerable:!0,configurable:!0,writable:!0,value:0});this._root=this;this._processor=processor;this.batchSize=null!=(_a8=null==params?void 0:params.batchSize)?_a8:1;this.yieldThreshold=null!=(_c3=null!=(_b4=null==params?void 0:params.yieldThreshold)?_b4:null==params?void 0:params.batchSize)?_c3:0;this.concurrentLimit=null!=(_d2=null==params?void 0:params.concurrentLimit)?_d2:1;this.delay=null!=(_e2=null==params?void 0:params.delay)?_e2:0;this.maintainDelay=null!=(_f=null==params?void 0:params.maintainDelay)&&_f;this.interval=null!=(_g=null==params?void 0:params.interval)?_g:0;(null==params?void 0:params.keepResultUntilDownstreamConnected)&&(this._keepResultUntilDownstreamConnected=params.keepResultUntilDownstreamConnected);(null==params?void 0:params.remainingReactiveSource)&&(this._remainingReactiveSource=null==params?void 0:params.remainingReactiveSource);(null==params?void 0:params.totalRemainingReactiveSource)&&(this._totalRemainingReactiveSource=null==params?void 0:params.totalRemainingReactiveSource);(null==params?void 0:params.processingEntitiesReactiveSource)&&(this._processingEntitiesReactiveSource=null==params?void 0:params.processingEntitiesReactiveSource);void 0!==(null==params?void 0:params.suspended)&&(this._isSuspended=null==params?void 0:params.suspended);enqueueProcessor&&this.replaceEnqueueProcessor(enqueueProcessor);void 0!==(null==params?void 0:params.pipeTo)&&this.pipeTo(params.pipeTo);this._intervalPaceMaker=new PaceMaker(this.interval);items&&this.enqueueAll(items);allRunningProcessors.add(this);this._initClerks();this._initEventHub();this.resume()}replaceEnqueueProcessor(processor){this._enqueueProcessor=processor;return this}modifyQueue(processor){this._queue=processor(this._queue);this._onTick()}clearQueue(){this._queue=[];this._onTick()}onUpdateProgress(proc){this._runOnUpdateBatch=proc;return this}pipeTo(pipeTo){this._pipeTo=pipeTo;this._pipeTo._root=this.root;if(this._keptResult.length>0){const temp=[...this._keptResult];this._keptResult=[];this._pipeTo.enqueueAll(temp)}return pipeTo}isIdle(){return this._isIdle()&&(!this._pipeTo||this._pipeTo.isIdle())}_isIdle(){return 0==this.totalRemaining}async _waitForIdle(){if(this._isSuspended)return Promise.resolve();if(this._isIdle())return Promise.resolve();do{const r4=await this._waitFor(["tickEmpty","tick","tickSuspended","suspended","idle"]);if("tickSuspended"===r4)break;if("suspended"==r4)break;if("tickEmpty"==r4)break;if("idle"==r4)break}while(!this._isIdle());return Promise.resolve()}idleDetectors(){const thisPromise=this._waitForIdle();return this._pipeTo?[thisPromise,...this._pipeTo.idleDetectors()]:[thisPromise]}get isSuspended(){var _a8;return this._isSuspended||(null==(_a8=this._pipeTo)?void 0:_a8.isSuspended)||!1}_updateReactiveSource(){this.root.updateReactiveSource()}updateReactiveSource(){this._pipeTo&&this._pipeTo.updateReactiveSource();this._remainingReactiveSource&&(this._remainingReactiveSource.value=this.remaining);this._totalRemainingReactiveSource&&(this._totalRemainingReactiveSource.value=this.totalRemaining);this._processingEntitiesReactiveSource&&(this._processingEntitiesReactiveSource.value=this.nowProcessing)}_updateBatchProcessStatus(){this._updateReactiveSource();this._runOnUpdateBatch()}_collectBatch(){return this._queue.splice(0,this.batchSize)}_canCollectBatch(){return 0!==this._queue.length}enqueue(entity){this._queue=this._enqueueProcessor(this._queue,entity);this._updateBatchProcessStatus();this._onTick();return this}enqueueAll(entities){let queue2=this._queue;for(const v2 of entities)queue2=this._enqueueProcessor(queue2,v2);this._queue=queue2;this._updateBatchProcessStatus();this._onTick();return this}requestNextFlush(){this._nextProcessNeedsImmediate=!0;this._onTick()}async _waitForSuspended(){}flush(){if(this._isSuspended)return Promise.resolve(!1);this.requestNextFlush();return this.waitForAllDownstream()}async waitForAllDownstream(timeout){const baseTasks=[];timeout&&baseTasks.push(delay(timeout,RESULT_TIMED_OUT));do{const idleTasks=this.idleDetectors(),tasks3=[...baseTasks,Promise.all(idleTasks)];if(await Promise.race(tasks3)===RESULT_TIMED_OUT)return!1}while(!this.isIdle());return!0}waitForAllProcessed(timeout){this.root.startPipeline();return this.root.waitForAllDownstream(timeout)}async waitForAllDoneAndTerminate(timeout){this.root.startPipeline();const r4=await this.root.waitForAllDownstream(timeout);this.terminateAll();return r4}async _runProcessor(items){const ret=await this._processor(items);ret&&(this._pipeTo?this._pipeTo.enqueueAll(ret):this._keepResultUntilDownstreamConnected&&this._keptResult.push(...ret))}async*pump(){do{const ticked=await this._waitFor(["tickImmediate","yielded","tickSuspended","tickDelayTimeout","tickSuspended"]);L2:do{const items=this._collectBatch();if(0==items.length)break L2;yield items}while(this._canCollectBatch());if("tickSuspended"==ticked)break}while(!this._isSuspended)}_initClerks(){this._collected=new Inbox(2*this.concurrentLimit);this._clerks=new ClerkGroup({assigned:this._collected,job:async items=>{const batchLength=items.length;this.updateStatus((()=>{this.processingEntities+=batchLength;this.waitingEntries-=batchLength}));await this._intervalPaceMaker.paced;this._processCount++;try{await this._runProcessor(items)}catch(ex){Logger("Processor error!");Logger(ex,LOG_LEVEL_VERBOSE)}this.updateStatus((()=>{this.processingEntities-=batchLength}));this._processCount--;0==this._processCount&&this._notifyIfIdle()},initialMemberCount:this.concurrentLimit,instantiate:params=>new Clerk(params)})}async _process(){if(!this._processing&&!this._isSuspended)try{this._processing=!0;do{const batchPump=this.pump();for await(const batch of batchPump){if(!batch||0===batch.length){this._hub.emitEvent("tickEmpty");continue}const batchLength=batch.length;this.updateStatus((()=>{this.waitingEntries+=batchLength}));await this._collected.post(batch)}}while(!this._isSuspended);this._hub.emitEvent("suspended")}finally{this._processing=!1}}_run(){this._isSuspended||this._processing||fireAndForget((()=>this._process()))}terminateAll(){this.root.terminate()}terminate(){if(this._pipeTo){this._pipeTo.terminate();this._pipeTo=void 0}this._isSuspended=!0;this._enqueueProcessor=()=>[];this._processor=()=>Promise.resolve([]);this.clearQueue();this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._collected.dispose();this._clerks.dispose();this._queue.length=0;allRunningProcessors.delete(this)}};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 err2,d4=e3.data,ed=d4.$e$;if(ed){(err2=new Error(ed[0])).code=ed[1];err2.stack=ed[2];cb2(err2,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,p4,m3){var o2=p4/8|0;return(d4[o2]|d4[o2+1]<<8)>>(7&p4)&m3};bits16=function(d4,p4){var o2=p4/8|0;return(d4[o2]|d4[o2+1]<<8|d4[o2+2]<<16)>>(7&p4)};shft=function(p4){return(p4+7)/8|0};slc=function(v2,s2,e3){(null==s2||s2<0)&&(s2=0);(null==e3||e3>v2.length)&&(e3=v2.length);return new u8(v2.subarray(s2,e3))};ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];err=function(ind,msg,nt){var e3=new Error(msg||ec[ind]);e3.code=ind;Error.captureStackTrace&&Error.captureStackTrace(e3,err);if(!nt)throw e3;return e3};inflt=function(dat,st,buf,dict){var noBuf,resize,noSt,cbuf,final,pos,bt2,lm,dm,lbt,dbt,tbts,type,s2,l2,t3,hLit,hcLen,tl,ldt,clt,i2,clb,clbmsk,clm,r4,c3,n3,lt,dt,lms,dms,lpos,sym,add,b3,d4,dsym,end,shift,dend,sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);resize=(noBuf=!buf)||2!=st.i;noSt=st.i;noBuf&&(buf=new u8(3*sl));cbuf=function(l3){var nbuf,bl2=buf.length;if(l3>bl2){(nbuf=new u8(Math.max(2*bl2,l3))).set(buf);buf=nbuf}};final=st.f||0,pos=st.p||0,bt2=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n;tbts=8*sl;do{if(!lm){final=bits(dat,pos,1);type=bits(dat,pos+1,3);pos+=3;if(!type){if((t3=(s2=shft(pos)+4)+(l2=dat[s2-4]|dat[s2-3]<<8))>sl){noSt&&err(0);break}resize&&cbuf(bt2+l2);buf.set(dat.subarray(s2,t3),bt2);st.b=bt2+=l2,st.p=pos=8*t3,st.f=final;continue}if(1==type)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(2==type){hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;tl=hLit+bits(dat,pos+5,31)+1;pos+=14;ldt=new u8(tl);clt=new u8(19);for(i2=0;i2>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 err(1);if(pos>tbts){noSt&&err(0);break}}resize&&cbuf(bt2+131072);lms=(1<>4;if((pos+=15&c3)>tbts){noSt&&err(0);break}c3||err(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||err(3);pos+=15&d4;dt=fd[dsym];if(dsym>3){b3=fdeb[dsym];dt+=bits16(dat,pos)&(1<tbts){noSt&&err(0);break}resize&&cbuf(bt2+131072);end=bt2+add;if(bt2>8};wbits16=function(d4,p4,v2){v2<<=7&p4;var o2=p4/8|0;d4[o2]|=v2;d4[o2+1]|=v2>>8;d4[o2+2]|=v2>>16};hTree=function(d4,mb){var i2,s2,t22,v2,l2,r4,i0,i1,i22,maxSym,tr,mbt,dt,lft,cst,i2_1,i2_2,i2_3,t3=[];for(i2=0;i2maxSym&&(maxSym=t22[i2].s);tr=new u16(maxSym+1);if((mbt=ln(t3[i1-1],tr,0))>mb){i2=0,dt=0;cst=1<<(lft=mbt-mb);t22.sort((function(a2,b3){return tr[b3.s]-tr[a2.s]||a2.f-b3.f}));for(;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,p4,dat.subarray(bs2,bs2+bl2));wbits(out,p4,1+(dtlen15&&(wbits(out,p4,clct[i2]>>5&127),p4+=clct[i2]>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i2=0;i2255){wbits16(out,p4,lm[257+(len=sym>>18&31)]),p4+=ll[len+257];len>7&&(wbits(out,p4,sym>>23&31),p4+=fleb[len]);wbits16(out,p4,dm[dst=31&sym]),p4+=dl[dst];dst>3&&(wbits16(out,p4,sym>>5&8191),p4+=fdeb[dst])}else wbits16(out,p4,lm[sym]),p4+=ll[sym];wbits16(out,p4,lm[256]);return p4+ll[256]};deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);et=new u8(0);dflt=function(dat,lvl,plvl,pre,post,st){var opt,n3,c3,msk_1,prev,head2,bs1_1,bs2_1,hsh,syms,lf,df,lc_1,eb,i2,li,wi,bs2,hv,imod,pimod,rem,j2,l2,d4,ch_1,dif,maxn,maxd,ml,nl,mmd,md,ti,cd2,lin,din,e3,s2=st.z||dat.length,o2=new u8(pre+s2+5*(1+Math.ceil(s2/7e3))+post),w2=o2.subarray(pre,o2.length-post),lst=st.l,pos=7&(st.r||0);if(lvl){pos&&(w2[0]=st.r>>3);n3=(opt=deo[lvl-1])>>13,c3=8191&opt;msk_1=(1<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,t3,dt=fn(),st=fn.toString(),ks=st.slice(st.indexOf("[")+1,st.lastIndexOf("]")).replace(/\s+/g,"").split(",");for(i2=0;i2!!uri.startsWith("https://")||!!uri.startsWith("http://");checkRemoteVersion=async(db,migrate,barrier=10)=>{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}};wrappedInflate=wrapFflateFunc((function inflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err(7);return cbify(data,opts,[bInflt],(function(ev){return pbf(inflateSync(ev.data[0],gopt(ev.data[1])))}),1,cb2)}));wrappedDeflate=wrapFflateFunc((function deflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err(7);return cbify(data,opts,[bDflt],(function(ev){return pbf(deflateSync(ev.data[0],ev.data[1]))}),0,cb2)}));replicationFilter=(db,compress)=>{db.transform({incoming:async doc=>compress?await async function compressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;if(doc.data.startsWith("LZ"))return doc;const oldData=doc.data,compressed=await async function _compressText(text2){const converted=function tryConvertBase64ToArrayBuffer(base64){try{const b64F=base64.replace(/\r|\n/g,"");if(!regexpBase64.test(b64F))return!1;const binary_string=globalThis.atob(b64F);if(globalThis.btoa(binary_string)!==b64F)return!1;const len=binary_string.length,bytes=new Uint8Array(len);for(let i2=0;i2newData.length&&(doc.data=newData);return doc}(doc):doc,outgoing:async doc=>await async function decompressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;doc.data.startsWith("LZ")&&(doc.data=await async function _decompressText(compressed){if(0==compressed.length)return"";const converted="~"==compressed[0],src=compressed.substring(converted?1:0);if(0==src.length)return"";const ab2=new Uint8Array(base64ToArrayBuffer(src));if(0==ab2.length)return"";const ret=await wrappedInflate(new Uint8Array(ab2),{consume:!0});if(converted)return await arrayBufferToBase64Single(ret);const response=new Blob([ret]);return await response.text()}(doc.data.substring(4)));return doc}(doc)})};EDEN_ENCRYPTED_KEY="h:++encrypted";preprocessOutgoing=async doc=>await Promise.resolve(doc);enableEncryption=(db,passphrase,useDynamicIterationCount,migrationDecrypt)=>{const decrypted=new Map,incoming=async doc=>{const saveDoc={...doc};if(isEncryptedChunkEntry(saveDoc)||isSyncInfoEntry(saveDoc))try{if(!("e_"in saveDoc)){saveDoc.data=await encrypt2(saveDoc.data,passphrase,useDynamicIterationCount);saveDoc.e_=!0}}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}(function shouldEncryptEden(doc){return"eden"in doc&&!("h:++encrypted"in doc.eden)})(saveDoc)&&(saveDoc.eden={[EDEN_ENCRYPTED_KEY]:{data:await encrypt2(JSON.stringify(saveDoc.eden),passphrase,useDynamicIterationCount),epoch:999999}});if(isObfuscatedEntry(saveDoc))try{const path2=getPath(saveDoc);isPathProbablyObfuscated(path2)||(saveDoc.path=await async function obfuscatePath(path2,passphrase,autoCalculateIterations){const dataBuf=writeString(path2),[key2,salt,iv]=await async function getKeyForObfuscatePath(passphrase,dataBuf,autoCalculateIterations){const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto3.subtle.digest({name:"SHA-256"},passphraseBin),buf2=new Uint8Array(await webcrypto3.subtle.digest({name:"SHA-256"},new Uint8Array([...dataBuf,...passphraseBin]))),salt=buf2.slice(0,16),iv=buf2.slice(16,32),keyMaterial=await webcrypto3.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]);return[await webcrypto3.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]),salt,iv]}(passphrase,dataBuf,autoCalculateIterations),encryptedDataArrayBuffer=await webcrypto3.subtle.encrypt({name:"AES-GCM",iv},key2,dataBuf),encryptedData2=await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`}(path2,passphrase,useDynamicIterationCount))}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}return saveDoc};preprocessOutgoing=incoming;db.transform({incoming,outgoing:async doc=>{var _a8,_b4;const loadDoc={...doc},_isChunkOrSyncInfo=isEncryptedChunkEntry(loadDoc)||isSyncInfoEntry(loadDoc),_isObfuscatedEntry=isObfuscatedEntry(loadDoc),_shouldDecryptEden=function shouldDecryptEden(doc){return"eden"in doc&&"h:++encrypted"in doc.eden}(loadDoc);if(_isChunkOrSyncInfo||_isObfuscatedEntry||_shouldDecryptEden){if(migrationDecrypt&&decrypted.has(loadDoc._id))return loadDoc;try{if(_isChunkOrSyncInfo){loadDoc.data=await decrypt2(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}else if("e_"in loadDoc){loadDoc.data=await decrypt2(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt2(path2,passphrase,useDynamicIterationCount))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt2(loadDoc.eden["h:++encrypted"].data,passphrase,useDynamicIterationCount)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex){if(!useDynamicIterationCount){Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_b4=loadDoc._rev)?void 0:_b4.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex}try{_isChunkOrSyncInfo&&(loadDoc.data=await decrypt2(loadDoc.data,passphrase,!1));if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt2(path2,passphrase,!1))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt2(loadDoc.eden["h:++encrypted"].data,passphrase,!1)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex2){if(migrationDecrypt&&"SyntaxError"==ex2.name)return loadDoc;Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex2,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_a8=loadDoc._rev)?void 0:_a8.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex2}}}return loadDoc}})};_requestToCouchDBFetch=async(baseUri,username,password,path2,body,method)=>{const utf8str=String.fromCharCode.apply(null,[...writeString(`${username}:${password}`)]),encoded=globalThis.btoa(utf8str),uri=`${baseUri}/${path2}`,requestParam={url:uri,method:method||(body?"PUT":"GET"),headers:new Headers({authorization:"Basic "+encoded,"content-type":"application/json"}),contentType:"application/json",body:JSON.stringify(body)};return await fetch(uri,requestParam)};SYMBOL_A=Symbol("a");SYMBOL_B=Symbol("b");globalSlipBoard=new class{constructor(){Object.defineProperty(this,"_clip",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}isAwaiting(type,key2){return this._clip.has(`${String(type)}:${key2}`)}issueAndProceed(type,key2="",opt){this.isAwaiting(type,key2)||fireAndForget((async()=>{try{const ret=await opt.callback();this.submit(type,key2,ret)}catch(ex){opt.submitAsSuccess?this.submit(type,key2,opt.transformError?opt.transformError(ex):ex):opt.dropSlipWithRisks?this._clip.delete(type):this.reject(type,key2,ex)}}));return this.awaitNext(type,key2)}async awaitNext(type,key2="",{timeout,onNotAwaited}={timeout:void 0,onNotAwaited:void 0}){let taskPromise=this._clip.get(`${String(type)}:${key2}`);if(!taskPromise){taskPromise=promiseWithResolver();taskPromise.promise=taskPromise.promise.then((ret=>ret)).finally((()=>{this._clip.delete(`${String(type)}:${key2}`)}));this._clip.set(`${String(type)}:${key2}`,taskPromise);onNotAwaited&&fireAndForget((async()=>(await yieldMicrotask(),onNotAwaited())))}if(timeout){const cDelay=cancelableDelay(timeout);return Promise.race([cDelay.promise,taskPromise.promise.then((ret=>ret)).finally((()=>cDelay.cancel()))])}return await taskPromise.promise}submit(type,key2,data){const taskPromise=this._clip.get(`${String(type)}:${key2}`);taskPromise&&taskPromise.resolve(data)}submitToAll(type,prefix,data){for(const[key2,taskPromise]of this._clip.entries())`${String(key2)}`.startsWith(`${String(type)}:${prefix}`)&&taskPromise.resolve(data)}reject(type,key2="",reason){const taskPromise=this._clip.get(`${String(type)}:${key2}`);taskPromise&&taskPromise.reject(reason)}};throttle=(func,timeout)=>{let timer,lastTime=0;return(...args)=>{if(lastTime){clearTimeout(timer);const delayTime=timeout-(Date.now()-lastTime);timer=setTimeout((()=>{func(...args);lastTime=Date.now()}),delayTime)}else{func(...args);lastTime=Date.now()}}};isIndexDBCmpExist=void 0!==(null==(_a3=null==globalThis?void 0:globalThis.indexedDB)?void 0:_a3.cmp);globalConcurrencyController=Semaphore(50);map={"\n":"\\n","\r":"\\r","\\":"\\\\"};revMap2={"\\n":"\n","\\r":"\r","\\\\":"\\"};previousValues=new Map;MARK_DELETED="__DELETED";MARK_ISARRAY="__ARRAY";MARK_SWAPPED="__SWAP";CustomRegExp=class{constructor(regexp,flags){const[negate3,exp]=parseCustomRegExp(regexp);this.pattern=exp;this.regexp=new RegExp(exp,flags);this.negate=negate3}test(str){return this.negate?!this.regexp.test(str):this.regexp.test(str)}};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]);epochFNV1a=2166136261;c1=3432918353;c2=461845907;r1=15;r2=13;m=5;n=3864292196;new TextEncoder;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)}}();charNewLine="\n".charCodeAt(0);segmenter="Segmenter"in Intl?new Intl.Segmenter(navigator.language,{granularity:"sentence"}):void 0;MAX_ITEMS=100;globalSlipBoard2=globalSlipBoard;BatchReader=class{constructor(db){this.requestChunkInbox=new Inbox(2e3);this.collectChunkBatch=new InboxWithEvent(100);this._porter=new Porter({from:this.requestChunkInbox,to:this.collectChunkBatch,timeout:30,maxSize:50});this._readers=new ClerkGroup({assigned:this.collectChunkBatch,initialMemberCount:3,name:"localChunkReader",instantiate:params=>new Clerk(params),job:async item=>{const chunk=await this.localDatabase.allDocs({keys:item,include_docs:!0});for(const row of chunk.rows)if("error"in row||row.value.deleted)globalSlipBoard2.submit("read-chunk",row.key,{_id:row.key,error:"NOT_FOUND"});else{const doc=row.doc;this.hashCaches.set(doc._id,doc.data);globalSlipBoard2.submit("read-chunk",doc._id,doc)}}});this._db=db}get localDatabase(){return this._db.localDatabase}get hashCaches(){return this._db.hashCaches}get settings(){return this._db.settings}get env(){return this._db.env}async readChunk(id,timeout){var _a8;const cached=this.hashCaches.get(id);if("string"==typeof cached)return Promise.resolve({_id:id,data:cached,type:"leaf"});const p4=await globalSlipBoard2.awaitNext("read-chunk",`${id}`,{onNotAwaited:()=>{this.requestChunkInbox.post(id)}});if(!p4||"error"in p4&&"NOT_FOUND"===p4.error){if(timeout){const r4=await globalSlipBoard2.awaitNext("read-chunk",`${id}`,{timeout});return r4===TIMED_OUT_SIGNAL?{_id:id,error:"TIMED_OUT"}:!r4||"error"in r4?{_id:id,error:null!=(_a8=null==r4?void 0:r4.error)?_a8:"UNKNOWN ERROR"}:r4}return{_id:id,error:"NOT_FOUND"}}return p4}};ChunkCollector=class{constructor(db){this.requestChunkInbox=new Inbox(2e3);this.collectChunkBatch=new InboxWithEvent(100);this.requestFetchChunkInbox=new Inbox(2e3);this.fetchChunkBatch=new Inbox(2e3);this._porter=new Porter({from:this.requestChunkInbox,to:this.collectChunkBatch,timeout:100,maxSize:50});this._collectors=new ClerkGroup({assigned:this.collectChunkBatch,initialMemberCount:3,instantiate:params=>new Clerk(params),job:async item=>{const chunk=await this.localDatabase.allDocs({keys:item,include_docs:!0});for(const row of chunk.rows)if("error"in row)await this.requestFetchChunkInbox.post(row.key);else{const doc=row.doc;this.hashCaches.set(doc._id,doc.data);globalSlipBoard2.submit("retrieve-chunk",doc._id,doc)}}});this._porterFetch=new Porter({from:this.requestFetchChunkInbox,to:this.fetchChunkBatch,timeout:25,maxSize:100});this._paceMaker=new PaceMaker(300);this._fetchers=new ClerkGroup({assigned:this.fetchChunkBatch,initialMemberCount:3,instantiate:params=>new Clerk(params),job:async item=>{await this._paceMaker.paced;const chunk=await this.env.$$getReplicator().fetchRemoteChunks(item,!1);if(chunk){chunk.forEach((e3=>this.hashCaches.set(e3._id,e3.data)));await this.localDatabase.bulkDocs(chunk,{new_edits:!1});chunk.forEach((e3=>globalSlipBoard2.submit("retrieve-chunk",e3._id,e3)))}else item.forEach((id=>globalSlipBoard2.submit("retrieve-chunk",id,{_id:id,error:"SERVER_OFFLINE"})))}});this._db=db}get localDatabase(){return this._db.localDatabase}get hashCaches(){return this._db.hashCaches}get settings(){return this._db.settings}get env(){return this._db.env}retrieveChunk(id,timeout){const cached=this.hashCaches.get(id);return"string"==typeof cached?Promise.resolve({_id:id,data:cached,type:"leaf"}):globalSlipBoard2.awaitNext("retrieve-chunk",`${id}`,{timeout,onNotAwaited:()=>{this.requestChunkInbox.post(id)}}).then((e3=>e3===TIMED_OUT_SIGNAL?{_id:id,error:"TIMED_OUT"}:e3))}async collectChunks(ids,showResult=!1,_waitForReady){this._paceMaker._interval!==this.settings.minimumIntervalOfReadChunksOnline&&this._paceMaker.changeInterval(this.settings.minimumIntervalOfReadChunksOnline);await this._porterFetch.changeParams({maxSize:this.settings.concurrencyOfReadChunksOnline});const result=await Promise.all(ids.map((e3=>this.retrieveChunk(e3))));result.filter((e3=>"error"in e3)).length>0&&Logger("Could not fetch chunks from the server. ",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_VERBOSE,"fetch");return result}};import_diff_match_patch2=__toESM(require_diff_match_patch(),1);chunkSplittersMainThread={[ChunkAlgorithms_V1]:splitPieces2,[ChunkAlgorithms_V2]:splitPieces2V2,[ChunkAlgorithms_V2Segmenter]:splitPieces2V2,[ChunkAlgorithms_RabinKarp]:async function splitPiecesRabinKarp(dataSrc,absoluteMaxPieceSize,doPlainSplit,minimumChunkSize,_filename,_useSegmenter){const plainSplit=doPlainSplit||isTextBlob2(dataSrc),minPieceSize=plainSplit?128:4096,splitPieceCount=plainSplit?20:12,avgChunkSize=Math.max(minPieceSize,Math.floor(dataSrc.size/splitPieceCount)),maxChunkSize=Math.min(absoluteMaxPieceSize,5*avgChunkSize),minChunkSize=Math.min(Math.max(Math.floor(avgChunkSize/4),minimumChunkSize),maxChunkSize),hashModulus=avgChunkSize;let P_pow_w=1;for(let i2=0;i2<47;i2++)P_pow_w=Math.imul(P_pow_w,31);const buffer=new Uint8Array(await dataSrc.arrayBuffer());let pos=0,hash2=0,start=0;const isText=isTextBlob2(dataSrc),length=buffer.length;return async function*piecesBlob(){for(;pos=start+48){const oldByte=buffer[pos-48],oldByteTerm=Math.imul(oldByte,P_pow_w);hash2=hash2-oldByteTerm|0;hash2=Math.imul(hash2,31);hash2=hash2+byte|0}else{hash2=Math.imul(hash2,31);hash2=hash2+byte|0}const currentChunkSize=pos-start+1;let isBoundaryCandidate=!1;currentChunkSize>=minChunkSize&&(hash2>>>0)%hashModulus==1&&(isBoundaryCandidate=!0);currentChunkSize>=maxChunkSize&&(isBoundaryCandidate=!0);if(isBoundaryCandidate){let isSafeBoundary=!0;isText&&pos+1{var _a9;Logger("Database closed.");this.isReady=!1;this.localDatabase.removeAllListeners();null==(_a9=this.env.$$getReplicator())||_a9.closeReplication()}));const changes3=this.localDatabase.changes({since:"now",live:!0,include_docs:!0,filter:doc=>"leaf"==doc.type}).on("change",(e3=>{e3.deleted||globalSlipBoard2.submit("read-chunk",e3.id,e3.doc)})),closeChanges=reason=>{if(reason)if(reason instanceof Error){Logger("Error while tracking changes",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}else{Logger("Tracking changes has been finished",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}changes3.cancel();changes3.removeAllListeners();this.changeHandler=null};changes3.on("error",closeChanges);changes3.on("complete",closeChanges);this.changeHandler=changes3;this.isReady=!0;Logger("Database is now ready.");return!0}async readChunk(id,timeout){const ret=await this.batchReader.readChunk(id,timeout);if("error"in ret)throw new Error(`Could not read chunk ${id}: (${ret.error})`);return ret.data}async getChunk(piece,doc){const cachedChunkId=this.hashCaches.revGet(piece);if(void 0!==cachedChunkId)return{isNew:!1,id:cachedChunkId,piece};const chunkId="h:"+await this.generateHashedChunk(piece);if(chunkId in doc.eden)return{isNew:!1,id:chunkId,piece};const cachedPiece=this.hashCaches.get(chunkId);if(cachedPiece&&cachedPiece!=piece){Logger(`Hash collided! If possible, please report the following string:${chunkId}=>\nA:--${cachedPiece}--\nB:--${piece}--`,LOG_LEVEL_NOTICE);return!1}this.hashCaches.set(chunkId,piece);return{isNew:!0,id:chunkId,piece}}async generateHashedChunk(piece){const hashedUserPassphrase=this.hashedPassphrase;if("sha1"==this.settings.hashAlg)return this.settings.encrypt?"+"+await sha1(`${piece}-${hashedUserPassphrase}-${piece.length}`):await sha1(`${piece}-${piece.length}`);if("mixed-purejs"==this.settings.hashAlg)return this.settings.encrypt?"+"+fallbackMixedHashEach(`${piece}${hashedUserPassphrase}${piece.length}`):fallbackMixedHashEach(`${piece}-${piece.length}`);if(""===this.settings.hashAlg){if(this.settings.encrypt){const userPasswordHash=this.hashedPassphrase32;return"+"+(this.h32Raw((new TextEncoder).encode(piece))^userPasswordHash^piece.length).toString(36)}return(this.h32Raw((new TextEncoder).encode(piece))^piece.length).toString(36)}return"xxhash64"==this.settings.hashAlg&&this.xxhash64?this.settings.encrypt?"+"+this.xxhash64(`${piece}-${hashedUserPassphrase}-${piece.length}`).toString(36):this.xxhash64(`${piece}-${piece.length}`).toString(36):this.settings.encrypt?"+"+this.xxhash32(`${piece}-${hashedUserPassphrase}-${piece.length}`).toString(36):this.xxhash32(`${piece}-${piece.length}`).toString(36)}async getDBLeafWithTimeout(id,timeout){try{return await this.readChunk(id,timeout)}catch(ex){Logger("Something went wrong while retrieving chunks");Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}getDBLeaf(id,waitForReady){return this.getDBLeafWithTimeout(id,waitForReady?9e4:0)}async getDBEntryMeta(path2,opt,includeDeleted=!1){var _a8,_b4;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!=(_b4=null!=(_a8=null==obj?void 0:obj.deleted)?_a8:obj._deleted)?_b4: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 allChunks(includeDeleted=!1){const used=new Set,existing=new Map;let since=0;for(;;){const changes3=await this.localDatabase.changes({since,limit:100,include_docs:!0,conflicts:!0,style:includeDeleted?"all_docs":"main_only"});if(0==changes3.results.length)break;for(const change of changes3.results){const doc=change.doc;if("leaf"==doc.type){if(doc._deleted&&!includeDeleted)continue;existing.set(doc._id,doc)}if("children"in doc){if(change.deleted&&(!doc._conflicts||0==doc._conflicts.length))continue;doc.children.forEach((e3=>used.add(e3)));if(doc._conflicts){const mineRevInfo=(await this.localDatabase.get(doc._id,{revs:!0,revs_info:!0}))._revs_info||[],keepRevs=new Set;for(const conflict of doc._conflicts){const conflictedRevInfo=(await this.localDatabase.get(doc._id,{rev:conflict,revs:!0,revs_info:!0}))._revs_info||[],diffRevs=mineRevInfo.filter((e3=>!conflictedRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))),diffRevs2=conflictedRevInfo.filter((e3=>!mineRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))),diffRevs3=diffRevs.concat(diffRevs2),sameRevs=mineRevInfo.filter((e3=>conflictedRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))).filter((e3=>"available"==e3.status)).sort(((a2,b3)=>getNoFromRev(b3.rev)-getNoFromRev(a2.rev))),sameRevsTop=sameRevs.length>0?[sameRevs[0].rev]:[];[...diffRevs3.filter((e3=>"available"==e3.status)).map((e3=>e3.rev)),...sameRevsTop].forEach((e3=>keepRevs.add(e3)))}const detail=await this.localDatabase.bulkGet({docs:[...keepRevs.values()].map((e3=>({id:doc._id,rev:e3})))});for(const e3 of detail.results)if("docs"in e3){const docs=e3.docs;for(const doc2 of docs)"ok"in doc2&&"children"in doc2.ok&&doc2.ok.children.forEach((e4=>used.add(e4)))}}}}since=changes3.results[changes3.results.length-1].seq}return{used,existing}}async getDBEntry(path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){const meta=await this.getDBEntryMeta(path2,opt,includeDeleted);return!!meta&&await this.getDBEntryFromMeta(meta,dump,waitForReady)}async getDBEntryFromMeta(meta,dump=!1,waitForReady=!0){var _a8,_b4,_c3;const filename=this.id2path(meta._id,meta);if(!this.isTargetFile(filename))return!1;const dispFilename=stripAllPrefixes(filename),deleted=null!=(_b4=null!=(_a8=meta.deleted)?_a8:meta._deleted)?_b4: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)}const childrenKeys=[...meta.children],loadedChildrenMap=new Map;meta.eden&&Object.entries(meta.eden).forEach((([key2,chunk])=>loadedChildrenMap.set(key2,chunk.data)));const missingChunks=unique(childrenKeys).filter((e3=>!loadedChildrenMap.has(e3)));if(0!=missingChunks.length)if(this.isOnDemandChunkEnabled){const items=await this.collectChunks(missingChunks,!1,waitForReady);if(!items||items.some((leaf=>"error"in leaf||"leaf"!=leaf.type))){Logger(`Chunks of ${dispFilename} (${meta._id.substring(0,8)}) are not valid. (p1)`,LOG_LEVEL_NOTICE);items&&Logger(`Missing chunks: ${items.map((e3=>e3._id)).join(",")}`,LOG_LEVEL_VERBOSE);return!1}items.filter((e3=>"data"in e3)).forEach((chunk=>loadedChildrenMap.set(chunk._id,chunk.data)))}else try{if(waitForReady)(await Promise.all(missingChunks.map((e3=>this.getDBLeaf(e3,waitForReady))))).forEach(((value,idx2)=>loadedChildrenMap.set(missingChunks[idx2],value)));else{const chunkDocs=await this.localDatabase.allDocs({keys:missingChunks,include_docs:!0});if(chunkDocs.rows.some((e3=>"error"in e3))){const missingChunks2=chunkDocs.rows.filter((e3=>"error"in e3)).map((e3=>e3.key)).join(", ");Logger(`Chunks of ${dispFilename} (${meta._id.substring(0,8)}) are not valid. (p2)`,LOG_LEVEL_NOTICE);Logger(`Missing chunks: ${missingChunks2}`,LOG_LEVEL_VERBOSE);return!1}if(chunkDocs.rows.some((e3=>"value"in e3&&e3.value.deleted))){const missingChunks2=chunkDocs.rows.filter((e3=>"value"in e3&&e3.value.deleted)).map((e3=>e3.key)).join(", ");Logger(`Chunks of ${dispFilename} (${meta._id.substring(0,8)}) are deleted. Please try "Resurrect deleted chunks" once.`,LOG_LEVEL_NOTICE);Logger(`Corrupted chunks: ${missingChunks2}`,LOG_LEVEL_VERBOSE);return!1}if(chunkDocs.rows.some((e3=>e3.doc&&"leaf"!=e3.doc.type))){const missingChunks2=chunkDocs.rows.filter((e3=>e3.doc&&"leaf"!=e3.doc.type)).map((e3=>e3.id)).join(", ");Logger(`Chunks of ${dispFilename} (${meta._id.substring(0,8)}) are not valid. (p3)`,LOG_LEVEL_NOTICE);Logger(`Corrupted chunks: ${missingChunks2}`,LOG_LEVEL_VERBOSE);return!1}chunkDocs.rows.forEach(((value,_idx)=>"doc"in value&&loadedChildrenMap.set(value.doc._id,value.doc.data)))}}catch(ex){Logger(`Something went wrong on reading chunks of ${dispFilename}(${meta._id.substring(0,8)}) from database, see verbose info for detail.`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}const l2=childrenKeys.map((e3=>loadedChildrenMap.get(e3)));if(l2.some((e3=>void 0===e3)))throw new Error("Load failed");const doc={data:l2,path:meta.path,_id:meta._id,ctime:meta.ctime,mtime:meta.mtime,size:meta.size,_rev:meta._rev,children:meta.children,datatype:meta.type,_conflicts:meta._conflicts,eden:meta.eden,deleted,type:meta.type};if(dump){Logger("--Loaded Document--");Logger(doc)}return doc}catch(ex){if(isErrorOfMissingDoc(ex)){Logger(`Missing document content!, could not read ${dispFilename}(${meta._id.substring(0,8)}) from database.`,LOG_LEVEL_NOTICE);return!1}Logger(`Something went wrong on reading ${dispFilename}(${meta._id.substring(0,8)}) from database:`,LOG_LEVEL_NOTICE);Logger(ex)}}return!1}async deleteDBEntry(path2,opt){var _a8;if(!this.isTargetFile(path2))return!1;const id=await this.path2id(path2);try{return null!=(_a8=await serialized("file:"+path2,(async()=>{let obj=null;obj=opt?await this.localDatabase.get(id,opt):await this.localDatabase.get(id);const revDeletion=opt&&""!=("rev"in opt?opt.rev:"");if(obj.type&&"leaf"==obj.type)return!1;if(!obj.type||obj.type&&"notes"==obj.type){obj._deleted=!0;const r4=await this.localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed:${path2} (${obj._id.substring(0,8)}-${r4.rev})`);return!0}if("newnote"==obj.type||"plain"==obj.type){if(revDeletion)obj._deleted=!0;else{obj.deleted=!0;obj.mtime=Date.now();this.settings.deleteMetadataOfDeletedFiles&&(obj._deleted=!0)}const r4=await this.localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed:${path2} (${obj._id.substring(0,8)}-${r4.rev})`);return!0}return!1})))&&_a8}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}}async deleteDBEntryPrefix(prefix){let c3=0,readCount=0;const delDocs=[];do{const result=await this.localDatabase.allDocs({include_docs:!1,skip:c3,limit:100,conflicts:!0});readCount=result.rows.length;if(readCount>0)for(const v2 of result.rows){const decodedPath=this.id2path(v2.id,v2.doc);decodedPath.startsWith(prefix)?this.isTargetFile(decodedPath)&&delDocs.push(v2.id):v2.id.startsWith("h:")}c3+=readCount}while(0!=readCount);let deleteCount=0,notfound=0;for(const v2 of delDocs)try{await serialized("file:"+v2,(async()=>{const item=await this.localDatabase.get(v2);if("newnote"==item.type||"plain"==item.type){item.deleted=!0;this.settings.deleteMetadataOfDeletedFiles&&(item._deleted=!0);item.mtime=Date.now()}else item._deleted=!0;await this.localDatabase.put(item,{force:!0})}));deleteCount++}catch(ex){if(!isErrorOfMissingDoc(ex))throw ex;notfound++}Logger(`deleteDBEntryPrefix:deleted ${deleteCount} items, skipped ${notfound}`);return!0}async putDBEntry(note,onlyChunks){var _a8,_b4,_c3;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}let processed=0;const pieceSize=Math.floor(102400*(1*(this.settings.customChunkSize||0)+1));let plainSplit=!1;const minimumChunkSize=this.settings.minimumChunkSize;(function shouldSplitAsPlainText(filename){return!!filename.endsWith(".md")||!!filename.endsWith(".txt")||!!filename.endsWith(".canvas")})(filename)&&(plainSplit=!0);const data=note.data instanceof Blob?note.data:createTextBlob(note.data);note.type=isTextBlob(data)?"plain":"newnote";note.datatype=note.type;const splitFuncInMainThread=null!=(_a8=null==chunkSplittersMainThread?void 0:chunkSplittersMainThread[this.settings.chunkSplitterVersion])?_a8:chunkSplittersMainThread.v1,splitFuncInWorker=null!=(_b4=null==chunkSplittersWorker?void 0:chunkSplittersWorker[this.settings.chunkSplitterVersion])?_b4:chunkSplittersWorker.v1,useSegmenter="v2-segmenter"===this.settings.chunkSplitterVersion,splitFunc=this.settings.disableWorkerForGeneratingChunks||this.settings.processSmallFilesInUIThread&¬e.data.size<1024?splitFuncInMainThread:splitFuncInWorker,pieces=await splitFunc(data,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter),chunkTasks=[];for await(const piece of pieces())if(0!==piece.length){processed++;chunkTasks.push(this.getChunk(piece,note))}data.size>0&&0===processed&&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);const chunks=await Promise.all(chunkTasks);if(chunks.some((e3=>!1===e3))){Logger(`This document could not be saved:${dispFilename}`,LOG_LEVEL_NOTICE);return!1}let eden={},currentRevAsNo=0;"eden"in note&&(eden=note.eden);let newChunks=[];if(this.settings.useEden&&!onlyChunks){try{const old=await this.localDatabase.get(note._id);currentRevAsNo=getNoFromRev(old._rev);eden={..."eden"in old?old.eden:{},...eden}}catch(ex){if(!isErrorOfMissingDoc(ex))throw ex}const chunkOnEdenInitial=Object.keys(eden).length;let removedChunkOnEden=0;const removeEdenChunks=Object.keys(eden).filter((e3=>chunks.every((c3=>c3.id!==e3))));for(const removeId of removeEdenChunks){removedChunkOnEden++;delete eden[removeId]}let newChunkOnEden=0,existChunkOnEden=0;for(const chunk of chunks)if(chunk.id in eden)existChunkOnEden++;else{newChunkOnEden++;eden[chunk.id]={epoch:currentRevAsNo+1,data:chunk.piece}}const allEdenChunks=Object.entries(eden).sort(((a2,b3)=>b3[1].epoch-a2[1].epoch));let totalLength=0,count=0;const allEdenChunksKey=Object.keys(eden);let alreadyIndependent=0,independent=0;const edenChunkOnDB=(await this.localDatabase.allDocs({keys:allEdenChunksKey})).rows.reduce(((p4,c3)=>({...p4,[c3.key]:c3})),{});for(const[key2,chunk]of allEdenChunks){count++;let makeChunkIndependent=!1;if(!(key2 in edenChunkOnDB)||edenChunkOnDB[key2].error){(chunk.data.length>1024||chunk.epoch+this.settings.maxAgeInEdenthis.settings.maxTotalLengthInEden&&(makeChunkIndependent=!0);count>this.settings.maxChunksInEden&&(makeChunkIndependent=!0);if(makeChunkIndependent){count--;independent++;newChunks.push({_id:key2,data:chunk.data,type:"leaf"});delete eden[key2]}else totalLength+=chunk.data.length}else{count--;delete eden[key2];alreadyIndependent++}}Logger(`Progress on Eden: doc: ${dispFilename} : ${chunkOnEdenInitial}->${Object.keys(eden).length} (removed: ${removedChunkOnEden}, new: ${newChunkOnEden}, exist: ${existChunkOnEden}, alreadyIndependent:${alreadyIndependent}, independent:${independent})`,LOG_LEVEL_VERBOSE)}else newChunks=chunks.filter((e3=>e3.isNew)).map((e3=>({_id:e3.id,data:e3.piece,type:"leaf"})));const cached=processed-newChunks.length;if(newChunks.length)if(this.settings.doNotUseFixedRevisionForChunks){const previousChunks=await this.localDatabase.allDocs({keys:newChunks.map((e3=>e3._id))}),missingChunks=previousChunks.rows.filter((e3=>"error"in e3||e3.value.deleted)).map((e3=>e3.key)),newChunksFiltered=newChunks.filter((e3=>missingChunks.includes(e3._id))),result=await this.localDatabase.bulkDocs(newChunksFiltered,{});if(result.some((e3=>"error"in e3))){Logger(`Save failed.: ${dispFilename} :${result.map((e3=>{var _a9;return null!=(_a9=null==e3?void 0:e3.id)?_a9:e3.toString()})).join(",")}`,LOG_LEVEL_VERBOSE);Logger(`This document could not be saved:${dispFilename}`,LOG_LEVEL_NOTICE);return!1}Logger(`Chunks saved: doc: ${dispFilename} ,chunks: ${processed} (new:${newChunksFiltered.length}, recycled:${previousChunks.rows.length-newChunksFiltered.length}, cached:${cached})`)}else{newChunks=newChunks.map((e3=>{return{...e3,_rev:(chunk=e3,`1-${(Math.imul(chunk.data.length,21+chunk._id.charCodeAt(5)).toString(16)+"0".repeat(32)).slice(0,32)}`)};var chunk}));const existDocMap=(await this.localDatabase.allDocs({keys:newChunks.map((e3=>e3._id)),include_docs:!0})).rows.map((e3=>"doc"in e3?e3.doc:void 0)).filter((e3=>null!=e3)).reduce(((p4,c3)=>({...p4,[c3._id]:c3})),{}),suspiciousChunks=newChunks.filter((e3=>{var _a9;return e3._id in existDocMap&&(null==(_a9=existDocMap[e3._id])?void 0:_a9._rev)!=e3._rev})),erroredChunks=suspiciousChunks.filter((e3=>{var _a9;return e3.data!=(null==(_a9=existDocMap[e3._id])?void 0:_a9.data)}));if(erroredChunks.length){Logger(`Save failed.: ${dispFilename} :${erroredChunks.length} items mismatched`,LOG_LEVEL_VERBOSE);Logger(`This document could not be saved:${dispFilename}`,LOG_LEVEL_NOTICE);Logger(`Mismatched items: ${erroredChunks.map((e3=>e3._id)).join(",")}`,LOG_LEVEL_VERBOSE);Logger(`Revision and content mismatch: ${erroredChunks.map((e3=>{var _a9;return`${e3._rev}, ${null==(_a9=null==existDocMap?void 0:existDocMap[e3._id])?void 0:_a9._rev}`})).join(",")}`,LOG_LEVEL_VERBOSE);return!1}const saveChunks=newChunks.filter((e3=>!(e3._id in existDocMap)));await this.localDatabase.bulkDocs(saveChunks,{new_edits:!1});Logger(`Chunks saved (with fixed): doc: ${dispFilename} ,chunks: ${processed} (new:${saveChunks.length}, recycled:${newChunks.length-saveChunks.length}, cached:${cached}, revision unmatched:${suspiciousChunks.length})`)}if(onlyChunks)return{id:note._id,ok:!0,rev:"dummy"};const newDoc={children:chunks.map((e3=>e3.id)),_id:note._id,path:note.path,ctime:note.ctime,mtime:note.mtime,size:note.size,type:note.datatype,eden};return null!=(_c3=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})))&&_c3}async resetDatabase(){var _a8,_b4;null==(_a8=this.changeHandler)||_a8.cancel();await(null==(_b4=this.changeHandler)?void 0:_b4.removeAllListeners());this.env.$$getReplicator().closeReplication();if(!await this.env.$everyOnResetDatabase(this)){Logger("Database reset has been prevented or failed on some modules.",LOG_LEVEL_NOTICE);return!1}Logger("Database closed for reset Database.");this.isReady=!1;await this.localDatabase.destroy();this.localDatabase=null;await this.initializeDatabase();Logger("Local Database Reset",LOG_LEVEL_NOTICE)}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)))}collectChunks(ids,showResult=!1,waitForReady){return this.chunkCollector.collectChunks(ids,showResult,waitForReady)}async*findAllChunks(opt){const targets=[()=>this.findEntries("h:","h:􏿿",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();yield*target}}async*findEntries(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});do{const docs=await req;if(0===docs.rows.length)break;nextKey=`${docs.rows[docs.rows.length-1].id}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});for(const row of docs.rows){const doc=row.doc;"type"in doc&&("newnote"!=doc.type&&"plain"!=doc.type||(yield doc))}}while(""!=nextKey)}async*findAllDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","",null!=opt?opt:{})];for(const targetFun of targets)yield*targetFun()}async*findEntryNames(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,...opt});do{const docs=await req;if(0==docs.rows.length){nextKey="";break}nextKey=`${docs.rows[docs.rows.length-1].key}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,...opt});for(const row of docs.rows)yield row.id}while(""!=nextKey)}async*findAllDocNames(opt){const targets=[()=>this.findEntryNames("","_",null!=opt?opt:{}),()=>this.findEntryNames("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntryNames("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntryNames("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntryNames("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntryNames("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4.startsWith("_")||"obsydian_livesync_version"!=f4&&(yield f4)}}async*findAllNormalDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntries("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntries("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntries("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4._id.startsWith("_")||"newnote"!=f4.type&&"plain"!=f4.type||(yield f4)}}async removeRevision(docId,revision){try{const doc=await this.localDatabase.get(docId,{rev:revision});doc._deleted=!0;await this.localDatabase.put(doc);return!0}catch(ex){isErrorOfMissingDoc(ex)&&Logger(`Remove revision: Missing target revision, ${docId}-${revision}`,LOG_LEVEL_VERBOSE)}return!1}getRaw(docId,options){return this.localDatabase.get(docId,options||{})}removeRaw(docId,revision,options){return this.localDatabase.remove(docId,revision,options||{})}putRaw(doc,options){return this.localDatabase.put(doc,options||{})}allDocsRaw(options){return this.localDatabase.allDocs(options)}bulkDocsRaw(docs,options){return this.localDatabase.bulkDocs(docs,options||{})}async UXFileInfoToSavingEntry(file){const datatype=determineTypeFromBlob(file.body),fullPath=file.path;return{_id:await this.path2id(fullPath),path:fullPath,data:file.body,mtime:file.stat.mtime,ctime:file.stat.ctime,size:file.stat.size,children:[],datatype,type:datatype,eden:{}}}async getConflictedDoc(path2,rev3){try{const doc=await this.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_patch2.DIFF_DELETE&&ret.push(...pieces.map((e3=>[d4[0],e3])));if(d4[0]==import_diff_match_patch2.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_patch2.DIFF_INSERT){for(const pt of pieces){ret.push([d4[0],pt]);const pairP=piecesPair.shift();void 0!==pairP&&ret.push([import_diff_match_patch2.DIFF_INSERT,pairP])}ret.push(...piecesPair.map((e3=>[nd[0],e3])))}else{ret.push(...pieces.map((e3=>[d4[0],e3])));ret.push(...piecesPair.map((e3=>[nd[0],e3])))}}else ret.push(...pieces.map((e3=>[0,e3])))}}while(src.length>0);return ret}var _a8,_b4,_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_patch2.diff_match_patch,mapLeft=dmp.diff_linesToChars_(baseLeaf.data,leftLeaf.data),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);const mapRight=dmp.diff_linesToChars_(baseLeaf.data,rightLeaf.data),diffRightSrc=dmp.diff_main(mapRight.chars1,mapRight.chars2,!1);dmp.diff_charsToLines_(diffRightSrc,mapRight.lineArray);const diffLeft=splitDiffPiece(diffLeftSrc),diffRight=splitDiffPiece(diffRightSrc);let rightIdx=0,leftIdx=0;const merged=[];autoMerge=!0;LOOP_MERGE:do{if(leftIdx>=diffLeft.length&&rightIdx>=diffRight.length)break LOOP_MERGE;const leftItem=null!=(_a8=diffLeft[leftIdx])?_a8:[0,""],rightItem=null!=(_b4=diffRight[rightIdx])?_b4:[0,""];leftIdx++;rightIdx++;if(leftItem[0]!=import_diff_match_patch2.DIFF_EQUAL||rightItem[0]!=import_diff_match_patch2.DIFF_EQUAL||leftItem[1]!=rightItem[1])if(leftItem[0]!=import_diff_match_patch2.DIFF_DELETE||rightItem[0]!=import_diff_match_patch2.DIFF_DELETE||leftItem[1]!=rightItem[1])if(leftItem[0]!=import_diff_match_patch2.DIFF_INSERT||rightItem[0]!=import_diff_match_patch2.DIFF_INSERT)if(leftItem[0]!=import_diff_match_patch2.DIFF_INSERT){if(rightItem[0]!=import_diff_match_patch2.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_patch2.DIFF_DELETE){if(rightItem[0]==import_diff_match_patch2.DIFF_EQUAL){merged.push(leftItem);continue}autoMerge=!1;break LOOP_MERGE}if(rightItem[0]==import_diff_match_patch2.DIFF_DELETE){if(leftItem[0]==import_diff_match_patch2.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_patch2.DIFF_INSERT&&nextRightItem[0]==import_diff_match_patch2.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 _a8,_b4,_c3;const conflictedRev=conflicts[0],conflictedRevNo=Number(conflictedRev.split("-")[0]),commonBase=null!=(_c3=null==(_b4=null==(_a8=((await this.getRaw(await this.path2id(path2),{revs_info:!0}))._revs_info||[]).filter((e3=>"available"==e3.status&&Number(e3.rev.split("-")[0])e3[0]!=import_diff_match_patch2.DIFF_DELETE)).map((e3=>e3[1])).join("");Logger(`Sensible merge:${path2}`,LOG_LEVEL_INFO)}else Logger("Sensible merge is not applicable.",LOG_LEVEL_VERBOSE)}else if(isObjectMargeApplicable(path2)){const result=await this.mergeObject(path2,commonBase,test._rev,conflictedRev);if(result){Logger(`Object merge:${path2}`,LOG_LEVEL_INFO);p4=result}else Logger("Object merge is not applicable..",LOG_LEVEL_VERBOSE)}if(void 0!==p4)return{result:p4,conflictedRev}}return!1}async tryAutoMerge(path2,enableMarkdownAutoMerge){const test=await this.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}}};LiveSyncAbstractReplicator=class{constructor(env){this.syncStatus="NOT_CONNECTED";this.docArrived=0;this.docSent=0;this.lastSyncPullSeq=0;this.maxPullSeq=0;this.lastSyncPushSeq=0;this.maxPushSeq=0;this.nodeid="";this.remoteLocked=!1;this.remoteCleaned=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;this.updateInfo=()=>{this.env.replicationStat.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}};this.env=env}async initializeDatabaseForReplication(){const db=this.env.getDatabase();try{const nodeinfo=await resolveWithIgnoreKnownError(db.get("_local/obsydian_livesync_nodeinfo"),{_id:"_local/obsydian_livesync_nodeinfo",type:"nodeinfo",nodeid:"",v20220607:!0});if(""==nodeinfo.nodeid){nodeinfo.nodeid=Math.random().toString(36).slice(-10);await db.put(nodeinfo)}this.nodeid=nodeinfo.nodeid;return!0}catch(ex){Logger(ex)}return!1}};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={};OpenKeyValueDatabase=async dbKey=>{if(dbKey in databaseCache){databaseCache[dbKey].close();delete databaseCache[dbKey]}const storeKey=dbKey,dbPromise=function openDB(name,version2,{blocked,upgrade,blocking,terminated}={}){const request2=indexedDB.open(name,version2),openPromise=wrap(request2);upgrade&&request2.addEventListener("upgradeneeded",(event2=>{upgrade(wrap(request2.result),event2.oldVersion,event2.newVersion,wrap(request2.transaction),event2)}));blocked&&request2.addEventListener("blocked",(event2=>blocked(event2.oldVersion,event2.newVersion,event2)));openPromise.then((db=>{terminated&&db.addEventListener("close",(()=>terminated()));blocking&&db.addEventListener("versionchange",(event2=>blocking(event2.oldVersion,event2.newVersion,event2)))})).catch((()=>{}));return openPromise}(dbKey,1,{upgrade(db2){db2.createObjectStore(storeKey)}}),db=await dbPromise;databaseCache[dbKey]=db;return{get:async key2=>await db.get(storeKey,key2),set:async(key2,value)=>await db.put(storeKey,value,key2),del:async key2=>await db.delete(storeKey,key2),clear:async()=>await db.clear(storeKey),keys:async(query3,count)=>await db.getAllKeys(storeKey,query3,count),close(){delete databaseCache[dbKey];return db.close()},async destroy(){delete databaseCache[dbKey];db.close();await function deleteDB(name,{blocked}={}){const request2=indexedDB.deleteDatabase(name);blocked&&request2.addEventListener("blocked",(event2=>blocked(event2.oldVersion,event2)));return wrap(request2).then((()=>{}))}(dbKey)}}};tasks2=new Map;intervals={};waitingItems=new Set;PersistentMap=class{flush(){this._save()}_save(){localStorage.setItem(this._key,JSON.stringify([...this._map.entries()]))}_load(suppliedEntries=[]){var _a8;try{const savedSource=null!=(_a8=localStorage.getItem(this._key))?_a8:"",sourceToParse=""===savedSource?"[]":savedSource,obj=JSON.parse(sourceToParse);this._map=new Map([...obj,...suppliedEntries])}catch(ex){console.log(`Map read error : ${this._key}`);console.dir(ex);this._map=new Map([...suppliedEntries])}return Promise.resolve()}_queueSave(){this._setCount--;if(this._setCount<0){this._setCount=100;scheduleTask(`save-map-${this._key}`,0,(()=>this._save()))}scheduleTask(`save-map-${this._key}`,150,(()=>this._save()))}delete(key2){const ret=this._map.delete(key2);this._queueSave();return ret}has(key2){return this._map.has(key2)}set(key2,value){this._map.set(key2,value);this._queueSave();return this}clear(){this._map=new Map;this._save()}get(key2,defValue){const v2=this._map.get(key2);return void 0===v2?defValue:v2}constructor(key2,entries2){Object.defineProperty(this,"_setCount",{enumerable:!0,configurable:!0,writable:!0,value:100});Object.defineProperty(this,"_map",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._key=key2;this._map=new Map(null!=entries2?entries2:[]);this._load(entries2)}};EVENT_LAYOUT_READY="layout-ready";EVENT_REQUEST_OPEN_SETUP_URI2="request-open-setup-uri";EVENT_REQUEST_COPY_SETUP_URI2="request-copy-setup-uri";EVENT_REQUEST_SHOW_SETUP_QR="request-show-setup-qr";EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2="request-open-plugin-sync-dialog";EVENT_REQUEST_RUN_DOCTOR="request-run-doctor";SHOULD_READ_NEW=Symbol("SHOULD_READ_NEW");NOT_USED=Symbol("NOT_USED");Refiner=class{_refinePromise(){const previous=this._evaluationPromise,newPromise=promiseWithResolver();this._evaluationPromise=newPromise;fireAndForget((async()=>{await Promise.race([previous.promise,Promise.resolve(NOT_USED)]).then((r4=>{r4!==NOT_USED||previous.reject(SHOULD_READ_NEW)}))}));return newPromise}constructor({initialSource:source2,evaluation,shouldUpdate,isDifferent}){Object.defineProperty(this,"_cachedBy",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_cachedResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_evaluationPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"__evaluation",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"__shouldUpdate",{enumerable:!0,configurable:!0,writable:!0,value:isDifferent2=>isDifferent2});Object.defineProperty(this,"__isDifferent",{enumerable:!0,configurable:!0,writable:!0,value:(a2,b3)=>isObjectDifferent(a2,b3)});Object.defineProperty(this,"_evaluations",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()});Object.defineProperty(this,"_latest",{enumerable:!0,configurable:!0,writable:!0,value:0});this.__evaluation=evaluation;this.__shouldUpdate=shouldUpdate||this.__shouldUpdate;this.__isDifferent=isDifferent||this.__isDifferent;this._refinePromise();void 0!==source2&&this._startEvaluation(source2)}_startEvaluation(source2){const _buff=this._cachedResult,_source=source2,index6=++this._latest,evaluationPromise=this._refinePromise(),proc=async()=>{if(!(this._latest>index6))try{const r4=await this.__evaluation(_source,_buff);if(this._latest<=index6){this._cachedBy=_source;this._cachedResult=r4}evaluationPromise.resolve(r4)}catch(error){evaluationPromise.reject(error)}};this._evaluations=this._evaluations.then((async()=>{await proc()}))}update(source2){const isDifferent=void 0===this._cachedBy||this.__isDifferent(this._cachedBy,source2);if(!this.__shouldUpdate(isDifferent,source2,this._cachedResult))return this;this._startEvaluation(source2);return this}async _getValue(){let result;for(;;)try{result=await this._evaluationPromise.promise;return result}catch(error){if(error!==SHOULD_READ_NEW)throw error}}get value(){return this._getValue()}};BasicHeaderGenerator=class{constructor(){this._header=new Refiner({evaluation(source2,previous){if("username"in source2){const userNameAndPassword=source2.username&&source2.password?`${source2.username}:${source2.password}`:"";return`Basic ${btoa(userNameAndPassword)}`}return""}})}async getBasicHeader(auth){return await this._header.update(auth).value}};JWTTokenGenerator=class{constructor(){this._currentCryptoKey=new Refiner({evaluation:async(auth,previous)=>await this._importKey(auth)});this._jwt=new Refiner({evaluation:async(params,previous)=>{const buff=`${btoa(JSON.stringify(params.header))}.${btoa(JSON.stringify(params.payload))}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),key2=await this._currentCryptoKey.update(params.credentials).value;let token="";if("ES256"==params.header.alg||"ES512"==params.header.alg){const jwt=await crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},key2,writeString(buff));token=(await arrayBufferToBase64Single(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}else{if("HS256"!=params.header.alg&&"HS512"!=params.header.alg)throw new Error("JWT algorithm is not supported.");{const jwt=await crypto.subtle.sign({name:"HMAC",hash:{name:params.header.alg}},key2,writeString(buff));token=(await arrayBufferToBase64Single(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}}return{...params,token:`${buff}.${token}`}}});this._jwtParams=new Refiner({evaluation(source2,previous){const kid=source2.jwtKid||void 0;if(""==(source2.jwtSub||"").trim())throw new Error("JWT sub is empty");const algorithm=source2.jwtAlgorithm||"";if(!algorithm)throw new Error("JWT algorithm is not configured.");if("HS256"!=algorithm&&"HS512"!=algorithm&&"ES256"!=algorithm&&"ES512"!=algorithm)throw new Error("JWT algorithm is not supported.");const header={alg:source2.jwtAlgorithm||"HS256",typ:"JWT",kid},iat=~~((new Date).getTime()/1e3);return{header,payload:{exp:iat+60*(source2.jwtExpDuration||5),iat,sub:source2.jwtSub||"","_couchdb.roles":["_admin"]},credentials:source2}},shouldUpdate(isDifferent,source2,previous){if(isDifferent)return!0;if(!previous)return!0;const d4=~~((new Date).getTime()/1e3);return previous.payload.exp{this.disable()}))}async process(){try{await this._process()}catch(ex){Logger(ex)}}enable(interval){this.disable();if(0!=interval){this._timer=window.setInterval((()=>fireAndForget((async()=>{await this.process();this._plugin.$$isUnloaded()&&this.disable()}))),interval);this._plugin.registerInterval(this._timer)}}disable(){if(void 0!==this._timer){window.clearInterval(this._timer);this._timer=void 0}}};_requestToCouchDB=async(baseUri,credentials,origin2,path2,body,method,customHeaders)=>{const authHeaderGen=new AuthorizationHeaderGenerator,requestParam={url:`${baseUri}/${path2}`,method:method||(body?"PUT":"GET"),headers:{authorization:await authHeaderGen.getAuthorizationHeader(credentials),origin:origin2,...customHeaders},contentType:"application/json",body:body?JSON.stringify(body):void 0};return await(0,import_obsidian.requestUrl)(requestParam)};BASE_IS_NEW=Symbol("base");TARGET_IS_NEW=Symbol("target");EVEN=Symbol("even");resolution=2e3;_cached=new Map;waitingTasks={};prefixMapObject={s:{1:"V",2:"W",3:"X",4:"Y",5:"Z"},o:{1:"v",2:"w",3:"x",4:"y",5:"z"}};decodePrefixMapObject=Object.fromEntries(Object.entries(prefixMapObject).flatMap((([prefix,map4])=>Object.entries(map4).map((([len,char])=>[char,{prefix,len:parseInt(len)}])))));prefixMapNumber={n:{1:"a",2:"b",3:"c",4:"d",5:"e"},N:{1:"A",2:"B",3:"C",4:"D",5:"E"}};decodePrefixMapNumber=Object.fromEntries(Object.entries(prefixMapNumber).flatMap((([prefix,map4])=>Object.entries(map4).map((([len,char])=>[char,{prefix,len:parseInt(len)}])))));decodeMapConstant={u:void 0,n:null,f:!1,t:!0};topologicalSortCache=new Map;_reactiveSourceId=0;reactiveSource({pending:[],running:[],count:0});collectingChunks=reactiveSource(0);pluginScanningCount=reactiveSource(0);hiddenFilesProcessingCount=reactiveSource(0);hiddenFilesEventCount=reactiveSource(0);logStore=new QueueProcessor((e3=>e3),{batchSize:1,suspended:!1,keepResultUntilDownstreamConnected:!0});logMessages=reactiveSource([]);AbstractModule=class{constructor(core){this.core=core;this._log=(msg,level=LOG_LEVEL_INFO,key2)=>{"string"==typeof msg&&level!==LOG_LEVEL_NOTICE&&(msg=`[${this.constructor.name}]  ${msg}`);Logger(msg,level,key2)};this.saveSettings=this.core.saveSettings.bind(this.core);Logger(`[${this.constructor.name}] Loaded`,LOG_LEVEL_VERBOSE)}get localDatabase(){return this.core.localDatabase}get settings(){return this.core.settings}set settings(value){this.core.settings=value}addTestResult(key2,value,summary,message){this.core.$$addTestResult(`${this.constructor.name}`,key2,value,summary,message)}testDone(result=!0){return Promise.resolve(result)}testFail(message){this._log(message,LOG_LEVEL_NOTICE);return this.testDone(!1)}async _test(key2,process2){this._log(`Testing ${key2}`,LOG_LEVEL_VERBOSE);try{const ret=await process2();if(!0!==ret){this.addTestResult(key2,!1,ret.toString());return this.testFail(`${key2} failed: ${ret}`)}this.addTestResult(key2,!0,"")}catch(ex){this.addTestResult(key2,!1,"Failed by Exception",ex.toString());return this.testFail(`${key2} failed: ${ex}`)}return this.testDone()}};AbstractObsidianModule=class extends AbstractModule{constructor(plugin3,core){super(core);this.plugin=plugin3;this.core=core;this.addCommand=this.plugin.addCommand.bind(this.plugin);this.registerView=this.plugin.registerView.bind(this.plugin);this.addRibbonIcon=this.plugin.addRibbonIcon.bind(this.plugin);this.registerObsidianProtocolHandler=this.plugin.registerObsidianProtocolHandler.bind(this.plugin);this.saveSettings=this.plugin.saveSettings.bind(this.plugin)}get localDatabase(){return this.plugin.localDatabase}get settings(){return this.plugin.settings}set settings(value){this.plugin.settings=value}get app(){return this.plugin.app}_isMainReady(){return this.core.$$isReady()}_isMainSuspended(){return this.core.$$isSuspended()}_isDatabaseReady(){return this.core.$$isDatabaseReady()}_isThisModuleEnabled(){return!0}};"undefined"!=typeof window&&(null!=(_c=(_b2=null!=(_a4=window.__svelte)?_a4:window.__svelte={}).v)?_c:_b2.v=new Set).add("5");EACH_ITEM_REACTIVE=1;EACH_INDEX_REACTIVE=2;EACH_IS_CONTROLLED=4;EACH_IS_ANIMATED=8;EACH_ITEM_IMMUTABLE=16;PROPS_IS_IMMUTABLE=1;PROPS_IS_RUNES=2;PROPS_IS_UPDATED=4;PROPS_IS_BINDABLE=8;PROPS_IS_LAZY_INITIAL=16;TEMPLATE_FRAGMENT=1;TEMPLATE_USE_IMPORT_NODE=2;HYDRATION_START="[";HYDRATION_START_ELSE="[!";HYDRATION_END="]";HYDRATION_ERROR={};UNINITIALIZED=Symbol();FILENAME=Symbol("filename");Symbol("hmr");NAMESPACE_HTML="http://www.w3.org/1999/xhtml";node_env=null==(_b3=null==(_a5=globalThis.process)?void 0:_a5.env)?void 0:_b3.NODE_ENV;dev_fallback_default=node_env&&!node_env.toLowerCase().startsWith("prod");is_array=Array.isArray;index_of=Array.prototype.indexOf;array_from=Array.from;Object.keys;define_property=Object.defineProperty;get_descriptor=Object.getOwnPropertyDescriptor;get_descriptors=Object.getOwnPropertyDescriptors;object_prototype=Object.prototype;array_prototype=Array.prototype;get_prototype_of=Object.getPrototypeOf;is_extensible=Object.isExtensible;noop2=()=>{};DERIVED=2;EFFECT=4;RENDER_EFFECT=8;BLOCK_EFFECT=16;BRANCH_EFFECT=32;ROOT_EFFECT=64;BOUNDARY_EFFECT=128;UNOWNED=256;DISCONNECTED=512;CLEAN=1024;DIRTY=2048;MAYBE_DIRTY=4096;INERT=8192;DESTROYED=16384;EFFECT_RAN=32768;EFFECT_TRANSPARENT=65536;LEGACY_DERIVED_PROP=1<<17;INSPECT_EFFECT=1<<18;HEAD_EFFECT=1<<19;EFFECT_HAS_DERIVED=1<<20;EFFECT_IS_UPDATING=1<<21;STATE_SYMBOL=Symbol("$state");LEGACY_PROPS=Symbol("legacy props");LOADING_ATTR_SYMBOL=Symbol("");bold="font-weight: bold";normal="font-weight: normal";hydrating=!1;tracing_expressions=null;legacy_mode_flag=!1;tracing_mode_flag=!1;stack=[];request_idle_callback="undefined"==typeof requestIdleCallback?cb2=>setTimeout(cb2,1):requestIdleCallback;micro_tasks=[];idle_tasks=[];handled_errors=new WeakSet;is_throwing_error=!1;is_flushing=!1;last_scheduled_effect=null;is_updating_effect=!1;is_destroying_effect=!1;queued_root_effects=[];dev_effect_stack=[];active_reaction=null;untracking=!1;active_effect=null;reaction_sources=null;new_deps=null;skipped_deps=0;untracked_writes=null;write_version=1;read_version=0;skip_reaction=!1;captured_signals=null;STATUS_MASK=~(DIRTY|MAYBE_DIRTY|CLEAN);inspect_effects=new Set;old_values=new Map;component_context=null;dev_current_component_function=null;PASSIVE_EVENTS=["touchstart","touchmove"];all_styles=new Map;listening_to_form_reset=!1;all_registered_events=new Set;root_event_handles=new Set;document_listeners=new Map;mounted_components=new WeakMap;current_each_item=null;whitespace=[..." \t\n\r\f \v\ufeff"];Symbol("class");Symbol("style");IS_CUSTOM_ELEMENT=Symbol("is custom element");IS_HTML=Symbol("is html");setters_cache=new Map;pending=new Set;_ResizeObserverSingleton=class _ResizeObserverSingleton{constructor(options){__privateAdd(this,_ResizeObserverSingleton_instances);__privateAdd(this,_listeners,new WeakMap);__privateAdd(this,_observer);__privateAdd(this,_options2);__privateSet(this,_options2,options)}observe(element2,listener){var listeners=__privateGet(this,_listeners).get(element2)||new Set;listeners.add(listener);__privateGet(this,_listeners).set(element2,listeners);__privateMethod(this,_ResizeObserverSingleton_instances,getObserver_fn).call(this).observe(element2,__privateGet(this,_options2));return()=>{var listeners2=__privateGet(this,_listeners).get(element2);listeners2.delete(listener);if(0===listeners2.size){__privateGet(this,_listeners).delete(element2);__privateGet(this,_observer).unobserve(element2)}}}};_listeners=new WeakMap;_observer=new WeakMap;_options2=new WeakMap;_ResizeObserverSingleton_instances=new WeakSet;getObserver_fn=function(){var _a8;return null!=(_a8=__privateGet(this,_observer))?_a8:__privateSet(this,_observer,new ResizeObserver((entries2=>{var entry,listener;for(entry of entries2){_ResizeObserverSingleton.entries.set(entry.target,entry);for(listener of __privateGet(this,_listeners).get(entry.target)||[])listener(entry)}})))};__publicField(_ResizeObserverSingleton,"entries",new WeakMap);if(dev_fallback_default){let throw_rune_error=function(rune){if(!(rune in globalThis)){let value;Object.defineProperty(globalThis,rune,{configurable:!0,get:()=>{if(void 0!==value)return value;(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")})(rune)},set:v2=>{value=v2}})}};throw_rune_error("$state");throw_rune_error("$effect");throw_rune_error("$derived");throw_rune_error("$inspect");throw_rune_error("$props");throw_rune_error("$bindable")}subscriber_queue=[];is_store_binding=!1;IS_UNMOUNTED=Symbol();spread_props_handler={get(target,key2){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());if("object"==typeof p4&&null!==p4&&key2 in p4)return p4[key2]}},set(target,key2,value){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());const desc=get_descriptor(p4,key2);if(desc&&desc.set){desc.set(value);return!0}}return!1},getOwnPropertyDescriptor(target,key2){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());if("object"==typeof p4&&null!==p4&&key2 in p4){const descriptor=get_descriptor(p4,key2);descriptor&&!descriptor.configurable&&(descriptor.configurable=!0);return descriptor}}},has(target,key2){if(key2===STATE_SYMBOL||key2===LEGACY_PROPS)return!1;for(let p4 of target.props){is_function(p4)&&(p4=p4());if(null!=p4&&key2 in p4)return!0}return!1},ownKeys(target){const keys3=[];for(let p4 of target.props){is_function(p4)&&(p4=p4());for(const key2 in p4)keys3.includes(key2)||keys3.push(key2)}return keys3}};new WeakMap;new WeakMap;"function"==typeof HTMLElement&&HTMLElement;SUPPORTED_I18N_LANGS=["def","de","es","ja","ko","ru","zh","zh-tw"];expandedMessage={...expandKeywords(_allMessages={"(BETA) Always overwrite with a newer file":{def:"(BETA) Always overwrite with a newer file",es:"(BETA) Sobrescribir siempre con archivo más nuevo",ja:"(ベータ機能) 常に新しいファイルで上書きする",ko:"(베타) 항상 새로운 파일로 덮어쓰기",zh:"始终使用更新的文件覆盖(测试版)"},"(Beta) Use ignore files":{def:"(Beta) Use ignore files",es:"(Beta) Usar archivos de ignorar",ja:"(ベータ機能) 無視ファイル(ignore)の使用",ko:"(베타) 제외 규칙 파일 사용",zh:"(测试版)使用忽略文件"},"(Days passed, 0 to disable automatic-deletion)":{def:"(Days passed, 0 to disable automatic-deletion)",es:"(Días transcurridos, 0 para desactivar)",ko:"(지난 일수, 0으로 설정하면 자동 삭제 비활성화)",zh:"(已过天数,0为禁用自动删除)"},"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.":{def:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.",es:"(Ej: Leer chunks online) Lee chunks directamente en línea. Aumente tamaño de chunks personalizados",ko:"(예: 청크를 원격에서 읽음) 이 옵션을 활성화하면, LiveSync는 청크를 로컬에 복제하지 않고 원격에서 직접 읽습니다. 커스텀 청크 크기를 키우는 것을 권장합니다.",zh:"(例如,在线读取块)如果启用此选项,LiveSync 将直接在线读取块,而不是在本地复制块。建议增加自定义块大小"},"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.":{def:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.",es:"(MB) Saltar cambios en archivos locales/remotos mayores a este tamaño. Si se reduce, se usará versión nueva",ko:"(MB) 이 값이 설정되면, 이보다 큰 로컬 및 원격 파일의 변경 사항은 건너뜁니다. 파일이 다시 작아지면 더 새로운 파일이 사용됩니다.",zh:"(MB)如果设置了此项,大于此大小的本地和远程文件的更改将被跳过。如果文件再次变小,将使用更新的文件"},"(Mega chars)":{def:"(Mega chars)",es:"(Millones de caracteres)",ko:"(메가 문자)",zh:"(百万字符)"},"(Not recommended) If set, credentials will be stored in the file.":{def:"(Not recommended) If set, credentials will be stored in the file.",es:"(No recomendado) Almacena credenciales en el archivo",ko:"(권장하지 않음) 설정한 경우 자격 증명이 파일에 저장됩니다.",zh:"(不建议)如果设置,凭据将存储在文件中。"},"(Obsolete) Use an old adapter for compatibility":{def:"(Obsolete) Use an old adapter for compatibility",es:"(Obsoleto) Usar adaptador antiguo",ja:"古いアダプターを利用(互換性重視)",ko:"(사용 중단) 호환성을 위해 이전 어댑터 사용",zh:"(已弃用)为兼容性使用旧适配器"},"Access Key":{def:"Access Key",es:"Clave de acceso",ja:"アクセスキー",ko:"액세스 키",zh:"Access Key"},"Always prompt merge conflicts":{def:"Always prompt merge conflicts",es:"Siempre preguntar en conflictos",ja:"常に競合は手動で解決する",ko:"항상 병합 충돌 알림",zh:"始终提示合并冲突"},"Apply Latest Change if Conflicting":{def:"Apply Latest Change if Conflicting",es:"Aplicar último cambio en conflictos",ja:"書類内に競合が発生しても、常に同期内容を反映する",ko:"충돌 시 최신 변경 사항 적용",zh:"如果冲突则应用最新更改"},"Apply preset configuration":{def:"Apply preset configuration",es:"Aplicar configuración predefinida",ja:"初期設定値に戻す",ko:"프리셋 구성 적용",zh:"应用预设配置"},"Automatically Sync all files when opening Obsidian.":{def:"Automatically Sync all files when opening Obsidian.",es:"Sincronizar automáticamente todos los archivos al abrir Obsidian",ko:"Obsidian을 열 때 모든 파일을 자동으로 동기화합니다.",zh:"打开 Obsidian 时自动同步所有文件。"},"Batch database update":{def:"Batch database update",es:"Actualización por lotes de BD",ja:"データベースのバッチ更新",ko:"일괄 데이터베이스 업데이트",zh:"批量数据库更新"},"Batch limit":{def:"Batch limit",es:"Límite de lotes",ja:"バッチの上限",ko:"일괄 제한",zh:"批量限制"},"Batch size":{def:"Batch size",es:"Tamaño de lote",ja:"バッチ容量",ko:"일괄 크기",zh:"批量大小"},"Batch size of on-demand fetching":{def:"Batch size of on-demand fetching",es:"Tamaño de lote para obtención bajo demanda",ko:"필요 시 가져올 청크 묶음 크기",zh:"按需获取的批量大小"},"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.":{def:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",es:"Antes de v0.17.16 usábamos adaptador antiguo. Nuevo adaptador requiere reconstruir BD local. Desactive cuando pueda",ja:"v0.17.6までは、古いアダプターをローカル用のデータベースに使用していました。現在は新しいアダプターを推奨しています。しかし、古いデータベースを再構築するためには必要です。有効のままにしておくと、リモートデータベースからフェッチする場合に、この設定を無効にするか質問があります。",ko:"v0.17.16 이전에는 로컬 데이터베이스에 이전 어댑터를 사용했습니다. 이제는 새로운 어댑터를 권장합니다. 하지만 로컬 데이터베이스 재구축이 필요합니다. 충분한 시간이 있을 때 이 토글을 비활성화해 주세요. 활성화된 상태로 두면 원격 데이터베이스에서 가져올 때도 이를 비활성화하라는 메시지가 나타납니다.",zh:"在 v0.17.16 之前,我们使用旧适配器作为本地数据库。现在首选新适配器。但是,它需要重建本地数据库。请在有足够时间时禁用此开关。如果保持启用状态,并且在从远程数据库获取时,系统将要求您禁用此开关。"},"Bucket Name":{def:"Bucket Name",es:"Nombre del bucket",ja:"バケット名",ko:"버킷 이름",zh:"Bucket Name"},"cmdConfigSync.showCustomizationSync":{def:"Show Customization sync",es:"Mostrar sincronización de personalización",ko:"사용자 설정 동기화 표시"},"Comma separated `.gitignore, .dockerignore`":{def:"Comma separated `.gitignore, .dockerignore`",es:"Separados por comas: `.gitignore, .dockerignore`",ko:"쉼표로 구분된 `.gitignore, .dockerignore`",zh:"用逗号分隔,例如 `.gitignore, .dockerignore`"},"Compute revisions for chunks":{def:"Compute revisions for chunks",ko:"청크에 대한 리비전 계산"},"Data Compression":{def:"Data Compression",es:"Compresión de datos",ja:"データ圧縮",ko:"데이터 압축",zh:"数据压缩(实验性)"},"Database Name":{def:"Database Name",es:"Nombre de la base de datos",ja:"データベース名",ko:"데이터베이스 이름",zh:"数据库名称"},"Database suffix":{def:"Database suffix",es:"Sufijo de base de datos",ja:"データベースの接尾詞(サフィックス)",ko:"데이터베이스 접미사",zh:"数据库后缀"},"Delay conflict resolution of inactive files":{def:"Delay conflict resolution of inactive files",es:"Retrasar resolución de conflictos en archivos inactivos",ja:"無効なファイルは、競合解決を先送りする",ko:"비활성 파일의 충돌 해결 지연",zh:"推迟解决不活动文件"},"Delay merge conflict prompt for inactive files.":{def:"Delay merge conflict prompt for inactive files.",es:"Retrasar aviso de fusión para archivos inactivos",ja:"手動で無効なファイルの競合を解決する",ko:"비활성 파일의 병합 충돌 프롬프트 지연.",zh:"推迟手动解决不活动文件"},"Delete old metadata of deleted files on start-up":{def:"Delete old metadata of deleted files on start-up",es:"Borrar metadatos viejos al iniciar",ja:"削除済みデータのメタデータをクリーンナップする",ko:"시작 시 삭제된 파일의 오래된 메타데이터 삭제",zh:"启动时删除已删除文件的旧元数据"},"Device name":{def:"Device name",es:"Nombre del dispositivo",ja:"デバイスネーム",ko:"기기 이름",zh:"设备名称"},"dialog.yourLanguageAvailable":{def:"Self-hosted LiveSync had translations for your language, so the %{Display language} setting was enabled.\n\nNote: Not all messages are translated. We are waiting for your contributions!\nNote 2: If you create an Issue, **please revert to %{lang-def}** and then take screenshots, messages and logs. This can be done in the setting dialogue.\nMay you find it easy to use!",ja:"Self-hosted LiveSync にご利用の言語の翻訳がありましたので、%{Display Language}が適用されました。\n\nご注意: すべてのメッセージは翻訳されていません。あなたのコントリビューションをお待ちしています!\nその2: Issueを作成する際には、 %{Display Language} を一旦 %{lang-def} に戻してから、キャプチャやメッセージ、ログを収集してください。これは設定ダイアログから変更できます。\n\nこれで便利に使用できれば幸いです。",ko:"Self-hosted LiveSync에서 귀하의 언어로 번역을 제공하므로 %{Display language} 설정이 활성화되었습니다.\n\n참고: 모든 메시지가 번역되지는 않습니다. 귀하의 기여를 기다리고 있습니다!\n참고 2: 이슈를 생성하는 경우 **%{lang-def}로 되돌린 후** 스크린샷, 메시지, 로그를 가져와 주세요. 이는 설정 대화 상자에서 할 수 있습니다.\n간편하게 사용하실 수 있었으면 좋겠습니다!"},"dialog.yourLanguageAvailable.btnRevertToDefault":{def:"Keep %{lang-def}",ko:"%{lang-def} 유지"},"dialog.yourLanguageAvailable.Title":{def:" Translation is available!",ko:" 번역을 사용할 수 있습니다!"},"Disables logging, only shows notifications. Please disable if you report an issue.":{def:"Disables logging, only shows notifications. Please disable if you report an issue.",es:"Desactiva registros, solo muestra notificaciones. Desactívelo si reporta un problema.",ko:"로깅을 비활성화하고 알림만 표시합니다. 문제를 신고하는 경우 비활성화해 주세요.",zh:"禁用日志记录,仅显示通知。如果您报告问题,请禁用此选项。"},"Display Language":{def:"Display Language",es:"Idioma de visualización",ja:"インターフェースの表示言語",ko:"표시 언어",zh:"显示语言"},"Do not check configuration mismatch before replication":{def:"Do not check configuration mismatch before replication",es:"No verificar incompatibilidades antes de replicar",ko:"복제 전 구성 불일치 확인 안 함",zh:"在复制前不检查配置不匹配"},"Do not keep metadata of deleted files.":{def:"Do not keep metadata of deleted files.",es:"No conservar metadatos de archivos borrados",ja:"削除済みファイルのメタデータを保持しない",ko:"삭제된 파일의 메타데이터를 보관하지 않습니다.",zh:"不保留已删除文件的元数据。"},"Do not split chunks in the background":{def:"Do not split chunks in the background",es:"No dividir chunks en segundo plano",ko:"백그라운드에서 청크 분할 안 함",zh:"不在后台分割 chunks"},"Do not use internal API":{def:"Do not use internal API",es:"No usar API interna",ja:"内部APIを使用しない",ko:"내부 API 사용 안 함",zh:"不使用内部 API"},"Doctor.Button.DismissThisVersion":{def:"No, and do not ask again until the next release",ko:"아니요, 다음 릴리스까지 다시 묻지 않음"},"Doctor.Button.Fix":{def:"Fix it",ko:"수정"},"Doctor.Button.FixButNoRebuild":{def:"Fix it but no rebuild",ko:"수정하지만 재구축하지 않음"},"Doctor.Button.No":{def:"No",ko:"아니요"},"Doctor.Button.Skip":{def:"Leave it as is",ko:"그대로 두기"},"Doctor.Button.Yes":{def:"Yes",ko:"예"},"Doctor.Dialogue.Main":{def:"Hi! Config Doctor has been activated because of ${activateReason}!\nAnd, unfortunately some configurations were detected as potential problems.\nPlease be assured. Let's solve them one by one.\n\nTo let you know ahead of time, we will ask you about the following items.\n\n${issues}\n\nShall we get started?",ko:"안녕하세요! ${activateReason} 로 인해 구성 진단 마법사가 활성화되었습니다!\n그리고 일부 구성이 잠재적인 문제로 감지되었습니다.\n안심하세요. 하나씩 해결해 봅시다.\n\n대상 항목은 다음과 같습니다.\n\n${issues}\n\n시작하시겠습니까?"},"Doctor.Dialogue.MainFix":{def:"\n## ${name}\n\n| Current | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Recommendation Level:** ${level}\n\n### Why this has been detected?\n\n${reason}\n\n${note}\n\nFix this to the ideal value?",ko:"**구성 이름:** `${name}`\n**현재 값:** `${current}`, **이상적인 값:** `${ideal}`\n**권장 수준:** ${level}\n**왜 이것이 감지되었나요?**\n${reason}\n\n\n${note}\n\n이상적인 값으로 수정하시겠습니까?"},"Doctor.Dialogue.Title":{def:"Self-hosted LiveSync Config Doctor",ko:"Self-hosted LiveSync 구성 진단 마법사"},"Doctor.Dialogue.TitleAlmostDone":{def:"Almost done!",ko:"거의 완료되었습니다!"},"Doctor.Dialogue.TitleFix":{def:"Fix issue ${current}/${total}",ko:"문제 해결 ${current}/${total}"},"Doctor.Level.Must":{def:"Must",ko:"필수"},"Doctor.Level.Necessary":{def:"Necessary",ko:"필수"},"Doctor.Level.Optional":{def:"Optional",ko:"선택사항"},"Doctor.Level.Recommended":{def:"Recommended",ko:"권장"},"Doctor.Message.NoIssues":{def:"No issues detected!",ko:"문제가 감지되지 않았습니다!"},"Doctor.Message.RebuildLocalRequired":{def:"Attention! A local database rebuild is required to apply this!",ko:"주의! 이를 적용하려면 로컬 데이터베이스 재구축이 필요합니다!"},"Doctor.Message.RebuildRequired":{def:"Attention! A rebuild is required to apply this!",ko:"주의! 이를 적용하려면 재구축이 필요합니다!"},"Doctor.Message.SomeSkipped":{def:"We left some issues as is. Shall I ask you again on next startup?",ko:"일부 문제를 그대로 두었습니다. 다음 시작 시 다시 질문할까요?"},"Enable advanced features":{def:"Enable advanced features",es:"Habilitar características avanzadas",ko:"고급 기능 활성화",zh:"启用高级功能"},"Enable customization sync":{def:"Enable customization sync",es:"Habilitar sincronización de personalización",ja:"カスタマイズ同期を有効",ko:"사용자 설정 동기화 활성화",zh:"启用自定义同步"},"Enable Developers' Debug Tools.":{def:"Enable Developers' Debug Tools.",es:"Habilitar herramientas de depuración",ko:"개발자 디버그 도구 활성화",zh:"启用开发者调试工具。"},"Enable edge case treatment features":{def:"Enable edge case treatment features",es:"Habilitar manejo de casos límite",ko:"특수 사례 처리 기능 활성화",zh:"启用边缘情况处理功能"},"Enable poweruser features":{def:"Enable poweruser features",es:"Habilitar funciones para usuarios avanzados",ko:"파워 유저 기능 활성화",zh:"启用高级用户功能"},"Enable this if your Object Storage doesn't support CORS":{def:"Enable this if your Object Storage doesn't support CORS",es:"Habilitar si su almacenamiento no soporta CORS",ko:"객체 스토리지가 CORS를 지원하지 않는 경우 활성화하세요",zh:"如果您的对象存储不支持 CORS,请启用此功能。"},"Enable this option to automatically apply the most recent change to documents even when it conflicts":{def:"Enable this option to automatically apply the most recent change to documents even when it conflicts",es:"Aplicar cambios recientes automáticamente aunque generen conflictos",ko:"이 옵션을 활성화하면 충돌이 있어도 문서에 가장 최근 변경 사항을 자동으로 적용합니다",zh:"启用此选项可在文档冲突时自动应用最新的更改"},"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.":{def:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.",es:"Cifrar contenido en la base de datos remota. Se recomienda habilitar si usa la sincronización del plugin.",ja:"リモートデータベースの暗号化(オンにすることをお勧めします)",ko:"원격 데이터베이스의 내용을 암호화합니다. 플러그인의 동기화 기능을 사용하는 경우 활성화를 권장합니다.",zh:"加密远程数据库中的内容。如果您使用插件的同步功能,则建议启用此功能。"},"Encrypting sensitive configuration items":{def:"Encrypting sensitive configuration items",es:"Cifrando elementos sensibles",ja:"機微設定項目の暗号化",ko:"민감한 구성 항목 암호화",zh:"加密敏感配置项"},"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.":{def:"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.",es:"Frase de cifrado. Si la cambia, sobrescriba la base del servidor con los nuevos archivos cifrados.",ko:"패스프레이즈는 암호화에 사용되는 긴 암호 문구입니다. 변경한 경우, 암호화된 새 파일로 서버의 데이터베이스를 덮어써야 합니다.",zh:"加密密码。如果更改,您应该用新的(加密的)文件覆盖服务器的数据库。"},"End-to-End Encryption":{def:"End-to-End Encryption",es:"Cifrado de extremo a extremo",ja:"E2E暗号化",ko:"종단간 암호화",zh:"端到端加密"},"Endpoint URL":{def:"Endpoint URL",es:"URL del endpoint",ja:"エンドポイントURL",ko:"엔드포인트 URL",zh:"Endpoint URL"},"Enhance chunk size":{def:"Enhance chunk size",es:"Mejorar tamaño de chunks",ja:"チャンクサイズを最新にする",ko:"청크 크기 향상",zh:"增强块大小"},"Fetch chunks on demand":{def:"Fetch chunks on demand",es:"Obtener chunks bajo demanda",ja:"ユーザーのタイミングでチャンクの更新を確認する",ko:"필요 시 청크 원격 가져오기",zh:"按需获取块"},"Fetch database with previous behaviour":{def:"Fetch database with previous behaviour",es:"Obtener BD con comportamiento anterior",ja:"以前の手法でデータベースを取得",ko:"이전 동작으로 데이터베이스 가져오기",zh:"使用以前的行为获取数据库"},Filename:{def:"Filename",es:"Nombre de archivo",ja:"ファイル名",ko:"파일명",zh:"文件名"},"Forces the file to be synced when opened.":{def:"Forces the file to be synced when opened.",es:"Forzar sincronización al abrir archivo",ko:"파일을 열 때 강제로 동기화합니다.",zh:"打开文件时强制同步该文件。"},"Handle files as Case-Sensitive":{def:"Handle files as Case-Sensitive",es:"Manejar archivos como sensibles a mayúsculas",ko:"파일을 대소문자 구분으로 처리",zh:"将文件视为区分大小写"},"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).":{def:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).",es:"Si se desactiva, chunks se dividen en hilo UI (comportamiento anterior)",ko:"비활성화(토글)되면 청크는 UI 스레드에서 분할됩니다 (이전 동작).",zh:"如果禁用(切换),chunks 将在 UI 线程上分割(以前的行为)。"},"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.":{def:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.",es:"Habilita sincronización eficiente por archivo. Requiere migración y actualizar todos dispositivos a v0.23.18. Pierde compatibilidad con versiones antiguas",ko:"활성화하면 파일별 효율적인 사용자 설정 동기화가 사용됩니다. 이를 활성화할 때 소규모 데이터 구조 전환이 필요합니다. 모든 기기를 v0.23.18로 업데이트해야 합니다. 이를 활성화하면 이전 버전과의 호환성이 사라집니다.",zh:"如果启用,将使用基于文件的、高效的自定义同步。启用此功能需要进行一次小的迁移。所有设备都应更新到 v0.23.18。一旦启用此功能,我们将失去与旧版本的兼容性。"},"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.":{def:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.",es:"Divide chunks en máximo 100 ítems. Menos eficiente en deduplicación",ko:"활성화하면 청크는 최대 100개 항목으로 분할됩니다. 하지만 중복 제거 기능이 약간 약해집니다.",zh:"如果启用,数据块将被分割成不超过 100 项。但是,去重效果会稍弱。"},"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.":{def:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",es:"Chunks nuevos se mantienen temporalmente en el documento hasta estabilizarse",ko:"활성화하면 새로 생성된 변경 기록(청크)은 문서 안에 임시로 보관되며, 일정 조건을 만족하면 자동으로 문서 밖으로 분리되어 저장됩니다.",zh:"如果启用,新创建的数据块将暂时保留在文档中,并在稳定后成为独立数据块。"},"If enabled, the file under 1kb will be processed in the UI thread.":{def:"If enabled, the file under 1kb will be processed in the UI thread.",es:"Archivos <1kb se procesan en hilo UI",ko:"활성화하면 1kb 미만의 파일은 UI 스레드에서 처리됩니다.",zh:"如果启用,小于 1kb 的文件将在 UI 线程中处理。"},"If enabled, the notification of hidden files change will be suppressed.":{def:"If enabled, the notification of hidden files change will be suppressed.",es:"Si se habilita, se suprimirá la notificación de cambios en archivos ocultos.",ko:"활성화하면 숨겨진 파일 변경 알림이 억제됩니다.",zh:"如果启用,隐藏文件更改的通知将被抑制。"},"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)":{def:"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)",es:"Si se habilita, todos los chunks se almacenan con la revisión hecha desde su contenido. (comportamiento anterior)",ko:"이 옵션이 활성화되면 모든 청크는 콘텐츠에서 생성된 리비전과 함께 저장됩니다. (이전 동작)",zh:"如果启用,所有 chunks 将使用根据其内容生成的修订版本存储。(以前的行为)"},"If this enabled, All files are handled as case-Sensitive (Previous behaviour).":{def:"If this enabled, All files are handled as case-Sensitive (Previous behaviour).",es:"Si se habilita, todos los archivos se manejan como sensibles a mayúsculas (comportamiento anterior)",ko:"이 옵션이 활성화되면 모든 파일이 대소문자를 구분하여 처리됩니다 (이전 동작).",zh:"如果启用,所有文件都将视为区分大小写(以前的行为)。"},"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.":{def:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.",es:"Divide chunks en segmentos semánticos. No todos los sistemas lo soportan",ko:"이 옵션을 활성화하면 청크가 문단이나 의미 단위로 나뉘어 저장됩니다. 단, 이 기능은 일부 플랫폼에서는 지원되지 않을 수 있습니다.",zh:"如果启用此功能,数据块将被分割成具有语义意义的段落。并非所有平台都支持此功能。"},"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.":{def:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.",es:"Saltar cambios en archivos locales que coincidan con ignore files. Cambios remotos usan ignore files locales",ko:"이 옵션을 활성화하면, 제외 규칙 파일에 일치하는 로컬 파일의 변경 사항은 건너뜁니다. 원격 변경 여부 또한 로컬의 제외 규칙 파일에 따라 판단됩니다.",zh:"如果设置了此项,与忽略文件匹配的本地文件的更改将被跳过。远程更改使用本地忽略文件确定"},"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.":{def:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.",es:"Mantiene conexión 60s. Si no hay cambios, reinicia socket. Útil con proxies limitantes",ja:"PouchDBの接続を60秒間維持し、その間に変更がない場合、接続を切断してソケットを再び開きます。プロキシによるリクエスト時間制限があり、なおかつリソースの使用量が増える可能性がある場合に便利です。",ko:"이 옵션이 활성화되면 PouchDB는 연결을 더이상 무한히 열어두지 않고 60초 동안 유지합니다. 그 시간 내에 변경 사항이 없으면 소켓을 닫고 다시 엽니다. 프록시가 요청 지속 시간을 제한할 때 유용하지만 리소스 사용량이 증가할 수 있습니다.",zh:"如果启用此选项,PouchDB 将保持连接打开 60 秒,如果在此时间内没有更改到达,则关闭并重新打开套接字,而不是无限期保持打开。当代理限制请求持续时间时有用,但可能会增加资源使用。"},"Ignore files":{def:"Ignore files",es:"Archivos a ignorar",ja:"無視ファイル",ko:"제외 규칙 파일",zh:"忽略文件"},"Incubate Chunks in Document":{def:"Incubate Chunks in Document",es:"Incubar chunks en documento",ja:"ドキュメント内でハッチングを行う",ko:"문서 내 변경 기록 임시 보관",zh:"在文档中孵化块(测试版)"},"Interval (sec)":{def:"Interval (sec)",es:"Intervalo (segundos)",ja:"秒",ko:"간격 (초)",zh:"间隔(秒)"},"K.exp":{def:"Experimental",ko:"실험 기능"},"K.long_p2p_sync":{def:"%{title_p2p_sync} (%{exp})",ko:"%{title_p2p_sync} (%{exp})"},"K.P2P":{def:"%{Peer}-to-%{Peer}",ko:"%{Peer}-to-%{Peer}"},"K.Peer":{def:"Peer",ko:"피어"},"K.ScanCustomization":{def:"Scan customization",ko:"사용자 설정 검색"},"K.short_p2p_sync":{def:"P2P Sync (%{exp})",ko:"P2P 동기화 (%{exp})"},"K.title_p2p_sync":{def:"Peer-to-Peer Sync",ko:"피어 투 피어(P2P) 동기화"},"Keep empty folder":{def:"Keep empty folder",es:"Mantener carpetas vacías",ja:"空フォルダの維持",ko:"빈 폴더 유지",zh:"保留空文件夹"},lang_def:{def:"Default",ko:"Default"},"lang-de":{def:"Deutsche",es:"Alemán",ko:"Deutsche",zh:"德语"},"lang-def":{def:"%{lang_def}",ko:"%{lang_def}"},"lang-es":{def:"Español",es:"Español",ko:"Español",zh:"西班牙语"},"lang-ja":{def:"日本語",es:"Japonés",ko:"日本語",zh:"日语"},"lang-ko":{def:"한국어",ko:"한국어"},"lang-ru":{def:"Русский",es:"Ruso",ko:"Русский",zh:"俄语"},"lang-zh":{def:"简体中文",es:"Chino simplificado",ko:"简体中文",zh:"简体中文"},"lang-zh-tw":{def:"繁體中文",es:"Chino tradicional",ko:"繁體中文",zh:"繁體中文"},"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.":{def:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.",es:"LiveSync no puede manejar múltiples bóvedas con mismo nombre sin prefijo. Se configura automáticamente",ja:"LiveSyncは、接頭詞のない同名の保管庫を扱うことができません。この設定は、自動的に設定されます。",ko:"LiveSync는 서로 다른 접두사 없이 동일한 이름을 가진 여러 볼트를 처리할 수 없습니다. 이는 자동으로 구성되어야 합니다.",zh:"LiveSync 无法处理具有相同名称但没有不同前缀的多个库。这应该自动配置。"},"liveSyncReplicator.beforeLiveSync":{def:"Before LiveSync, start OneShot once...",es:"Antes de LiveSync, inicia OneShot...",ko:"LiveSync 전에 OneShot을 먼저 시작합니다..."},"liveSyncReplicator.cantReplicateLowerValue":{def:"We can't replicate more lower value.",es:"No podemos replicar un valor más bajo.",ko:"더 낮은 값으로 복제할 수 없습니다."},"liveSyncReplicator.checkingLastSyncPoint":{def:"Looking for the point last synchronized point.",es:"Buscando el último punto sincronizado.",ko:"마지막으로 동기화된 지점을 찾고 있습니다."},"liveSyncReplicator.couldNotConnectTo":{def:"Could not connect to ${uri} : ${name}\n(${db})",es:"No se pudo conectar a ${uri} : ${name} \n(${db})",ko:"${uri}에 연결할 수 없습니다: ${name} \n(${db})"},"liveSyncReplicator.couldNotConnectToRemoteDb":{def:"Could not connect to remote database: ${d}",es:"No se pudo conectar a base de datos remota: ${d}",ko:"원격 데이터베이스에 연결할 수 없습니다: ${d}"},"liveSyncReplicator.couldNotConnectToServer":{def:"Could not connect to server.",es:"No se pudo conectar al servidor.",ko:"서버에 연결할 수 없습니다."},"liveSyncReplicator.couldNotConnectToURI":{def:"Could not connect to ${uri}:${dbRet}",es:"No se pudo conectar a ${uri}:${dbRet}",ko:"${uri}에 연결할 수 없습니다: ${dbRet}"},"liveSyncReplicator.couldNotMarkResolveRemoteDb":{def:"Could not mark resolve remote database.",es:"No se pudo marcar como resuelta la base de datos remota.",ko:"원격 데이터베이스를 해결됨으로 표시할 수 없습니다."},"liveSyncReplicator.liveSyncBegin":{def:"LiveSync begin...",es:"Inicio de LiveSync...",ko:"LiveSync 시작..."},"liveSyncReplicator.lockRemoteDb":{def:"Lock remote database to prevent data corruption",es:"Bloquear base de datos remota para prevenir corrupción de datos",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠급니다"},"liveSyncReplicator.markDeviceResolved":{def:"Mark this device as 'resolved'.",es:"Marcar este dispositivo como 'resuelto'.",ko:"이 기기를 '해결됨'으로 표시합니다."},"liveSyncReplicator.oneShotSyncBegin":{def:"OneShot Sync begin... (${syncMode})",es:"Inicio de sincronización OneShot... (${syncMode})",ko:"OneShot 동기화 시작... (${syncMode})"},"liveSyncReplicator.remoteDbCorrupted":{def:"Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed",es:"La base de datos remota es más nueva o está dañada, asegúrese de tener la última versión de self-hosted-livesync instalada",ko:"원격 데이터베이스가 더 최신이거나 손상되었습니다. 최신 버전의 self-hosted-livesync가 설치되어 있는지 확인하세요"},"liveSyncReplicator.remoteDbCreatedOrConnected":{def:"Remote Database Created or Connected",es:"Base de datos remota creada o conectada",ko:"원격 데이터베이스가 생성되거나 연결되었습니다"},"liveSyncReplicator.remoteDbDestroyed":{def:"Remote Database Destroyed",es:"Base de datos remota destruida",ko:"원격 데이터베이스가 삭제되었습니다"},"liveSyncReplicator.remoteDbDestroyError":{def:"Something happened on Remote Database Destroy:",es:"Algo ocurrió al destruir base de datos remota:",ko:"원격 데이터베이스 삭제 중 오류가 발생했습니다:"},"liveSyncReplicator.remoteDbMarkedResolved":{def:"Remote database has been marked resolved.",es:"Base de datos remota marcada como resuelta.",ko:"원격 데이터베이스가 해결됨으로 표시되었습니다."},"liveSyncReplicator.replicationClosed":{def:"Replication closed",es:"Replicación cerrada",ko:"복제가 종료되었습니다"},"liveSyncReplicator.replicationInProgress":{def:"Replication is already in progress",es:"Replicación en curso",ko:"복제가 이미 진행 중입니다"},"liveSyncReplicator.retryLowerBatchSize":{def:"Retry with lower batch size:${batch_size}/${batches_limit}",es:"Reintentar con tamaño de lote más bajo:${batch_size}/${batches_limit}",ko:"더 낮은 일괄 크기로 재시도: ${batch_size}/${batches_limit}"},"liveSyncReplicator.unlockRemoteDb":{def:"Unlock remote database to prevent data corruption",es:"Desbloquear base de datos remota para prevenir corrupción de datos",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠금 해제합니다"},"liveSyncSetting.errorNoSuchSettingItem":{def:"No such setting item: ${key}",es:"No existe el ajuste: ${key}",ko:"해당 설정 항목이 없습니다: ${key}"},"liveSyncSetting.originalValue":{def:"Original: ${value}",es:"Original: ${value}",ko:"원본: ${value}"},"liveSyncSetting.valueShouldBeInRange":{def:"The value should ${min} < value < ${max}",es:"El valor debe estar entre ${min} y ${max}",ko:"값은 ${min} < 값 < ${max} 범위에 있어야 합니다"},"liveSyncSettings.btnApply":{def:"Apply",es:"Aplicar",ko:"적용"},"logPane.autoScroll":{def:"Auto scroll",es:"Autodesplazamiento",ko:"자동 스크롤",zh:"自动滚动"},"logPane.logWindowOpened":{def:"Log window opened",es:"Ventana de registro abierta",ko:"로그 창이 열렸습니다"},"logPane.pause":{def:"Pause",es:"Pausar",ko:"일시 중단",zh:"暂停"},"logPane.title":{def:"Self-hosted LiveSync Log",es:"Registro de Self-hosted LiveSync",ko:"Self-hosted LiveSync 로그",zh:"Self-hosted LiveSync 日志"},"logPane.wrap":{def:"Wrap",es:"Ajustar",ko:"줄 바꿈",zh:"自动换行"},"Maximum delay for batch database updating":{def:"Maximum delay for batch database updating",es:"Retraso máximo para actualización por lotes",ko:"일괄 데이터베이스 업데이트 최대 지연",zh:"批量数据库更新的最大延迟"},"Maximum file size":{def:"Maximum file size",es:"Tamaño máximo de archivo",ja:"最大ファイル容量",ko:"최대 파일 크기",zh:"最大文件大小"},"Maximum Incubating Chunk Size":{def:"Maximum Incubating Chunk Size",es:"Tamaño máximo de chunks incubados",ja:"保持するチャンクの最大サイズ",ko:"임시 보관 변경 기록의 최대 크기",zh:"最大孵化块大小"},"Maximum Incubating Chunks":{def:"Maximum Incubating Chunks",es:"Máximo de chunks incubados",ja:"最大ハッチング数",ko:"임시 보관 중인 변경 기록 최대 수",zh:"最大孵化块数"},"Maximum Incubation Period":{def:"Maximum Incubation Period",es:"Periodo máximo de incubación",ja:"最大保持期限",ko:"변경 기록 임시 보관 최대 시간",zh:"最大孵化期"},"MB (0 to disable).":{def:"MB (0 to disable).",es:"MB (0 para desactivar)",ko:"MB (0으로 설정하면 비활성화).",zh:"MB(0为禁用)。"},"Memory cache size (by total characters)":{def:"Memory cache size (by total characters)",es:"Tamaño caché memoria (por caracteres)",ja:"全体でキャッシュする文字数",ko:"메모리 캐시 크기 (총 문자 수)",zh:"内存缓存大小(按总字符数)"},"Memory cache size (by total items)":{def:"Memory cache size (by total items)",es:"Tamaño caché memoria (por ítems)",ja:"全体のキャッシュサイズ",ko:"메모리 캐시 크기 (총 항목 수)",zh:"内存缓存大小(按总项目数)"},"Minimum delay for batch database updating":{def:"Minimum delay for batch database updating",es:"Retraso mínimo para actualización por lotes",ko:"일괄 데이터베이스 업데이트 최소 지연",zh:"批量数据库更新的最小延迟"},"moduleCheckRemoteSize.logCheckingStorageSizes":{def:"Checking storage sizes",es:"Comprobando tamaños de almacenamiento",ko:"스토리지 크기 확인 중",zh:"正在检查存储大小"},"moduleCheckRemoteSize.logCurrentStorageSize":{def:"Remote storage size: ${measuredSize}",es:"Tamaño del almacenamiento remoto: ${measuredSize}",ko:"원격 스토리지 크기: ${measuredSize}",zh:"远程存储大小:${measuredSize}"},"moduleCheckRemoteSize.logExceededWarning":{def:"Remote storage size: ${measuredSize} exceeded ${notifySize}",es:"Tamaño del almacenamiento remoto: ${measuredSize} superó ${notifySize}",ko:"원격 스토리지 크기: ${measuredSize}가 ${notifySize}를 초과했습니다",zh:"远程存储大小:${measuredSize} 超过 ${notifySize}"},"moduleCheckRemoteSize.logThresholdEnlarged":{def:"Threshold has been enlarged to ${size}MB",es:"El umbral se ha ampliado a ${size}MB",ko:"임계값이 ${size}MB로 증가되었습니다",zh:"阈值已扩大到 ${size}MB"},"moduleCheckRemoteSize.msgConfirmRebuild":{def:"This may take a bit of a long time. Do you really want to rebuild everything now?",es:"Esto puede llevar un poco de tiempo. ¿Realmente quieres reconstruir todo ahora?",ko:"시간이 꽤 오래 걸릴 수 있습니다. 정말 지금 모든 것을 재구축하시겠습니까?",zh:"这可能需要一些时间。您真的想现在重建所有内容吗?"},"moduleCheckRemoteSize.msgDatabaseGrowing":{def:"**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.\n\n| Measured size | Configured size |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.\n>\n> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.\n>\n\n> [!WARNING]\n> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.\n",es:"**¡Tu base de datos está creciendo!** Pero no te preocupes, podemos abordarlo ahora. El tiempo antes de quedarse sin espacio en el almacenamiento remoto.\n\n| Tamaño medido | Tamaño configurado |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> Si lo has estado utilizando durante muchos años, puede haber fragmentos no referenciados - es decir, basura - acumulándose en la base de datos. Por lo tanto, recomendamos reconstruir todo. Probablemente se volverá mucho más pequeño.\n>\n> Si el volumen de tu bóveda simplemente está aumentando, es mejor reconstruir todo después de organizar los archivos. Self-hosted LiveSync no elimina los datos reales incluso si los eliminas para acelerar el proceso. Está aproximadamente [documentado](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> Si no te importa el aumento, puedes aumentar el límite de notificación en 100 MB. Este es el caso si lo estás ejecutando en tu propio servidor. Sin embargo, es mejor reconstruir todo de vez en cuando.\n>\n\n> [!WARNING]\n> Si realizas la reconstrucción completa, asegúrate de que todos los dispositivos estén sincronizados. El complemento fusionará tanto como sea posible, sin embargo.\n",ko:"**데이터베이스 용량이 점점 커지고 있습니다!** 하지만 걱정하지 마세요. 아직 원격 스토리지 공간이 완전히 부족해진 건 아닙니다.\n\n| 측정된 크기 | 설정된 한도 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 오랜 기간 사용했다면 참조되지 않는 청크, 즉 '쓰레기 데이터'가 쌓였을 수 있습니다. 이 경우 전체 재구성을 권장합니다. 용량이 훨씬 줄어들 수 있습니다.\n> \n> 단순히 볼트 자체 용량이 커지고 있는 것이라면, 먼저 파일을 정리한 후 전체를 재구성하는 것이 좋습니다. Self-hosted LiveSync는 처리 속도를 위해 삭제해도 실제 데이터를 바로 지우지 않습니다. 이 내용은 [기술 문서](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)에 간략히 정리되어 있습니다.\n> \n> 용량 증가가 괜찮다면 알림 임계치를 100MB 단위로 높일 수 있습니다. 직접 서버를 운영하는 경우에 적합한 방법입니다. 다만, 가끔은 전체 재구성을 해주는 것이 바람직합니다.\n\n> [!WARNING]\n> 전체 재구성을 실행할 경우, 모든 기기가 반드시 동기화되어 있어야 합니다. 플러그인이 최대한 병합하려고 시도하긴 하지만 완전하지 않을 수 있습니다.",zh:"**您的数据库正在变大!** 但别担心,我们现在可以解决它。在远程存储空间用完之前还有时间。\n\n| 测量大小 | 配置大小 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 如果您已经使用了很多年,数据库中可能会积累未引用的 chunks——也就是垃圾。因此,我们建议重建所有内容。它可能会变得小得多。\n> \n> 如果您的库容量只是在增加,最好在整理文件后重建所有内容。即使您为了加速过程删除了文件,Self-hosted LiveSync 也不会删除实际数据。这大致[有文档记录](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)。\n> \n> 如果您不介意增加,可以将通知限制增加 100MB。如果您在自己的服务器上运行,就是这种情况。但是,最好还是不时地重建所有内容。\n> \n\n> [!WARNING]\n> 如果您执行重建所有内容,请确保所有设备都已同步。尽管如此,插件会尽可能地合并。\n"},"moduleCheckRemoteSize.msgSetDBCapacity":{def:"We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.\nDo you want to enable this?\n\n> [!MORE]-\n> - 0: Do not warn about storage size.\n> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.\n> - 800: Warn if the remote storage size exceeds 800MB.\n> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.\n> - 2000: Warn if the remote storage size exceeds 2GB.\n\nIf we have reached the limit, we will be asked to enlarge the limit step by step.\n",es:"Podemos configurar una advertencia de capacidad máxima de base de datos, **para tomar medidas antes de quedarse sin espacio en el almacenamiento remoto**.\n¿Quieres habilitar esto?\n\n> [!MORE]-\n> - 0: No advertir sobre el tamaño del almacenamiento.\n> Esto es recomendado si tienes suficiente espacio en el almacenamiento remoto, especialmente si lo tienes autoalojado. Y puedes comprobar el tamaño del almacenamiento y reconstruir manualmente.\n> - 800: Advertir si el tamaño del almacenamiento remoto supera los 800 MB.\n> Esto es recomendado si estás usando fly.io con un límite de 1 GB o IBM Cloudant.\n> - 2000: Advertir si el tamaño del almacenamiento remoto supera los 2 GB.\n\nSi hemos alcanzado el límite, se nos pedirá que aumentemos el límite paso a paso.\n",ko:"**원격 스토리지 공간이 부족해지기 전에 미리 조치할 수 있도록** 데이터베이스 용량 경고를 설정할 수 있습니다.\n이 기능을 활성화하시겠습니까?\n\n> [!MORE]-\n> - 0: 스토리지 용량에 대한 경고 없음\n> 자체 서버를 사용하는 등 여유 공간이 충분한 경우에 권장됩니다. 스토리지 용량을 직접 확인하고 수동으로 재구성할 수 있습니다.\n> - 800: 원격 스토리지 용량이 800MB를 초과하면 경고\n> 1GB 제한이 있는 fly.io나 IBM Cloudant 사용 시 권장됩니다.\n> - 2000: 원격 스토리지 용량이 2GB를 초과하면 경고\n\n설정한 용량 한도에 도달하면, 단계적으로 경고 한도를 늘릴지 여부를 묻게 됩니다.\n",zh:"我们可以设置一个最大数据库容量警告,**以便在远程存储空间耗尽前采取行动**。\n您想启用这个功能吗?\n\n> [!MORE]-\n> - 0: 不警告存储大小。\n> 如果您在远程存储(尤其是自托管)上有足够的空间,则推荐此选项。您可以手动检查存储大小并重建。\n> - 800: 如果远程存储大小超过 800MB 则发出警告。\n> 如果您使用的是 fly.io(1GB 限制)或 IBM Cloudant,则推荐此选项。\n> - 2000: 如果远程存储大小超过 2GB 则发出警告。\n\n如果达到限制,系统会要求我们逐步增大限制。\n"},"moduleCheckRemoteSize.option2GB":{def:"2GB (Standard)",es:"2GB (Estándar)",ko:"2GB (표준)",zh:"2GB (标准)"},"moduleCheckRemoteSize.option800MB":{def:"800MB (Cloudant, fly.io)",es:"800MB (Cloudant, fly.io)",ko:"800MB (Cloudant, fly.io)",zh:"800MB (Cloudant, fly.io)"},"moduleCheckRemoteSize.optionAskMeLater":{def:"Ask me later",es:"Pregúntame más tarde",ko:"나중에 물어보기",zh:"稍后问我"},"moduleCheckRemoteSize.optionDismiss":{def:"Dismiss",es:"Descartar",ko:"무시",zh:"忽略"},"moduleCheckRemoteSize.optionIncreaseLimit":{def:"increase to ${newMax}MB",es:"aumentar a ${newMax}MB",ko:"${newMax}MB로 증가",zh:"增加到 ${newMax}MB"},"moduleCheckRemoteSize.optionNoWarn":{def:"No, never warn please",es:"No, nunca advertir por favor",ko:"아니요, 경고하지 마세요",zh:"不,请永远不要警告"},"moduleCheckRemoteSize.optionRebuildAll":{def:"Rebuild Everything Now",es:"Reconstruir todo ahora",ko:"지금 모든 것 재구축",zh:"立即重建所有内容"},"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded":{def:"Remote storage size exceeded the limit",es:"El tamaño del almacenamiento remoto superó el límite",ko:"원격 스토리지 크기가 제한을 초과했습니다",zh:"远程存储大小超出限制"},"moduleCheckRemoteSize.titleDatabaseSizeNotify":{def:"Setting up database size notification",es:"Configuración de notificación de tamaño de base de datos",ko:"데이터베이스 크기 알림 설정",zh:"设置数据库大小通知"},"moduleInputUIObsidian.defaultTitleConfirmation":{def:"Confirmation",es:"Confirmación",ko:"확인",zh:"确认"},"moduleInputUIObsidian.defaultTitleSelect":{def:"Select",es:"Seleccionar",ko:"선택",zh:"选择"},"moduleInputUIObsidian.optionNo":{def:"No",es:"No",ko:"아니요",zh:"否"},"moduleInputUIObsidian.optionYes":{def:"Yes",es:"Sí",ko:"예",zh:"是"},"moduleLiveSyncMain.logAdditionalSafetyScan":{def:"Additional safety scan...",es:"Escanéo de seguridad adicional...",ko:"추가 안전 검사 중...",zh:"额外的安全扫描..."},"moduleLiveSyncMain.logLoadingPlugin":{def:"Loading plugin...",es:"Cargando complemento...",ko:"플러그인 로딩 중...",zh:"正在加载插件..."},"moduleLiveSyncMain.logPluginInitCancelled":{def:"Plugin initialisation was cancelled by a module",es:"La inicialización del complemento fue cancelada por un módulo",ko:"모듈에 의해 플러그인 초기화가 취소되었습니다",zh:"插件初始化被某个模块取消"},"moduleLiveSyncMain.logPluginVersion":{def:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",es:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",ko:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",zh:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}"},"moduleLiveSyncMain.logReadChangelog":{def:"LiveSync has updated, please read the changelog!",es:"LiveSync se ha actualizado, ¡por favor lee el registro de cambios!",ko:"LiveSync가 업데이트되었습니다. 변경사항을 읽어보세요!",zh:"LiveSync 已更新,请阅读更新日志!"},"moduleLiveSyncMain.logSafetyScanCompleted":{def:"Additional safety scan completed",es:"Escanéo de seguridad adicional completado",ko:"추가 안전 검사가 완료되었습니다",zh:"额外的安全扫描完成"},"moduleLiveSyncMain.logSafetyScanFailed":{def:"Additional safety scan has failed on a module",es:"El escaneo de seguridad adicional ha fallado en un módulo",ko:"모듈에서 추가 안전 검사가 실패했습니다",zh:"额外的安全扫描在某个模块上失败"},"moduleLiveSyncMain.logUnloadingPlugin":{def:"Unloading plugin...",es:"Descargando complemento...",ko:"플러그인 언로딩 중...",zh:"正在卸载插件..."},"moduleLiveSyncMain.logVersionUpdate":{def:"LiveSync has been updated, In case of breaking updates, all automatic synchronization has been temporarily disabled. Ensure that all devices are up to date before enabling.",es:"LiveSync se ha actualizado, en caso de actualizaciones que rompan, toda la sincronización automática se ha desactivado temporalmente. Asegúrate de que todos los dispositivos estén actualizados antes de habilitar.",ko:"LiveSync가 업데이트되었습니다. 호환성 문제가 있는 업데이트의 경우 모든 자동 동기화가 일시적으로 비활성화되었습니다. 활성화하기 전에 모든 기기가 최신 상태인지 확인하세요.",zh:"LiveSync 已更新,如果存在破坏性更新,所有自动同步已暂时禁用。请确保所有设备都更新到最新版本后再启用。"},"moduleLiveSyncMain.msgScramEnabled":{def:"Self-hosted LiveSync has been configured to ignore some events. Is this correct?\n\n| Type | Status | Note |\n|:---:|:---:|---|\n| Storage Events | ${fileWatchingStatus} | Every modification will be ignored |\n| Database Events | ${parseReplicationStatus} | Every synchronised change will be postponed |\n\nDo you want to resume them and restart Obsidian?\n\n> [!DETAILS]-\n> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.\n> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.\n",es:"Self-hosted LiveSync se ha configurado para ignorar algunos eventos. ¿Es esto correcto?\n\n| Tipo | Estado | Nota |\n|:---:|:---:|---|\n| Eventos de almacenamiento | ${fileWatchingStatus} | Se ignorará cada modificación |\n| Eventos de base de datos | ${parseReplicationStatus} | Cada cambio sincronizado se pospondrá |\n\n¿Quieres reanudarlos y reiniciar Obsidian?\n\n> [!DETAILS]-\n> Estas banderas son establecidas por el complemento mientras se reconstruye o se obtiene. Si el proceso termina de forma anormal, puede mantenerse sin querer.\n> Si no estás seguro, puedes intentar volver a ejecutar estos procesos. Asegúrate de hacer una copia de seguridad de tu bóveda.\n",ko:"Self-hosted LiveSync가 일부 이벤트를 무시하도록 설정되어 있습니다. 이 설정이 맞습니까?\n\n| 유형 | 상태 | 설명 |\n|:---:|:---:|---|\n| 스토리지 이벤트 | ${fileWatchingStatus} | 모든 수정 사항이 무시됩니다 |\n| 데이터베이스 이벤트 | ${parseReplicationStatus} | 모든 동기화 변경이 지연됩니다 |\n\n이벤트 감지를 다시 활성화하고 Obsidian을 재시작하시겠습니까?\n\n> [!DETAILS]-\n> 이러한 설정은 플러그인이 재구성 또는 데이터 가져오기 중에 자동으로 설정한 것입니다. 프로세스가 비정상적으로 종료되면 이 상태가 의도치 않게 유지될 수 있습니다.\n> 상태가 확실하지 않다면 이 과정을 다시 실행해 보세요. 재시작 전에 반드시 볼트를 백업해 주세요.",zh:"Self-hosted LiveSync 已被配置为忽略某些事件。这样对吗?\n\n| 类型 | 状态 | 说明 |\n|:---:|:---:|---|\n| 存储事件 | ${fileWatchingStatus} | 所有修改都将被忽略 |\n| 数据库事件 | ${parseReplicationStatus} | 所有同步的更改都将被推迟 |\n\n您想恢复它们并重启 Obsidian 吗?\n\n> [!DETAILS]-\n> 这些标志是在重建或获取时由插件设置的。如果过程异常结束,它们可能会被无意中保留。\n> 如果您不确定,可以尝试重新运行这些过程。请确保备份您的库。\n"},"moduleLiveSyncMain.optionKeepLiveSyncDisabled":{def:"Keep LiveSync disabled",es:"Mantener LiveSync desactivado",ko:"LiveSync 비활성화 유지",zh:"保持 LiveSync 禁用"},"moduleLiveSyncMain.optionResumeAndRestart":{def:"Resume and restart Obsidian",es:"Reanudar y reiniciar Obsidian",ko:"재개 후 Obsidian 재시작",zh:"恢复并重启 Obsidian"},"moduleLiveSyncMain.titleScramEnabled":{def:"Scram Enabled",es:"Scram habilitado",ko:"Scram 활성화됨",zh:"紧急停止已启用"},"moduleLocalDatabase.logWaitingForReady":{def:"Waiting for ready...",es:"Esperando a que la base de datos esté lista...",ja:"しばらくお待ちください...",ko:"준비 대기 중...",zh:"等待就绪..."},"moduleLog.showLog":{def:"Show Log",es:"Mostrar registro",ko:"로그 표시"},"moduleMigration.docUri":{def:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use",es:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README_ES.md#how-to-use",ko:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use",zh:"https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/zh/README_zh.md#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8"},"moduleMigration.logBulkSendCorrupted":{def:"Send chunks in bulk has been enabled, however, this feature had been corrupted. Sorry for your inconvenience. Automatically disabled.",es:"El envío de fragmentos en bloque se ha habilitado, sin embargo, esta función se ha corrompido. Disculpe las molestias. Deshabilitado automáticamente.",ko:"청크 일괄 전송이 활성화되었지만, 이 기능에 문제가 있었습니다. 불편을 드려 죄송합니다. 자동으로 비활성화되었습니다.",zh:"已启用批量发送 chunks,但此功能已损坏。给您带来不便,我们深表歉意。已自动禁用。"},"moduleMigration.logFetchRemoteTweakFailed":{def:"Failed to fetch remote tweak values",es:"Error al obtener los valores de ajuste remoto",ko:"원격 조정 값을 가져오는데 실패했습니다",zh:"获取远程调整值失败"},"moduleMigration.logLocalDatabaseNotReady":{def:"Something went wrong! The local database is not ready",es:"¡Algo salió mal! La base de datos local no está lista",ko:"문제가 발생했습니다! 로컬 데이터베이스가 준비되지 않았습니다",zh:"出错了!本地数据库尚未准备好"},"moduleMigration.logMigratedSameBehaviour":{def:"Migrated to db:${current} with the same behaviour as before",es:"Migrado a db:${current} con el mismo comportamiento que antes",ko:"이전과 같은 방식으로 동작하도록 db:${current}로 데이터 구조 전환이 완료되었습니다",zh:"已迁移到 db:${current},行为与之前相同"},"moduleMigration.logMigrationFailed":{def:"Migration failed or cancelled from ${old} to ${current}",es:"La migración falló o se canceló de ${old} a ${current}",ko:"${old}에서 ${current}로의 데이터 구조 전환이 실패했거나 중단되었습니다",zh:"从 ${old} 到 ${current} 的迁移失败或已取消"},"moduleMigration.logRedflag2CreationFail":{def:"Failed to create redflag2",es:"Error al crear redflag2",ko:"redflag2 생성에 실패했습니다",zh:"创建 redflag2 失败"},"moduleMigration.logRemoteTweakUnavailable":{def:"Could not get remote tweak values",es:"No se pudieron obtener los valores de ajuste remoto",ko:"원격 조정 값을 가져올 수 없습니다",zh:"无法获取远程调整值"},"moduleMigration.logSetupCancelled":{def:"The setup has been cancelled, Self-hosted LiveSync waiting for your setup!",es:"La configuración ha sido cancelada, ¡Self-hosted LiveSync está esperando tu configuración!",ko:"설정이 취소되었습니다. Self-hosted LiveSync가 설정을 기다리고 있습니다!",zh:"设置已取消,Self-hosted LiveSync 正在等待您的设置!"},"moduleMigration.msgFetchRemoteAgain":{def:"As you may already know, the self-hosted LiveSync has changed its default behaviour and database structure.\n\nAnd thankfully, with your time and efforts, the remote database appears to have already been migrated. Congratulations!\n\nHowever, we need a bit more. The configuration of this device is not compatible with the remote database. We will need to fetch the remote database again. Should we fetch from the remote again now?\n\n___Note: We cannot synchronise until the configuration has been changed and the database has been fetched again.___\n___Note2: The chunks are completely immutable, we can fetch only the metadata and difference.___",es:"Como ya sabrás, Self-hosted LiveSync ha cambiado su comportamiento predeterminado y la estructura de la base de datos.\n\nAfortunadamente, con tu tiempo y esfuerzo, la base de datos remota parece haber sido ya migrada. ¡Felicidades!\n\nSin embargo, necesitamos un poco más. La configuración de este dispositivo no es compatible con la base de datos remota. Necesitaremos volver a obtener la base de datos remota. ¿Debemos obtenerla nuevamente ahora?\n\n___Nota: No podemos sincronizar hasta que la configuración haya sido cambiada y la base de datos haya sido obtenida nuevamente.___\n___Nota2: Los fragmentos son completamente inmutables, solo podemos obtener los metadatos y diferencias.___",ko:"이미 알고 계시겠지만, Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다.\n\n다행히도 여러분의 노력 덕분에 원격 데이터베이스는 이미 성공적으로 데이터 구조 전환이 완료된 것으로 보입니다. 축하드립니다!\n\n하지만 아직 일부 추가 작업이 필요합니다. 이 기기의 설정이 원격 데이터베이스와 호환되지 않으므로, 원격 데이터를 다시 가져와야 합니다. 지금 원격 데이터베이스를 다시 가져오시겠습니까?\n\n___참고: 설정이 변경되고 데이터베이스를 다시 불러오기 전까지는 동기화가 불가능합니다.___\n___참고2: 청크는 변경이 불가능한 구조이므로, 메타데이터와 차이점만 가져올 수 있습니다.___",zh:"您可能已经知道,Self-hosted LiveSync 更改了其默认行为和数据库结构。\n\n值得庆幸的是,在您的时间和努力下,远程数据库似乎已经迁移完成。恭喜!\n\n但是,我们还需要一点点操作。此设备的配置与远程数据库不兼容。我们需要再次从远程数据库获取。我们现在应该再次从远程获取吗?\n\n___注意:在更改配置并再次获取数据库之前,我们无法进行同步。___\n___注意2:chunks 是完全不可变的,我们只能获取元数据和差异。___"},"moduleMigration.msgInitialSetup":{def:"Your device has **not been set up yet**. Let me guide you through the setup process.\n\nPlease keep in mind that every dialogue content can be copied to the clipboard. If you need to refer to it later, you can paste it into a note in Obsidian. You can also translate it into your language using a translation tool.\n\nFirst, do you have **Setup URI**?\n\nNote: If you do not know what it is, please refer to the [documentation](${URI_DOC}).",es:"Tu dispositivo **aún no ha sido configurado**. Permíteme guiarte a través del proceso de configuración.\n\nTen en cuenta que todo el contenido del diálogo se puede copiar al portapapeles. Si necesitas consultarlo más tarde, puedes pegarlo en una nota en Obsidian. También puedes traducirlo a tu idioma utilizando una herramienta de traducción.\n\nPrimero, ¿tienes **URI de configuración**?\n\nNota: Si no sabes qué es, consulta la [documentación](${URI_DOC}).",ko:"이 기기는 **아직 초기 설정이 완료되지 않았습니다**. 지금부터 설정 과정을 안내해 드리겠습니다.\n\n모든 대화 내용은 클립보드에 복사할 수 있습니다. 나중에 참고하려면 Obsidian 노트에 붙여넣거나 번역 도구를 활용해 번역하셔도 됩니다.\n\n먼저, **Setup URI**를 가지고 계신가요?\n\n참고: Setup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요.",zh:"您的设备**尚未设置**。让我引导您完成设置过程。\n\n请记住,每个对话框内容都可以复制到剪贴板。如果以后需要参考,可以将其粘贴到 Obsidian 的笔记中。您也可以使用翻译工具将其翻译成您的语言。\n\n首先,您有**设置 URI** 吗?\n\n注意:如果您不知道这是什么,请参阅[文档](${URI_DOC})。"},"moduleMigration.msgRecommendSetupUri":{def:"We strongly recommend that you generate a set-up URI and use it.\nIf you do not have knowledge about it, please refer to the [documentation](${URI_DOC}) (Sorry again, but it is important).\n\nHow do you want to set it up manually?",es:"Te recomendamos encarecidamente que generes una URI de configuración y la utilices.\nSi no tienes conocimientos al respecto, consulta la [documentación](${URI_DOC}) (Lo siento de nuevo, pero es importante).\n\n¿Cómo quieres configurarlo manualmente?",ko:"Setup URI를 생성해 사용하는 것을 강력히 권장합니다.\nSetup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요. 중요한 내용이니 꼭 확인하시기 바랍니다.\n\n직접 수동 설정을 진행하시겠습니까?",zh:"我们强烈建议您生成一个设置 URI 并使用它。\n如果您对此不了解,请参阅[文档](${URI_DOC})(再次抱歉,但这很重要)。\n\n您想如何手动设置?"},"moduleMigration.msgSinceV02321":{def:"Since v0.23.21, the self-hosted LiveSync has changed the default behaviour and database structure. The following changes have been made:\n\n1. **Case sensitivity of filenames**\n The handling of filenames is now case-insensitive. This is a beneficial change for most platforms, other than Linux and iOS, which do not manage filename case sensitivity effectively.\n (On These, a warning will be displayed for files with the same name but different cases).\n\n2. **Revision handling of the chunks**\n Chunks are immutable, which allows their revisions to be fixed. This change will enhance the performance of file saving.\n\n___However, to enable either of these changes, both remote and local databases need to be rebuilt. This process takes a few minutes, and we recommend doing it when you have ample time.___\n\n- If you wish to maintain the previous behaviour, you can skip this process by using `${KEEP}`.\n- If you do not have enough time, please choose `${DISMISS}`. You will be prompted again later.\n- If you have rebuilt the database on another device, please select `${DISMISS}` and try synchronizing again. Since a difference has been detected, you will be prompted again.",es:"Desde la versión v0.23.21, Self-hosted LiveSync ha cambiado el comportamiento predeterminado y la estructura de la base de datos. Se han realizado los siguientes cambios:\n\n1. **Sensibilidad a mayúsculas de los nombres de archivo**\n El manejo de los nombres de archivo ahora no distingue entre mayúsculas y minúsculas. Este cambio es beneficioso para la mayoría de las plataformas, excepto Linux y iOS, que no gestionan efectivamente la sensibilidad a mayúsculas de los nombres de archivo.\n (En estos, se mostrará una advertencia para archivos con el mismo nombre pero diferentes mayúsculas).\n\n2. **Manejo de revisiones de los fragmentos**\n Los fragmentos son inmutables, lo que permite que sus revisiones sean fijas. Este cambio mejorará el rendimiento al guardar archivos.\n\n___Sin embargo, para habilitar cualquiera de estos cambios, es necesario reconstruir tanto las bases de datos remota como la local. Este proceso toma unos minutos, y recomendamos hacerlo cuando tengas tiempo suficiente.___\n\n- Si deseas mantener el comportamiento anterior, puedes omitir este proceso usando `${KEEP}`.\n- Si no tienes suficiente tiempo, por favor elige `${DISMISS}`. Se te pedirá nuevamente más tarde.\n- Si has reconstruido la base de datos en otro dispositivo, selecciona `${DISMISS}` e intenta sincronizar nuevamente. Dado que se ha detectado una diferencia, se te solicitará nuevamente.",ko:"v0.23.21부터 Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다. 주요 변경사항은 다음과 같습니다:\n\n1. **파일명 대소문자 구분 처리**\n 이제 파일명은 대소문자를 구분하지 않고 처리됩니다. 이는 파일명 구분을 제대로 지원하지 않는 Linux 및 iOS를 제외한 대부분의 플랫폼에서 유리한 변화입니다.\n (Linux나 iOS에서는 대소문자만 다른 파일이 존재할 경우 경고가 표시됩니다)\n\n2. **청크 리비전 관리 방식 개선**\n 청크는 변경 불가능한(immutable) 구조로 고정되며, 이를 통해 리비전 처리가 안정화되고 파일 저장 성능이 향상됩니다.\n\n___단, 위 기능을 활성화하려면 원격 및 로컬 데이터베이스를 모두 재구성해야 합니다. 이 과정은 수 분이 소요되므로 여유가 있을 때 실행하시는 것을 권장합니다.___\n\n- 기존 방식대로 유지하려면 `${KEEP}`을 선택해 이 과정을 건너뛸 수 있습니다.\n- 시간이 부족하다면 `${DISMISS}`를 눌러주시면 나중에 다시 안내드리겠습니다.\n- 이미 다른 기기에서 데이터베이스를 재구성하셨다면 `${DISMISS}`를 선택한 뒤 다시 동기화해 보세요. 차이점이 감지되면 다시 안내드리겠습니다.",zh:"自 v0.23.21 起,Self-hosted LiveSync 更改了默认行为和数据库结构。进行了以下更改:\n\n1. **文件名的区分大小写** \n现在处理文件名时不区分大小写。这对于大多数平台来说是一个有益的更改,除了 Linux 和 iOS,它们不能有效地管理文件名的大小写敏感性。\n(在这些平台上,对于名称相同但大小写不同的文件将显示警告)。\n\n2. **chunks 的版本处理** \nchunks 是不可变的,这使得它们的版本可以固定。此更改将提高文件保存的性能。\n\n___然而,要启用这些更改中的任何一个,都需要重建远程和本地数据库。这个过程需要几分钟,我们建议您在有充足时间时进行。___\n\n- 如果您希望保持以前的行为,可以使用 `${KEEP}` 跳过此过程。\n- 如果您没有足够的时间,请选择 `${DISMISS}`。稍后会再次提示您。\n- 如果您已在另一台设备上重建了数据库,请选择 `${DISMISS}` 并尝试再次同步。由于检测到差异,系统会再次提示您。"},"moduleMigration.optionAdjustRemote":{def:"Adjust to remote",es:"Ajustar al remoto",ko:"원격에 맞추기",zh:"调整到远程设置"},"moduleMigration.optionDecideLater":{def:"Decide it later",es:"Decidirlo más tarde",ko:"나중에 결정하기",zh:"稍后决定"},"moduleMigration.optionEnableBoth":{def:"Enable both",es:"Habilitar ambos",ko:"둘 다 활성화",zh:"启用两者"},"moduleMigration.optionEnableFilenameCaseInsensitive":{def:"Enable only #1",es:"Habilitar solo #1",ko:"#1만 활성화",zh:"仅启用 #1"},"moduleMigration.optionEnableFixedRevisionForChunks":{def:"Enable only #2",es:"Habilitar solo #2",ko:"#2만 활성화",zh:"仅启用 #2"},"moduleMigration.optionHaveSetupUri":{def:"Yes, I have",es:"Sí, tengo",ko:"예, 있습니다",zh:"是的,我有"},"moduleMigration.optionKeepPreviousBehaviour":{def:"Keep previous behaviour",es:"Mantener comportamiento anterior",ko:"이전 동작 유지",zh:"保持以前的行为"},"moduleMigration.optionManualSetup":{def:"Set it up all manually",es:"Configurarlo todo manualmente",ko:"모든 것을 수동으로 설정",zh:"全部手动设置"},"moduleMigration.optionNoAskAgain":{def:"No, please ask again",es:"No, por favor pregúntame de nuevo",ko:"아니요 (나중에 다시 물어보기)",zh:"不,请稍后再次询问"},"moduleMigration.optionNoSetupUri":{def:"No, I do not have",es:"No, no tengo",ko:"아니요, 없습니다",zh:"不,我没有"},"moduleMigration.optionRemindNextLaunch":{def:"Remind me at the next launch",es:"Recordármelo en el próximo inicio",ko:"다음 시작 시 알림",zh:"下次启动时提醒我"},"moduleMigration.optionSetupViaP2P":{def:"Use %{short_p2p_sync} to set up",ko:"%{short_p2p_sync}를 사용하여 설정"},"moduleMigration.optionSetupWizard":{def:"Take me into the setup wizard",es:"Llévame al asistente de configuración",ko:"설정 마법사로 안내",zh:"带我进入设置向导"},"moduleMigration.optionYesFetchAgain":{def:"Yes, fetch again",es:"Sí, obtener nuevamente",ko:"예 (다시 가져오기)",zh:"是的,再次获取"},"moduleMigration.titleCaseSensitivity":{def:"Case Sensitivity",es:"Sensibilidad a mayúsculas",ko:"대소문자 구분",zh:"大小写敏感性"},"moduleMigration.titleRecommendSetupUri":{def:"Recommendation to use Setup URI",es:"Recomendación de uso de URI de configuración",ko:"Setup URI 사용 권장",zh:"推荐使用设置 URI"},"moduleMigration.titleWelcome":{def:"Welcome to Self-hosted LiveSync",es:"Bienvenido a Self-hosted LiveSync",ko:"Self-hosted LiveSync에 오신 것을 환영합니다",zh:"欢迎使用 Self-hosted LiveSync"},"moduleObsidianMenu.replicate":{def:"Replicate",es:"Replicar",ko:"복제"},"Move remotely deleted files to the trash, instead of deleting.":{def:"Move remotely deleted files to the trash, instead of deleting.",es:"Mover archivos borrados remotos a papelera en lugar de eliminarlos",ko:"원격에서 삭제된 파일을 삭제하는 대신 휴지통으로 이동합니다.",zh:"将远程删除的文件移至回收站,而不是直接删除。"},'Not all messages have been translated. And, please revert to "Default" when reporting errors.':{def:'Not all messages have been translated. And, please revert to "Default" when reporting errors.',es:'No todos los mensajes están traducidos. Por favor, vuelva a "Predeterminado" al reportar errores.',ja:'すべてのメッセージが翻訳されているわけではありません。また、Issue報告の際にはいったん"Default"に戻してください',ko:'모든 메시지가 번역되지 않았습니다. 오류 신고 시 "기본값"으로 되돌려 주세요.',zh:'并非所有消息都已翻译。请在报告错误时恢复为"Default"'},"Notify all setting files":{def:"Notify all setting files",es:"Notificar todos los archivos de configuración",ja:"すべての設定を通知",ko:"모든 설정 파일 알림",zh:"通知所有设置文件"},"Notify customized":{def:"Notify customized",es:"Notificar personalizaciones",ja:"カスタマイズが行われたら通知する",ko:"사용자 설정 알림",zh:"通知自定义设置"},"Notify when other device has newly customized.":{def:"Notify when other device has newly customized.",es:"Notificar cuando otro dispositivo personalice",ja:"別の端末がカスタマイズを行なったら通知する",ko:"다른 기기에서 새로운 사용자 설정이 있을 때 알림을 받습니다.",zh:"当其他设备有新的自定义设置时通知。"},"Notify when the estimated remote storage size exceeds on start up":{def:"Notify when the estimated remote storage size exceeds on start up",es:"Notificar cuando el tamaño estimado del almacenamiento remoto exceda al iniciar",ko:"시작 시 예상 원격 스토리지 크기가 초과되면 알림",zh:"启动时当估计的远程存储大小超出时通知"},"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.":{def:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.",es:"Número de lotes a procesar. Default 40, mínimo 2. Controla documentos en memoria",ja:"1度に処理するバッチの数。デフォルトは40、最小は2。この数値は、どれだけの容量の書類がメモリに保存されるかも定義します。",ko:"한 번에 처리할 일괄 처리 수입니다. 기본값은 40입니다. 최소값은 2입니다. 이는 일괄 크기와 함께 메모리에 보관되는 문서 수를 제어합니다.",zh:"一次处理的批量数量。默认为 40。最小为 2。此设置与批量大小一起控制一次在内存中保留多少文档。"},"Number of changes to sync at a time. Defaults to 50. Minimum is 2.":{def:"Number of changes to sync at a time. Defaults to 50. Minimum is 2.",es:"Número de cambios a sincronizar simultáneamente. Default 50, mínimo 2",ko:"한 번에 동기화할 변경 사항의 수입니다. 기본값은 50입니다. 최소값은 2입니다.",zh:"一次同步的更改数量。默认为 50。最小为 2。"},"obsidianLiveSyncSettingTab.btnApply":{def:"Apply",es:"Aplicar",ko:"적용",zh:"应用"},"obsidianLiveSyncSettingTab.btnCheck":{def:"Check",es:"Verificar",ko:"확인",zh:"检查"},"obsidianLiveSyncSettingTab.btnCopy":{def:"Copy",es:"Copiar",ko:"복사",zh:"复制"},"obsidianLiveSyncSettingTab.btnDisable":{def:"Disable",es:"Desactivar",ko:"비활성화",zh:"禁用"},"obsidianLiveSyncSettingTab.btnDiscard":{def:"Discard",es:"Descartar",ko:"삭제",zh:"丢弃"},"obsidianLiveSyncSettingTab.btnEnable":{def:"Enable",es:"Activar",ko:"활성화",zh:"启用"},"obsidianLiveSyncSettingTab.btnFix":{def:"Fix",es:"Corregir",ko:"수정",zh:"修复"},"obsidianLiveSyncSettingTab.btnGotItAndUpdated":{def:"I got it and updated.",es:"Lo entendí y actualicé.",ko:"알겠습니다. 업데이트했습니다.",zh:"我明白了并且已更新。"},"obsidianLiveSyncSettingTab.btnNext":{def:"Next",es:"Siguiente",ko:"다음",zh:"下一步"},"obsidianLiveSyncSettingTab.btnStart":{def:"Start",es:"Iniciar",ko:"시작",zh:"开始"},"obsidianLiveSyncSettingTab.btnTest":{def:"Test",es:"Probar",ko:"테스트",zh:"测试"},"obsidianLiveSyncSettingTab.btnUse":{def:"Use",es:"Usar",ko:"사용",zh:"使用"},"obsidianLiveSyncSettingTab.buttonFetch":{def:"Fetch",es:"Obtener",ko:"가져오기",zh:"获取"},"obsidianLiveSyncSettingTab.buttonNext":{def:"Next",es:"Siguiente",ko:"다음",zh:"下一步"},"obsidianLiveSyncSettingTab.defaultLanguage":{def:"Default",es:"Predeterminado",ko:"기본값",zh:"默认"},"obsidianLiveSyncSettingTab.descConnectSetupURI":{def:"This is the recommended method to set up Self-hosted LiveSync with a Setup URI.",es:"Este es el método recomendado para configurar Self-hosted LiveSync con una URI de configuración.",ko:"이것은 Setup URI로 Self-hosted LiveSync를 설정하는 권장 방법입니다.",zh:"这是使用设置 URI 设置 Self-hosted LiveSync 的推荐方法。"},"obsidianLiveSyncSettingTab.descCopySetupURI":{def:"Perfect for setting up a new device!",es:"¡Perfecto para configurar un nuevo dispositivo!",ko:"새 기기 설정에 완벽합니다!",zh:"非常适合设置新设备!"},"obsidianLiveSyncSettingTab.descEnableLiveSync":{def:"Only enable this after configuring either of the above two options or completing all configuration manually.",es:"Solo habilita esto después de configurar cualquiera de las dos opciones anteriores o completar toda la configuración manualmente.",ko:"위의 두 옵션 중 하나를 구성하거나 모든 구성을 수동으로 완료한 후에만 활성화하세요.",zh:"仅在配置了上述两个选项之一或手动完成所有配置后启用此选项。"},"obsidianLiveSyncSettingTab.descFetchConfigFromRemote":{def:"Fetch necessary settings from already configured remote server.",es:"Obtener las configuraciones necesarias del servidor remoto ya configurado.",ko:"이미 구성된 원격 서버에서 필요한 설정을 가져옵니다.",zh:"从已配置的远程服务器获取必要的设置。"},"obsidianLiveSyncSettingTab.descManualSetup":{def:"Not recommended, but useful if you don't have a Setup URI",es:"No recomendado, pero útil si no tienes una URI de configuración",ko:"권장하지 않지만 Setup URI가 없는 경우에 유용합니다",zh:"不推荐,但如果您没有设置 URI 则很有用"},"obsidianLiveSyncSettingTab.descTestDatabaseConnection":{def:"Open database connection. If the remote database is not found and you have permission to create a database, the database will be created.",es:"Abrir conexión a la base de datos. Si no se encuentra la base de datos remota y tienes permiso para crear una base de datos, se creará la base de datos.",ko:"데이터베이스 연결을 엽니다. 원격 데이터베이스를 찾을 수 없고 데이터베이스 생성 권한이 있는 경우, 데이터베이스가 생성됩니다.",zh:"打开数据库连接。如果未找到远程数据库并且您有创建数据库的权限,则将创建数据库。"},"obsidianLiveSyncSettingTab.descValidateDatabaseConfig":{def:"Checks and fixes any potential issues with the database config.",es:"Verifica y soluciona cualquier problema potencial con la configuración de la base de datos.",ko:"데이터베이스 구성의 잠재적 문제를 확인하고 수정합니다.",zh:"检查并修复数据库配置中的任何潜在问题。"},"obsidianLiveSyncSettingTab.errAccessForbidden":{def:"❗ Access forbidden.",es:"Acceso prohibido.",ko:"❗ 액세스가 금지되었습니다.",zh:"❗ 访问被禁止。"},"obsidianLiveSyncSettingTab.errCannotContinueTest":{def:"We could not continue the test.",es:"No se pudo continuar con la prueba.",ko:"테스트를 계속할 수 없습니다.",zh:"我们无法继续测试。"},"obsidianLiveSyncSettingTab.errCorsCredentials":{def:"❗ cors.credentials is wrong",es:"❗ cors.credentials es incorrecto",ko:"❗ cors.credentials가 잘못되었습니다",zh:"❗ cors.credentials 设置错误"},"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials":{def:"❗ CORS is not allowing credentials",es:"CORS no permite credenciales",ko:"❗ CORS에서 자격 증명을 허용하지 않습니다",zh:"❗ CORS 不允许凭据"},"obsidianLiveSyncSettingTab.errCorsOrigins":{def:"❗ cors.origins is wrong",es:"❗ cors.origins es incorrecto",ko:"❗ cors.origins가 잘못되었습니다",zh:"❗ cors.origins 设置错误"},"obsidianLiveSyncSettingTab.errEnableCors":{def:"❗ httpd.enable_cors is wrong",es:"❗ httpd.enable_cors es incorrecto",ko:"❗ httpd.enable_cors가 잘못되었습니다",zh:"❗ httpd.enable_cors 设置错误"},"obsidianLiveSyncSettingTab.errMaxDocumentSize":{def:"❗ couchdb.max_document_size is low)",es:"❗ couchdb.max_document_size es bajo)",ko:"❗ couchdb.max_document_size가 낮습니다)",zh:"❗ couchdb.max_document_size 设置过低)"},"obsidianLiveSyncSettingTab.errMaxRequestSize":{def:"❗ chttpd.max_http_request_size is low)",es:"❗ chttpd.max_http_request_size es bajo)",ko:"❗ chttpd.max_http_request_size가 낮습니다)",zh:"❗ chttpd.max_http_request_size 设置过低)"},"obsidianLiveSyncSettingTab.errMissingWwwAuth":{def:"❗ httpd.WWW-Authenticate is missing",es:"❗ httpd.WWW-Authenticate falta",ko:"❗ httpd.WWW-Authenticate가 누락되었습니다",zh:"❗ 缺少 httpd.WWW-Authenticate 设置"},"obsidianLiveSyncSettingTab.errRequireValidUser":{def:"❗ chttpd.require_valid_user is wrong.",es:"❗ chttpd.require_valid_user es incorrecto.",ko:"❗ chttpd.require_valid_user가 잘못되었습니다.",zh:"❗ chttpd.require_valid_user 设置错误。"},"obsidianLiveSyncSettingTab.errRequireValidUserAuth":{def:"❗ chttpd_auth.require_valid_user is wrong.",es:"❗ chttpd_auth.require_valid_user es incorrecto.",ko:"❗ chttpd_auth.require_valid_user가 잘못되었습니다.",zh:"❗ chttpd_auth.require_valid_user 设置错误。"},"obsidianLiveSyncSettingTab.labelDisabled":{def:"⏹️ : Disabled",es:"⏹️ : Desactivado",ko:"⏹️ : 비활성화됨",zh:"⏹️ : 已禁用"},"obsidianLiveSyncSettingTab.labelEnabled":{def:"🔁 : Enabled",es:"🔁 : Activado",ko:"🔁 : 활성화됨",zh:"🔁 : 已启用"},"obsidianLiveSyncSettingTab.levelAdvanced":{def:" (Advanced)",es:" (avanzado)",ko:" (고급)",zh:"(进阶)"},"obsidianLiveSyncSettingTab.levelEdgeCase":{def:" (Edge Case)",es:" (excepción)",ko:" (특수 사례)",zh:"(边缘情况)"},"obsidianLiveSyncSettingTab.levelPowerUser":{def:" (Power User)",es:" (experto)",ko:" (파워 유저)",zh:"(高级用户)"},"obsidianLiveSyncSettingTab.linkOpenInBrowser":{def:"Open in browser",es:"Abrir en el navegador",ko:"브라우저에서 열기",zh:"在浏览器中打开"},"obsidianLiveSyncSettingTab.linkPageTop":{def:"Page Top",es:"Ir arriba",ko:"페이지 상단",zh:"页面顶部"},"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting":{def:"Tips and Troubleshooting",es:"Consejos y solución de problemas",ko:"팁 및 문제 해결",zh:"提示和故障排除"},"obsidianLiveSyncSettingTab.linkTroubleshooting":{def:"/docs/troubleshooting.md",es:"/docs/es/troubleshooting.md",ko:"/docs/troubleshooting.md",zh:"/docs/troubleshooting.md"},"obsidianLiveSyncSettingTab.logCannotUseCloudant":{def:"This feature cannot be used with IBM Cloudant.",es:"Esta función no se puede utilizar con IBM Cloudant.",ko:"이 기능은 IBM Cloudant와 함께 사용할 수 없습니다.",zh:"此功能不能与 IBM Cloudant 一起使用。"},"obsidianLiveSyncSettingTab.logCheckingConfigDone":{def:"Checking configuration done",es:"Verificación de configuración completada",ko:"구성 확인 완료",zh:"配置检查完成"},"obsidianLiveSyncSettingTab.logCheckingConfigFailed":{def:"Checking configuration failed",es:"La verificación de configuración falló",ko:"구성 확인 실패",zh:"配置检查失败"},"obsidianLiveSyncSettingTab.logCheckingDbConfig":{def:"Checking database configuration",es:"Verificando la configuración de la base de datos",ko:"데이터베이스 구성 확인 중",zh:"正在检查数据库配置"},"obsidianLiveSyncSettingTab.logCheckPassphraseFailed":{def:"ERROR: Failed to check passphrase with the remote server:\n${db}.",es:"ERROR: Error al comprobar la frase de contraseña con el servidor remoto: \n${db}.",ko:"오류: 원격 서버와 패스프레이즈 확인에 실패했습니다: \n${db}.",zh:"错误:无法使用远程服务器检查密码:\n${db}。"},"obsidianLiveSyncSettingTab.logConfiguredDisabled":{def:"Configured synchronization mode: DISABLED",es:"Modo de sincronización configurado: DESACTIVADO",ko:"구성된 동기화 모드: 비활성화됨",zh:"配置的同步模式:已禁用"},"obsidianLiveSyncSettingTab.logConfiguredLiveSync":{def:"Configured synchronization mode: LiveSync",es:"Modo de sincronización configurado: Sincronización en Vivo",ko:"구성된 동기화 모드: LiveSync",zh:"配置的同步模式:LiveSync"},"obsidianLiveSyncSettingTab.logConfiguredPeriodic":{def:"Configured synchronization mode: Periodic",es:"Modo de sincronización configurado: Periódico",ko:"구성된 동기화 모드: 주기적",zh:"配置的同步模式:定期"},"obsidianLiveSyncSettingTab.logCouchDbConfigFail":{def:"CouchDB Configuration: ${title} failed",es:"Configuración de CouchDB: ${title} falló",ko:"CouchDB 구성: ${title} 실패",zh:"CouchDB 配置:${title} 失败"},"obsidianLiveSyncSettingTab.logCouchDbConfigSet":{def:"CouchDB Configuration: ${title} -> Set ${key} to ${value}",es:"Configuración de CouchDB: ${title} -> Establecer ${key} en ${value}",ko:"CouchDB 구성: ${title} -> ${key}를 ${value}로 설정",zh:"CouchDB 配置:${title} -> 设置 ${key} 为 ${value}"},"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated":{def:"CouchDB Configuration: ${title} successfully updated",es:"Configuración de CouchDB: ${title} actualizado correctamente",ko:"CouchDB 구성: ${title} 성공적으로 업데이트됨",zh:"CouchDB 配置:${title} 成功更新"},"obsidianLiveSyncSettingTab.logDatabaseConnected":{def:"Database connected",es:"Base de datos conectada",ko:"데이터베이스 연결됨",zh:"数据库已连接"},"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase":{def:"You cannot enable encryption without a passphrase",es:"No puedes habilitar el cifrado sin una frase de contraseña",ko:"패스프레이즈 없이는 암호화를 활성화할 수 없습니다",zh:"没有密码无法启用加密"},"obsidianLiveSyncSettingTab.logEncryptionNoSupport":{def:"Your device does not support encryption.",es:"Tu dispositivo no admite el cifrado.",ko:"기기가 암호화를 지원하지 않습니다.",zh:"您的设备不支持加密。"},"obsidianLiveSyncSettingTab.logErrorOccurred":{def:"An error occurred!!",es:"¡Ocurrió un error!",ko:"오류가 발생했습니다!",zh:"发生错误!!"},"obsidianLiveSyncSettingTab.logEstimatedSize":{def:"Estimated size: ${size}",es:"Tamaño estimado: ${size}",ko:"예상 크기: ${size}",zh:"估计大小:${size}"},"obsidianLiveSyncSettingTab.logPassphraseInvalid":{def:"Passphrase is not valid, please fix it.",es:"La frase de contraseña no es válida, por favor corrígela.",ko:"패스프레이즈가 유효하지 않습니다. 수정해 주세요.",zh:"密码无效,请修正。"},"obsidianLiveSyncSettingTab.logPassphraseNotCompatible":{def:"ERROR: Passphrase is not compatible with the remote server! Please check it again!",es:"ERROR: ¡La frase de contraseña no es compatible con el servidor remoto! ¡Por favor, revísala de nuevo!",ko:"오류: 패스프레이즈가 원격 서버와 호환되지 않습니다! 다시 확인해 주세요!",zh:"错误:密码与远程服务器不兼容!请再次检查!"},"obsidianLiveSyncSettingTab.logRebuildNote":{def:"Syncing has been disabled, fetch and re-enabled if desired.",es:"La sincronización ha sido desactivada, obtén y vuelve a activar si lo deseas.",ko:"동기화가 비활성화되었습니다. 원하는 경우 가져오기 후 다시 활성화하세요.",zh:"同步已禁用,如果需要,请获取并重新启用。"},"obsidianLiveSyncSettingTab.logSelectAnyPreset":{def:"Select any preset.",es:"Selecciona cualquier preestablecido.",ko:"프리셋을 선택하세요.",zh:"选择任何预设。"},"obsidianLiveSyncSettingTab.msgAreYouSureProceed":{def:"Are you sure to proceed?",es:"¿Estás seguro de proceder?",ko:"정말로 진행하시겠습니까?",zh:"您确定要继续吗?"},"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied":{def:"Changes need to be applied!",es:"¡Los cambios deben aplicarse!",ko:"변경사항을 적용해야 합니다!",zh:"需要应用更改!"},"obsidianLiveSyncSettingTab.msgConfigCheck":{def:"--Config check--",es:"--Verificación de configuración--",ko:"--구성 확인--",zh:"--配置检查--"},"obsidianLiveSyncSettingTab.msgConfigCheckFailed":{def:"The configuration check has failed. Do you want to continue anyway?",es:"La verificación de configuración ha fallado. ¿Quieres continuar de todos modos?",ko:"구성 확인에 실패했습니다. 그래도 계속하시겠습니까?",zh:"配置检查失败。您仍要继续吗?"},"obsidianLiveSyncSettingTab.msgConnectionCheck":{def:"--Connection check--",es:"--Verificación de conexión--",ko:"--연결 확인--",zh:"--连接检查--"},"obsidianLiveSyncSettingTab.msgConnectionProxyNote":{def:"If you're having trouble with the Connection-check (even after checking config), please check your reverse proxy configuration.",es:"Si tienes problemas con la verificación de conexión (incluso después de verificar la configuración), por favor verifica la configuración de tu proxy reverso.",ko:"구성 확인 후에도 연결 확인에 문제가 있는 경우, 리버스 프록시 구성을 확인해 주세요.",zh:"如果您在连接检查时遇到问题(即使检查了配置后),请检查您的反向代理配置。"},"obsidianLiveSyncSettingTab.msgCurrentOrigin":{def:"Current origin: {origin}",es:"Origen actual: {origin}",ko:"현재 원점: {origin}",zh:"当前源: {origin}"},"obsidianLiveSyncSettingTab.msgDiscardConfirmation":{def:"Do you really want to discard existing settings and databases?",es:"¿Realmente deseas descartar las configuraciones y bases de datos existentes?",ko:"정말로 기존 설정과 데이터베이스를 삭제하시겠습니까?",zh:"您真的要丢弃现有的设置和数据库吗?"},"obsidianLiveSyncSettingTab.msgDone":{def:"--Done--",es:"--Hecho--",ko:"--완료--",zh:"--完成--"},"obsidianLiveSyncSettingTab.msgEnableCors":{def:"Set httpd.enable_cors",es:"Configurar httpd.enable_cors",ko:"httpd.enable_cors 설정",zh:"设置 httpd.enable_cors"},"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation":{def:"We recommend enabling End-To-End Encryption, and Path Obfuscation. Are you sure you want to continue without encryption?",es:"Recomendamos habilitar el cifrado de extremo a extremo y la obfuscación de ruta. ¿Estás seguro de querer continuar sin cifrado?",ko:"종단간 암호화와 경로 난독화를 활성화하는 것을 권장합니다. 정말로 암호화 없이 계속하시겠습니까?",zh:"我们建议启用端到端加密和路径混淆。您确定要在没有加密的情况下继续吗?"},"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote":{def:"Do you want to fetch the config from the remote server?",es:"¿Quieres obtener la configuración del servidor remoto?",ko:"원격 서버에서 구성을 가져오시겠습니까?",zh:"您想从远程服务器获取配置吗?"},"obsidianLiveSyncSettingTab.msgGenerateSetupURI":{def:"All done! Do you want to generate a setup URI to set up other devices?",es:"¡Todo listo! ¿Quieres generar un URI de configuración para configurar otros dispositivos?",ko:"모든 작업이 완료되었습니다! 다른 기기를 설정하기 위해 Setup URI를 생성하시겠습니까?",zh:"全部完成!您想生成一个设置 URI 来设置其他设备吗?"},"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent":{def:"If the server configuration is not persistent (e.g., running on docker), the values here may change. Once you are able to connect, please update the settings in the server's local.ini.",es:"Si la configuración del servidor no es persistente (por ejemplo, ejecutándose en docker), los valores aquí pueden cambiar. Una vez que puedas conectarte, por favor actualiza las configuraciones en el local.ini del servidor.",ko:"서버 설정이 영구적으로 저장되지 않는 환경(예: Docker에서 실행 중)에서는 이곳의 값들이 변경될 수 있습니다. 연결이 가능해지면 서버의 local.ini 파일에서 설정을 수동으로 업데이트해 주세요.",zh:"如果服务器配置不是持久的(例如,在 docker 上运行),此处的值可能会更改。一旦能够连接,请更新服务器 local.ini 中的设置。"},"obsidianLiveSyncSettingTab.msgInvalidPassphrase":{def:"Your encryption passphrase might be invalid. Are you sure you want to continue?",es:"Tu frase de contraseña de cifrado podría ser inválida. ¿Estás seguro de querer continuar?",ko:"암호화 패스프레이즈가 유효하지 않을 수 있습니다. 정말로 계속하시겠습니까?",zh:"您的加密密码可能无效。您确定要继续吗?"},"obsidianLiveSyncSettingTab.msgNewVersionNote":{def:"Here due to an upgrade notification? Please review the version history. If you're satisfied, click the button. A new update will prompt this again.",es:"¿Aquí debido a una notificación de actualización? Por favor, revise el historial de versiones. Si está satisfecho, haga clic en el botón. Una nueva actualización volverá a mostrar esto.",ko:"업그레이드 알림으로 여기에 오셨나요? 버전 기록을 검토해 주세요. 만족하신다면 버튼을 클릭하세요. 새로운 업데이트 시 다시 안내됩니다.",zh:"因为升级通知来到这里?请查看版本历史。如果您满意,请点击按钮。新的更新将再次提示此信息。"},"obsidianLiveSyncSettingTab.msgNonHTTPSInfo":{def:"Configured as non-HTTPS URI. Be warned that this may not work on mobile devices.",es:"Configurado como URI que no es HTTPS. Ten en cuenta que esto puede no funcionar en dispositivos móviles.",ko:"비 HTTPS URI로 구성되었습니다. 모바일 기기에서는 작동하지 않을 수 있으니 주의하세요.",zh:"配置为非 HTTPS URI。请注意,这可能在移动设备上无法工作。"},"obsidianLiveSyncSettingTab.msgNonHTTPSWarning":{def:"Cannot connect to non-HTTPS URI. Please update your config and try again.",es:"No se puede conectar a URI que no sean HTTPS. Por favor, actualiza tu configuración y vuelve a intentarlo.",ko:"비 HTTPS URI에 연결할 수 없습니다. 구성을 업데이트하고 다시 시도해 주세요.",zh:"无法连接到非 HTTPS URI。请更新您的配置并重试。"},"obsidianLiveSyncSettingTab.msgNotice":{def:"---Notice---",es:"---Aviso---",ko:"---공지사항---",zh:"---注意---"},"obsidianLiveSyncSettingTab.msgObjectStorageWarning":{def:"WARNING: This feature is a Work In Progress, so please keep in mind the following:\n- Append only architecture. A rebuild is required to shrink the storage.\n- A bit fragile.\n- When first syncing, all history will be transferred from the remote. Be mindful of data caps and slow speeds.\n- Only differences are synced live.\n\nIf you run into any issues, or have ideas about this feature, please create a issue on GitHub.\nI appreciate you for your great dedication.",es:"ADVERTENCIA: Esta característica está en desarrollo, así que por favor ten en cuenta lo siguiente:\n- Arquitectura de solo anexado. Se requiere una reconstrucción para reducir el almacenamiento.\n- Un poco frágil.\n- Al sincronizar por primera vez, todo el historial será transferido desde el remoto. Ten en cuenta los límites de datos y las velocidades lentas.\n- Solo las diferencias se sincronizan en vivo.\n\nSi encuentras algún problema o tienes ideas sobre esta característica, por favor crea un issue en GitHub.\nAprecio mucho tu gran dedicación.",ko:"⚠️ 주의: 이 기능은 아직 개발 중(WIP)입니다. 다음 사항을 유의해 주세요:\n- 추가 전용 구조(append-only)로 동작합니다. 저장 용량을 줄이려면 데이터 재구성이 필요합니다.\n- 기능이 다소 불안정할 수 있습니다.\n- 최초 동기화 시, 전체 히스토리가 원격 서버에서 전송됩니다. 데이터 용량 제한 및 느린 속도에 유의해 주세요.\n- 실시간 동기화는 변경된 부분만 처리됩니다.\n\n문제가 발생했거나 개선 아이디어가 있으시면 GitHub에 이슈를 등록해 주세요.\n기여에 깊이 감사드립니다.",zh:"警告:此功能仍在开发中,请注意以下几点:\n- 仅追加架构。需要重建才能缩小存储空间。\n- 有点脆弱。\n- 首次同步时,所有历史记录将从远程传输。注意数据上限和慢速。\n- 只有差异会实时同步。\n\n如果您遇到任何问题,或对此功能有任何想法,请在 GitHub 上创建 issue。\n感谢您的巨大贡献。"},"obsidianLiveSyncSettingTab.msgOriginCheck":{def:"Origin check: {org}",es:"Verificación de origen: {org}",ko:"원점 확인: {org}",zh:"源检查: {org}"},"obsidianLiveSyncSettingTab.msgRebuildRequired":{def:"Rebuilding Databases are required to apply the changes.. Please select the method to apply the changes.\n\n
\nLegends\n\n| Symbol | Meaning |\n|: ------ :| ------- |\n| ⇔ | Up to Date |\n| ⇄ | Synchronise to balance |\n| ⇐,⇒ | Transfer to overwrite |\n| ⇠,⇢ | Transfer to overwrite from other side |\n\n
\n\n## ${OPTION_REBUILD_BOTH}\nAt a glance: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruct both the local and remote databases using existing files from this device.\nThis causes a lockout other devices, and they need to perform fetching.\n## ${OPTION_FETCH}\nAt a glance: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInitialise the local database and reconstruct it using data fetched from the remote database.\nThis case includes the case which you have rebuilt the remote database.\n## ${OPTION_ONLY_SETTING}\nStore only the settings. **Caution: This may lead to data corruption**; database reconstruction is generally necessary.",es:"Es necesario reconstruir las bases de datos para aplicar los cambios. Por favor selecciona el método para aplicar los cambios.\n\n
\nLegendas\n\n| Símbolo | Significado |\n|: ------ :| ------- |\n| ⇔ | Actualizado |\n| ⇄ | Sincronizar para equilibrar |\n| ⇐,⇒ | Transferir para sobrescribir |\n| ⇠,⇢ | Transferir para sobrescribir desde otro lado |\n\n
\n\n## ${OPTION_REBUILD_BOTH}\nA simple vista: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruir tanto la base de datos local como la remota utilizando los archivos existentes de este dispositivo.\nEsto bloquea a otros dispositivos, y necesitan realizar la obtención.\n## ${OPTION_FETCH}\nA simple vista: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInicializa la base de datos local y la reconstruye utilizando los datos obtenidos de la base de datos remota.\nEste caso incluye el caso en el que has reconstruido la base de datos remota.\n## ${OPTION_ONLY_SETTING}\nAlmacena solo la configuración. **Precaución: esto puede provocar corrupción de datos**; generalmente es necesario reconstruir la base de datos.",ko:"변경사항을 적용하려면 데이터베이스를 재구축해야 합니다. 아래 중 한 가지 방법을 선택해 주세요.\n\n
\n범례\n\n| 기호 | 의미 |\n|: ------ :| ------- |\n| ⇔ | 최신 상태 |\n| ⇄ | 동기화 균형 유지 |\n| ⇐,⇒ | 덮어쓰기 방식의 전송 |\n| ⇠,⇢ | 상대편에서 가져와 덮어쓰기 |\n\n
\n\n## ${OPTION_REBUILD_BOTH}\n개요: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n이 기기의 기존 파일을 기반으로 로컬과 원격 데이터베이스를 모두 재구축합니다.\n이 과정에서 다른 기기는 일시적으로 접근이 제한되며, 가져오기 작업을 별도로 수행해야 합니다.\n\n## ${OPTION_FETCH}\n개요: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n로컬 데이터베이스를 초기화한 후, 원격 데이터베이스에서 데이터를 가져와 재구축합니다.\n이는 원격 측에서 데이터베이스를 먼저 재구축한 경우에도 해당됩니다.\n\n## ${OPTION_ONLY_SETTING}\n설정만 저장합니다. **⚠️ 주의: 이 방법은 데이터 손상을 일으킬 수 있습니다.** 일반적으로는 전체 데이터베이스 재구축이 필요합니다.",zh:"需要重建数据库以应用更改。请选择应用更改的方法。\n\n
\n图例\n\n| 符号 | 含义 |\n|: ------ :| ------- |\n| ⇔ | 最新 |\n| ⇄ | 同步以平衡 |\n| ⇐,⇒ | 传输以覆盖 |\n| ⇠,⇢ | 从另一侧传输以覆盖 |\n\n
\n\n## ${OPTION_REBUILD_BOTH}\n概览:📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n使用此设备的现有文件重建本地和远程数据库。\n这将导致其他设备被锁定,并且它们需要执行获取操作。\n## ${OPTION_FETCH}\n概览:📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n初始化本地数据库并使用从远程数据库获取的数据重建它。\n这种情况包括您已经重建了远程数据库的情况。\n## ${OPTION_ONLY_SETTING}\n仅存储设置。**注意:这可能导致数据损坏**;通常需要重建数据库。"},"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset":{def:"Please select and apply any preset item to complete the wizard.",es:"Por favor, selecciona y aplica cualquier elemento preestablecido para completar el asistente.",ko:"마법사를 완료하려면 프리셋 항목을 선택하고 적용해 주세요.",zh:"请选择并应用任何预设项以完成向导。"},"obsidianLiveSyncSettingTab.msgSetCorsCredentials":{def:"Set cors.credentials",es:"Configurar cors.credentials",ko:"cors.credentials 설정",zh:"设置 cors.credentials"},"obsidianLiveSyncSettingTab.msgSetCorsOrigins":{def:"Set cors.origins",es:"Configurar cors.origins",ko:"cors.origins 설정",zh:"设置 cors.origins"},"obsidianLiveSyncSettingTab.msgSetMaxDocSize":{def:"Set couchdb.max_document_size",es:"Configurar couchdb.max_document_size",ko:"couchdb.max_document_size 설정",zh:"设置 couchdb.max_document_size"},"obsidianLiveSyncSettingTab.msgSetMaxRequestSize":{def:"Set chttpd.max_http_request_size",es:"Configurar chttpd.max_http_request_size",ko:"chttpd.max_http_request_size 설정",zh:"设置 chttpd.max_http_request_size"},"obsidianLiveSyncSettingTab.msgSetRequireValidUser":{def:"Set chttpd.require_valid_user = true",es:"Configurar chttpd.require_valid_user = true",ko:"chttpd.require_valid_user = true로 설정",zh:"设置 chttpd.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth":{def:"Set chttpd_auth.require_valid_user = true",es:"Configurar chttpd_auth.require_valid_user = true",ko:"chttpd_auth.require_valid_user = true로 설정",zh:"设置 chttpd_auth.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSettingModified":{def:'The setting "${setting}" was modified from another device. Click {HERE} to reload settings. Click elsewhere to ignore changes.',es:'La configuración "${setting}" fue modificada desde otro dispositivo. Haz clic {HERE} para recargar la configuración. Haz clic en otro lugar para ignorar los cambios.',ko:'"${setting}" 설정이 다른 기기에서 수정되었습니다. 설정을 다시 로드하려면 {HERE}를 클릭하세요. 변경사항을 무시하려면 다른 곳을 클릭하세요.',zh:'设置 "${setting}" 已从另一台设备修改。点击 {HERE} 重新加载设置。点击其他地方忽略更改。'},"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync":{def:'These settings are unable to be changed during synchronization. Please disable all syncing in the "Sync Settings" to unlock.',es:'Estas configuraciones no se pueden cambiar durante la sincronización. Por favor, deshabilita toda la sincronización en las "Configuraciones de Sincronización" para desbloquear.',ko:'동기화 중에는 이 설정들을 변경할 수 없습니다. 잠금을 해제하려면 "동기화 설정"에서 모든 동기화를 비활성화해 주세요.',zh:"这些设置在同步期间无法更改。请在“同步设置”中禁用所有同步以解锁。"},"obsidianLiveSyncSettingTab.msgSetWwwAuth":{def:"Set httpd.WWW-Authenticate",es:"Configurar httpd.WWW-Authenticate",ko:"httpd.WWW-Authenticate 설정",zh:"设置 httpd.WWW-Authenticate"},"obsidianLiveSyncSettingTab.nameApplySettings":{def:"Apply Settings",es:"Aplicar configuraciones",ko:"설정 적용",zh:"应用设置"},"obsidianLiveSyncSettingTab.nameConnectSetupURI":{def:"Connect with Setup URI",es:"Conectar con URI de configuración",ko:"Setup URI로 연결",zh:"使用设置 URI 连接"},"obsidianLiveSyncSettingTab.nameCopySetupURI":{def:"Copy the current settings to a Setup URI",es:"Copiar la configuración actual a una URI de configuración",ko:"현재 설정을 Setup URI로 복사",zh:"将当前设置复制为设置 URI"},"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync":{def:"Disable Hidden files sync",es:"Desactivar sincronización de archivos ocultos",ko:"숨김 파일 동기화 비활성화",zh:"禁用隐藏文件同步"},"obsidianLiveSyncSettingTab.nameDiscardSettings":{def:"Discard existing settings and databases",es:"Descartar configuraciones y bases de datos existentes",ko:"기존 설정 및 데이터베이스 삭제",zh:"丢弃现有设置和数据库"},"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync":{def:"Enable Hidden files sync",es:"Activar sincronización de archivos ocultos",ko:"숨김 파일 동기화 활성화",zh:"启用隐藏文件同步"},"obsidianLiveSyncSettingTab.nameEnableLiveSync":{def:"Enable LiveSync",es:"Activar LiveSync",ko:"LiveSync 활성화",zh:"启用 LiveSync"},"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization":{def:"Hidden file synchronization",es:"Sincronización de archivos ocultos",ko:"숨김 파일 동기화",zh:"隐藏文件同步"},"obsidianLiveSyncSettingTab.nameManualSetup":{def:"Manual Setup",es:"Configuración manual",ko:"수동 설정",zh:"手动设置"},"obsidianLiveSyncSettingTab.nameTestConnection":{def:"Test Connection",es:"Probar conexión",ko:"연결 테스트",zh:"测试连接"},"obsidianLiveSyncSettingTab.nameTestDatabaseConnection":{def:"Test Database Connection",es:"Probar Conexión de Base de Datos",ko:"데이터베이스 연결 테스트",zh:"测试数据库连接"},"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig":{def:"Validate Database Configuration",es:"Validar Configuración de la Base de Datos",ko:"데이터베이스 구성 검증",zh:"验证数据库配置"},"obsidianLiveSyncSettingTab.okAdminPrivileges":{def:"✔ You have administrator privileges.",es:"✔ Tienes privilegios de administrador.",ko:"✔ 관리자 권한이 있습니다.",zh:"✔ 您拥有管理员权限。"},"obsidianLiveSyncSettingTab.okCorsCredentials":{def:"✔ cors.credentials is ok.",es:"✔ cors.credentials está correcto.",ko:"✔ cors.credentials가 정상입니다.",zh:"✔ cors.credentials 设置正确。"},"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin":{def:"CORS credentials OK",es:"CORS credenciales OK",ko:"CORS 자격 증명 정상",zh:"CORS 凭据正常"},"obsidianLiveSyncSettingTab.okCorsOriginMatched":{def:"✔ CORS origin OK",es:"✔ Origen de CORS correcto",ko:"✔ CORS 원점 정상",zh:"✔ CORS 源正常"},"obsidianLiveSyncSettingTab.okCorsOrigins":{def:"✔ cors.origins is ok.",es:"✔ cors.origins está correcto.",ko:"✔ cors.origins가 정상입니다.",zh:"✔ cors.origins 设置正确。"},"obsidianLiveSyncSettingTab.okEnableCors":{def:"✔ httpd.enable_cors is ok.",es:"✔ httpd.enable_cors está correcto.",ko:"✔ httpd.enable_cors가 정상입니다.",zh:"✔ httpd.enable_cors 设置正确。"},"obsidianLiveSyncSettingTab.okMaxDocumentSize":{def:"✔ couchdb.max_document_size is ok.",es:"✔ couchdb.max_document_size está correcto.",ko:"✔ couchdb.max_document_size가 정상입니다.",zh:"✔ couchdb.max_document_size 设置正确。"},"obsidianLiveSyncSettingTab.okMaxRequestSize":{def:"✔ chttpd.max_http_request_size is ok.",es:"✔ chttpd.max_http_request_size está correcto.",ko:"✔ chttpd.max_http_request_size가 정상입니다.",zh:"✔ chttpd.max_http_request_size 设置正确。"},"obsidianLiveSyncSettingTab.okRequireValidUser":{def:"✔ chttpd.require_valid_user is ok.",es:"✔ chttpd.require_valid_user está correcto.",ko:"✔ chttpd.require_valid_user가 정상입니다.",zh:"✔ chttpd.require_valid_user 设置正确。"},"obsidianLiveSyncSettingTab.okRequireValidUserAuth":{def:"✔ chttpd_auth.require_valid_user is ok.",es:"✔ chttpd_auth.require_valid_user está correcto.",ko:"✔ chttpd_auth.require_valid_user가 정상입니다.",zh:"✔ chttpd_auth.require_valid_user 设置正确。"},"obsidianLiveSyncSettingTab.okWwwAuth":{def:"✔ httpd.WWW-Authenticate is ok.",es:"✔ httpd.WWW-Authenticate está correcto.",ko:"✔ httpd.WWW-Authenticate가 정상입니다.",zh:"✔ httpd.WWW-Authenticate 设置正确。"},"obsidianLiveSyncSettingTab.optionApply":{def:"Apply",es:"Aplicar",ko:"적용",zh:"应用"},"obsidianLiveSyncSettingTab.optionCancel":{def:"Cancel",es:"Cancelar",ko:"취소",zh:"取消"},"obsidianLiveSyncSettingTab.optionCouchDB":{def:"CouchDB",es:"CouchDB",ko:"CouchDB",zh:"CouchDB"},"obsidianLiveSyncSettingTab.optionDisableAllAutomatic":{def:"Disable all automatic",es:"Desactivar lo automático",ko:"모든 자동 비활성화",zh:"禁用所有自动同步"},"obsidianLiveSyncSettingTab.optionFetchFromRemote":{def:"Fetch from Remote",es:"Obtener del remoto",ko:"원격에서 가져오기",zh:"从远程获取"},"obsidianLiveSyncSettingTab.optionHere":{def:"HERE",es:"AQUÍ",ko:"여기",zh:"这里"},"obsidianLiveSyncSettingTab.optionLiveSync":{def:"LiveSync",es:"LiveSync",ko:"LiveSync",zh:"LiveSync"},"obsidianLiveSyncSettingTab.optionMinioS3R2":{def:"Minio,S3,R2",es:"Minio,S3,R2",ko:"Minio,S3,R2",zh:"Minio, S3, R2"},"obsidianLiveSyncSettingTab.optionOkReadEverything":{def:"OK, I have read everything.",es:"OK, he leído todo.",ko:"네, 모든 것을 읽었습니다.",zh:"好的,我已经阅读了所有内容。"},"obsidianLiveSyncSettingTab.optionOnEvents":{def:"On events",es:"En eventos",ko:"이벤트 시",zh:"基于事件"},"obsidianLiveSyncSettingTab.optionPeriodicAndEvents":{def:"Periodic and on events",es:"Periódico y en eventos",ko:"주기적 및 이벤트 시",zh:"定期和基于事件"},"obsidianLiveSyncSettingTab.optionPeriodicWithBatch":{def:"Periodic w/ batch",es:"Periódico con lote",ko:"주기적 w/ 일괄",zh:"定期与批量"},"obsidianLiveSyncSettingTab.optionRebuildBoth":{def:"Rebuild Both from This Device",es:"Reconstructuir ambos desde este dispositivo",ko:"이 기기에서 둘 다 재구축",zh:"从此设备重建两者"},"obsidianLiveSyncSettingTab.optionSaveOnlySettings":{def:"(Danger) Save Only Settings",es:"(Peligro) Guardar solo configuración",ko:"(위험) 설정만 저장",zh:"(危险)仅保存设置"},"obsidianLiveSyncSettingTab.panelChangeLog":{def:"Change Log",es:"Registro de cambios",ko:"변경 로그",zh:"更新日志"},"obsidianLiveSyncSettingTab.panelGeneralSettings":{def:"General Settings",es:"Configuraciones Generales",ko:"일반 설정",zh:"常规设置"},"obsidianLiveSyncSettingTab.panelPrivacyEncryption":{def:"Privacy & Encryption",es:"Privacidad y Cifrado",ko:"개인정보 보호 및 암호화",zh:"隐私与加密"},"obsidianLiveSyncSettingTab.panelRemoteConfiguration":{def:"Remote Configuration",es:"Configuración remota",ko:"원격 구성",zh:"远程配置"},"obsidianLiveSyncSettingTab.panelSetup":{def:"Setup",es:"Configuración",ko:"설정",zh:"设置"},"obsidianLiveSyncSettingTab.titleAppearance":{def:"Appearance",es:"Apariencia",ko:"외관",zh:"外观"},"obsidianLiveSyncSettingTab.titleConflictResolution":{def:"Conflict resolution",es:"Resolución de conflictos",ko:"충돌 해결",zh:"冲突解决"},"obsidianLiveSyncSettingTab.titleCongratulations":{def:"Congratulations!",es:"¡Felicidades!",ko:"축하합니다!",zh:"恭喜!"},"obsidianLiveSyncSettingTab.titleCouchDB":{def:"CouchDB",es:"CouchDB",ko:"CouchDB",zh:"CouchDB"},"obsidianLiveSyncSettingTab.titleDeletionPropagation":{def:"Deletion Propagation",es:"Propagación de eliminación",ko:"삭제 전파",zh:"删除传播"},"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled":{def:"Encryption is not enabled",es:"El cifrado no está habilitado",ko:"암호화가 활성화되지 않음",zh:"未启用加密"},"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid":{def:"Encryption Passphrase Invalid",es:"La frase de contraseña de cifrado es inválida",ko:"암호화 패스프레이즈 유효하지 않음",zh:"加密密码无效"},"obsidianLiveSyncSettingTab.titleExtraFeatures":{def:"Enable extra and advanced features",es:"Habilitar funciones extras y avanzadas",ko:"추가 및 고급 기능 활성화",zh:"启用额外和高级功能"},"obsidianLiveSyncSettingTab.titleFetchConfig":{def:"Fetch Config",es:"Obtener configuración",ko:"구성 가져오기",zh:"获取配置"},"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote":{def:"Fetch config from remote server",es:"Obtener configuración del servidor remoto",ko:"원격 서버에서 구성 가져오기",zh:"从远程服务器获取配置"},"obsidianLiveSyncSettingTab.titleFetchSettings":{def:"Fetch Settings",es:"Obtener configuraciones",ko:"설정 가져오기",zh:"获取设置"},"obsidianLiveSyncSettingTab.titleHiddenFiles":{def:"Hidden Files",es:"Archivos ocultos",ko:"숨김 파일",zh:"隐藏文件"},"obsidianLiveSyncSettingTab.titleLogging":{def:"Logging",es:"Registro",ko:"로깅",zh:"日志记录"},"obsidianLiveSyncSettingTab.titleMinioS3R2":{def:"Minio,S3,R2",es:"Minio,S3,R2",ko:"Minio,S3,R2",zh:"Minio, S3, R2"},"obsidianLiveSyncSettingTab.titleNotification":{def:"Notification",es:"Notificación",ko:"알림",zh:"通知"},"obsidianLiveSyncSettingTab.titleOnlineTips":{def:"Online Tips",es:"Consejos en línea",ko:"온라인 팁",zh:"在线提示"},"obsidianLiveSyncSettingTab.titleQuickSetup":{def:"Quick Setup",es:"Configuración rápida",ko:"빠른 설정",zh:"快速设置"},"obsidianLiveSyncSettingTab.titleRebuildRequired":{def:"Rebuild Required",es:"Reconstrucción necesaria",ko:"재구축 필요",zh:"需要重建"},"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed":{def:"Remote Configuration Check Failed",es:"La verificación de configuración remota falló",ko:"원격 구성 확인 실패",zh:"远程配置检查失败"},"obsidianLiveSyncSettingTab.titleRemoteServer":{def:"Remote Server",es:"Servidor remoto",ko:"원격 서버",zh:"远程服务器"},"obsidianLiveSyncSettingTab.titleReset":{def:"Reset",es:"Reiniciar",ko:"리셋",zh:"重置"},"obsidianLiveSyncSettingTab.titleSetupOtherDevices":{def:"To setup other devices",es:"Para configurar otros dispositivos",ko:"다른 기기 설정",zh:"设置其他设备"},"obsidianLiveSyncSettingTab.titleSynchronizationMethod":{def:"Synchronization Method",es:"Método de sincronización",ko:"동기화 방법",zh:"同步方法"},"obsidianLiveSyncSettingTab.titleSynchronizationPreset":{def:"Synchronization Preset",es:"Preestablecimiento de sincronización",ko:"동기화 프리셋",zh:"同步预设"},"obsidianLiveSyncSettingTab.titleSyncSettings":{def:"Sync Settings",es:"Configuraciones de Sincronización",ko:"동기화 설정",zh:"同步设置"},"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown":{def:"Sync Settings via Markdown",es:"Configuración de sincronización a través de Markdown",ko:"마크다운을 통한 동기화 설정",zh:"通过 Markdown 同步设置"},"obsidianLiveSyncSettingTab.titleUpdateThinning":{def:"Update Thinning",es:"Actualización de adelgazamiento",ko:"업데이트 솎아내기",zh:"更新频率限制"},"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched":{def:"⚠ CORS Origin is unmatched {from}->{to}",es:"⚠ El origen de CORS no coincide: {from}->{to}",ko:"⚠ CORS 원점이 일치하지 않습니다 {from}->{to}",zh:"⚠ CORS 源不匹配 {from}->{to}"},"obsidianLiveSyncSettingTab.warnNoAdmin":{def:"⚠ You do not have administrator privileges.",es:"⚠ No tienes privilegios de administrador.",ko:"⚠ 관리자 권한이 없습니다.",zh:"⚠ 您没有管理员权限。"},"P2P.AskPassphraseForDecrypt":{def:"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.",ko:"원격 피어가 구성을 공유했습니다. 구성을 복호화하려면 패스프레이즈를 입력해 주세요."},"P2P.AskPassphraseForShare":{def:"The remote peer requested this device configuration. Please input the passphrase to share the configuration. You can ignore the request by cancelling this dialogue.",ko:"원격 피어가 이 기기의 구성을 요청했습니다. 구성을 공유하려면 패스프레이즈를 입력해 주세요. 이 대화상자를 취소하여 요청을 무시할 수 있습니다."},"P2P.DisabledButNeed":{def:"%{title_p2p_sync} is disabled. Do you really want to enable it?",ko:"%{title_p2p_sync}가 비활성화되어 있습니다. 정말로 활성화하시겠습니까?"},"P2P.FailedToOpen":{def:"Failed to open P2P connection to the signaling server.",ko:"시그널링 서버에 P2P 연결을 열 수 없습니다."},"P2P.NoAutoSyncPeers":{def:"No auto-sync peers found. Please set peers on the %{long_p2p_sync} pane.",ko:"자동 동기화 피어를 찾을 수 없습니다. %{long_p2p_sync} 창에서 피어를 설정해 주세요."},"P2P.NoKnownPeers":{def:"No peers has been detected, waiting incoming other peers...",ko:"피어가 감지되지 않았습니다. 다른 피어의 접속을 기다리고 있습니다..."},"P2P.Note.description":{def:" This replicator allows us to synchronise our vault with other devices\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\nThis replicator is based on Trystero. It also uses a signaling server to establish a connection between devices. The signaling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\n\nThe signaling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signaling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\n\nBy the way, even if the signaling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.",ko:"이 복제기는 피어 투 피어(P2P) 연결을 통해 다른 기기들과 볼트를 동기화할 수 있도록 합니다. 클라우드 서비스를 거치지 않고도 기기간 동기화를 구현할 수 있습니다.\n\n이 복제기는 Trystero를 기반으로 하며, 기기 간 연결을 설정하기 위해 시그널링 서버를 사용합니다. 시그널링 서버는 단순히 연결 정보를 교환하는 용도로만 사용되며, 사용자 데이터를 저장하거나 접근하지 않습니다 (또는 그래야만 합니다).\n\n시그널링 서버는 누구나 운영할 수 있으며, 이는 단순한 Nostr 릴레이입니다. 편의성과 복제기의 작동 확인을 위해 `vrtmrz`가 자체적으로 시그널링 서버 인스턴스를 운영 중입니다. 사용자는 `vrtmrz`가 제공하는 실험용 서버를 사용할 수도 있고, 별도로 자신만의 서버를 설정할 수도 있습니다.\n\n참고로, 시그널링 서버는 사용자 데이터를 저장하지 않더라도 일부 기기의 연결 정보는 볼 수 있습니다. 이 점을 유의해 주세요. 특히 타인이 운영하는 서버를 사용할 경우 주의가 필요합니다."},"P2P.Note.important_note":{def:"The Experimental Implementation of the Peer-to-Peer Replicator.",ko:"피어 투 피어(P2P) 복제기의 실험적 구현입니다."},"P2P.Note.important_note_sub":{def:"This feature is still in the experimental stage. Please be aware that this feature may not work as expected. Furthermore, it may have some bugs, security issues, and other issues. Please use this feature at your own risk. Please contribute to the development of this feature.",ko:"이 기능은 아직 실험 단계에 있습니다. 이 기능이 예상대로 작동하지 않을 수 있음을 알아주세요. 또한 버그, 보안 문제 및 기타 문제가 있을 수 있습니다. 이 기능을 사용할 때는 본인의 책임 하에 사용하세요. 이 기능의 개발에 기여해 주세요."},"P2P.Note.Summary":{def:"What is this feature? (and some important notes, please read once)",ko:"이 기능은 무엇인가요? (설명과 참고사항이 적혀있습니다. 한 번 읽어보세요!)"},"P2P.NotEnabled":{def:"%{title_p2p_sync} is not enabled. We cannot open a new connection.",ko:"%{title_p2p_sync}가 활성화되지 않았습니다. 새로운 연결을 열 수 없습니다."},"P2P.P2PReplication":{def:"%{P2P} Replication",ko:"%{P2P} 복제"},"P2P.PaneTitle":{def:"%{long_p2p_sync}",ko:"%{long_p2p_sync}"},"P2P.ReplicatorInstanceMissing":{def:"P2P Sync replicator is not found, possibly not have been configured or enabled.",ko:"P2P 동기화 복제기를 찾을 수 없습니다. 구성되지 않았거나 활성화되지 않았을 수 있습니다."},"P2P.SeemsOffline":{def:"Peer ${name} seems offline, skipped.",ko:"피어 ${name}이(가) 오프라인인 것 같습니다. 건너뜁니다."},"P2P.SyncAlreadyRunning":{def:"P2P Sync is already running.",ko:"P2P 동기화가 이미 실행 중입니다."},"P2P.SyncCompleted":{def:"P2P Sync completed.",ko:"P2P 동기화가 완료되었습니다."},"P2P.SyncStartedWith":{def:"P2P Sync with ${name} have been started.",ko:"${name}과의 P2P 동기화가 시작되었습니다."},Passphrase:{def:"Passphrase",es:"Frase de contraseña",ja:"パスフレーズ",ko:"패스프레이즈",zh:"密码"},"Passphrase of sensitive configuration items":{def:"Passphrase of sensitive configuration items",es:"Frase para elementos sensibles",ja:"機微設定項目にパスフレーズを使用",ko:"민감한 구성 항목의 패스프레이즈",zh:"敏感配置项的密码"},password:{def:"password",es:"contraseña",ja:"パスワード",ko:"비밀번호",zh:"密码"},Password:{def:"Password",es:"Contraseña",ja:"パスワード",ko:"비밀번호",zh:"密码"},"Path Obfuscation":{def:"Path Obfuscation",es:"Ofuscación de rutas",ja:"パスの難読化",ko:"경로 난독화",zh:"路径混淆"},"Per-file-saved customization sync":{def:"Per-file-saved customization sync",es:"Sincronización de personalización por archivo",ko:"파일별 저장 사용자 설정 동기화",zh:"按文件保存的自定义同步"},"Periodic Sync interval":{def:"Periodic Sync interval",es:"Intervalo de sincronización periódica",ja:"定時同期の感覚",ko:"주기적 동기화 간격",zh:"定期同步间隔"},Presets:{def:"Presets",es:"Preconfiguraciones",ja:"プリセット",ko:"프리셋",zh:"预设"},"Process small files in the foreground":{def:"Process small files in the foreground",es:"Procesar archivos pequeños en primer plano",ko:"포그라운드에서 작은 파일 처리",zh:"在前台处理小文件"},"RedFlag.Fetch.Method.Desc":{def:"How do you want to fetch?\n- %{RedFlag.Fetch.Method.FetchSafer}. (Recommended)\n **Low Traffic**, **High CPU**, **Low Risk**\n- %{RedFlag.Fetch.Method.FetchSmoother}.\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\n- %{RedFlag.Fetch.Method.FetchTraditional}.\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\n\n>[!INFO]- Details\n> ## %{RedFlag.Fetch.Method.FetchSafer}. (Recommended)\n> **Low Traffic**, **High CPU**, **Low Risk**\n> This option first creates a local database using existing local files before fetching data from the remote source.\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\n> This is generally the safest method, minimizing data loss risk.\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\n> This uses less CPU and faster than \"%{RedFlag.Fetch.Method.FetchSafer}\", but it may lead to data loss if not used carefully.\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\n> All things will be fetched from the remote.\n> Similar to the %{RedFlag.Fetch.Method.FetchSmoother}, but all chunks are fetched from the remote source.\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the '%{RedFlag.Fetch.Method.FetchSmoother}' option.\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.",ko:"어떻게 가져오시겠습니까?\n- %{RedFlag.Fetch.Method.FetchSafer}. (권장)\n **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n- %{RedFlag.Fetch.Method.FetchSmoother}.\n **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험**\n- %{RedFlag.Fetch.Method.FetchTraditional}.\n **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험**\n\n>[!INFO]- 세부 사항\n> ## %{RedFlag.Fetch.Method.FetchSafer}. (권장)\n> **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n> 이 옵션은 원격 소스에서 데이터를 가져오기 전에 기존 로컬 파일을 사용하여 로컬 데이터베이스를 먼저 생성합니다.\n> 로컬과 원격 모두에 일치하는 파일이 있으면 둘 사이의 차이점만 전송됩니다.\n> 하지만 두 위치 모두에 있는 파일은 초기에 충돌 파일로 처리됩니다. 실제로 충돌하지 않는다면 자동으로 해결되지만 이 과정은 시간이 걸릴 수 있습니다.\n> 이는 일반적으로 가장 안전한 방법으로 데이터 손실 위험을 최소화합니다.\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\n> **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험** (작업에 따라)\n> 이 옵션은 먼저 로컬 파일에서 데이터베이스용 청크를 생성한 다음 데이터를 가져옵니다. 따라서 로컬에 없는 청크만 전송됩니다. 하지만 모든 메타데이터는 원격 소스에서 가져옵니다.\n> 그런 다음 로컬 파일이 시작 시 이 메타데이터와 비교됩니다. 더 새로운 것으로 간주되는 콘텐츠가 오래된 것을 덮어씁니다(수정 시간 기준). 이 결과는 원격 데이터베이스에 다시 동기화됩니다.\n> 로컬 파일이 실제로 최신 타임스탬프라면 일반적으로 안전합니다. 하지만 파일이 더 새로운 타임스탬프를 가지고 있지만 더 오래된 콘텐츠를 가지고 있다면(초기 `welcome.md`처럼) 문제가 발생할 수 있습니다.\n> 이는 \"%{RedFlag.Fetch.Method.FetchSafer}\"보다 CPU를 덜 사용하고 더 빠르지만 주의 깊게 사용하지 않으면 데이터 손실로 이어질 수 있습니다.\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\n> **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험** (작업에 따라)\n> 모든 것이 원격에서 가져와집니다.\n> %{RedFlag.Fetch.Method.FetchSmoother}와 유사하지만 모든 청크가 원격 소스에서 가져와집니다.\n> 이는 가장 전통적인 가져오기 방법으로 일반적으로 가장 많은 네트워크 트래픽과 시간을 소모합니다. 또한 '%{RedFlag.Fetch.Method.FetchSmoother}' 옵션과 유사하게 원격 파일을 덮어쓸 위험이 있습니다.\n> 하지만 가장 오래되고 가장 직접적인 접근 방식이기 때문에 종종 가장 안정적인 방법으로 간주됩니다."},"RedFlag.Fetch.Method.FetchSafer":{def:"Create a local database once before fetching",ko:"가져오기 전에 로컬 데이터베이스를 한 번 생성"},"RedFlag.Fetch.Method.FetchSmoother":{def:"Create local file chunks before fetching",ko:"가져오기 전에 로컬 파일 청크 생성"},"RedFlag.Fetch.Method.FetchTraditional":{def:"Fetch everything from the remote",ko:"원격에서 모든 것 가져오기"},"RedFlag.Fetch.Method.Title":{def:"How do you want to fetch?",ko:"어떻게 가져오시겠습니까?"},"Reducing the frequency with which on-disk changes are reflected into the DB":{def:"Reducing the frequency with which on-disk changes are reflected into the DB",es:"Reducir frecuencia de actualizaciones de disco a BD",ko:"디스크 변경 사항이 데이터베이스에 반영되는 빈도를 줄입니다",zh:"降低将磁盘上的更改反映到数据库中的频率"},Region:{def:"Region",es:"Región",ja:"リージョン",ko:"지역",zh:"Region"},"Remote server type":{def:"Remote server type",es:"Tipo de servidor remoto",ja:"リモートの種別",ko:"원격 서버 유형",zh:"远程服务器类型"},"Remote Type":{def:"Remote Type",es:"Tipo de remoto",ja:"同期方式",ko:"원격 유형",zh:"远程类型"},"Replicator.Dialogue.Locked.Action.Dismiss":{def:"Cancel for reconfirmation",ko:"재확인을 위해 취소"},"Replicator.Dialogue.Locked.Action.Fetch":{def:"Fetch all from the remote database again",ko:"원격 데이터베이스에서 모든 것을 다시 가져오기"},"Replicator.Dialogue.Locked.Action.Unlock":{def:"Unlock the remote database",ko:"원격 데이터베이스 잠금 해제"},"Replicator.Dialogue.Locked.Message":{def:"Remote database is locked. This is due to a rebuild on one of the terminals.\nThe device is therefore asked to withhold the connection to avoid database corruption.\n\nThere are three options that we can do:\n\n- %{Replicator.Dialogue.Locked.Action.Fetch}\n The most preferred and reliable way. This will dispose the local database once, and fetch all from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\n- %{Replicator.Dialogue.Locked.Action.Unlock}\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\n This will cancel the operation. And we will asked again on next request.\n",ko:"원격 데이터베이스가 잠겨 있습니다. 이는 일부 터미널에서 데이터베이스를 재구축했기 때문입니다.\n따라서 현재 기기는 데이터베이스 손상을 방지하기 위해 연결을 일시적으로 보류해야 합니다.\n\n선택할 수 있는 세 가지 방법이 있습니다:\n\n- %{Replicator.Dialogue.Locked.Action.Fetch}\n 가장 권장되고 신뢰할 수 있는 방법입니다. 로컬 데이터베이스를 초기화한 뒤, 원격 데이터베이스의 전체 데이터를 다시 가져옵니다. 대부분의 경우 안전하게 수행할 수 있으나, 시간이 다소 걸리며 안정적인 네트워크 환경에서 진행해야 합니다.\n- %{Replicator.Dialogue.Locked.Action.Unlock}\n 이 방법은 다른 동기화 방식으로 이미 완전하고 안정적으로 동기화된 경우에만 사용할 수 있습니다. 단순히 파일이 같다는 의미가 아니므로, 확신이 없다면 사용을 피하는 것이 좋습니다.\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\n 이번 작업을 취소하고, 다음 요청 시 다시 안내받습니다.\n"},"Replicator.Dialogue.Locked.Message.Fetch":{def:"Fetch all has been scheduled. Plug-in will be restarted to perform it.",ko:"모든 것 가져오기가 예약되었습니다. 이를 수행하기 위해 플러그인이 재시작됩니다."},"Replicator.Dialogue.Locked.Message.Unlocked":{def:"The remote database has been unlocked. Please retry the operation.",ko:"원격 데이터베이스 잠금이 해제되었습니다. 작업을 다시 시도해 주세요."},"Replicator.Dialogue.Locked.Title":{def:"Locked",ko:"잠김"},"Replicator.Message.Cleaned":{def:"Database cleaning up is in process. replication has been cancelled",ko:"데이터베이스 정리가 진행 중입니다. 복제가 취소되었습니다"},"Replicator.Message.InitialiseFatalError":{def:"No replicator is available, this is the fatal error.",ko:"사용 가능한 복제기가 없습니다. 치명적인 오류입니다."},"Replicator.Message.Pending":{def:"Some file events are pending. Replication has been cancelled.",ko:"일부 파일 이벤트가 대기 중입니다. 복제가 취소되었습니다."},"Replicator.Message.SomeModuleFailed":{def:"Replication has been cancelled by some module failure",ko:"일부 모듈 실패로 복제가 취소되었습니다"},"Replicator.Message.VersionUpFlash":{def:"Open settings and check message, please. replication has been cancelled.",ko:"설정을 열고 메시지를 확인해 주세요. 복제가 취소되었습니다."},"Requires restart of Obsidian":{def:"Requires restart of Obsidian",es:"Requiere reiniciar Obsidian",ko:"Obsidian 재시작 필요",zh:"需要重启 Obsidian"},"Requires restart of Obsidian.":{def:"Requires restart of Obsidian.",es:"Requiere reiniciar Obsidian",ko:"Obsidian 재시작이 필요합니다.",zh:"需要重启 Obsidian。"},"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.":{def:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.",es:"Guardar configuración en archivo markdown. Se notificarán nuevos ajustes. Puede definir diferentes archivos por plataforma",ko:"설정을 마크다운 파일에 저장합니다. 새로운 설정이 도착하면 알림을 받게 됩니다. 플랫폼별로 다른 파일을 설정할 수 있습니다.",zh:"将设置保存到一个 Markdown 文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件。"},"Saving will be performed forcefully after this number of seconds.":{def:"Saving will be performed forcefully after this number of seconds.",es:"Guardado forzado tras esta cantidad de segundos",ko:"이 시간(초) 후에 강제로 저장이 수행됩니다.",zh:"在此秒数后将强制执行保存。"},"Scan changes on customization sync":{def:"Scan changes on customization sync",es:"Escanear cambios en sincronización de personalización",ja:"カスタマイズされた同期時に、変更をスキャンする",ko:"사용자 설정 동기화 시 변경 사항 검색",zh:"在自定义同步时扫描更改"},"Scan customization automatically":{def:"Scan customization automatically",es:"Escanear personalización automáticamente",ja:"自動的にカスタマイズをスキャン",ko:"사용자 설정 자동 검색",zh:"自动扫描自定义设置"},"Scan customization before replicating.":{def:"Scan customization before replicating.",es:"Escanear personalización antes de replicar",ja:"レプリケーション前に、カスタマイズをスキャン",ko:"복제하기 전에 사용자 설정을 검색합니다.",zh:"在复制前扫描自定义设置。"},"Scan customization every 1 minute.":{def:"Scan customization every 1 minute.",es:"Escanear personalización cada 1 minuto",ja:"カスタマイズのスキャンを1分ごとに行う",ko:"1분마다 사용자 설정을 검색합니다.",zh:"每1分钟扫描自定义设置。"},"Scan customization periodically":{def:"Scan customization periodically",es:"Escanear personalización periódicamente",ja:"定期的にカスタマイズをスキャン",ko:"주기적으로 사용자 설정 검색",zh:"定期扫描自定义设置"},"Scan for hidden files before replication":{def:"Scan for hidden files before replication",es:"Escanear archivos ocultos antes de replicar",ja:"レプリケーション開始前に、隠しファイルのスキャンを行う",ko:"복제 전 숨겨진 파일 검색",zh:"复制前扫描隐藏文件"},"Scan hidden files periodically":{def:"Scan hidden files periodically",es:"Escanear archivos ocultos periódicamente",ja:"定期的に隠しファイルのスキャンを行う",ko:"주기적으로 숨겨진 파일 검색",zh:"定期扫描隐藏文件"},"Seconds, 0 to disable":{def:"Seconds, 0 to disable",es:"Segundos, 0 para desactivar",ko:"초 단위, 0으로 설정하면 비활성화",zh:"秒,0为禁用"},"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.":{def:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.",es:"Segundos. Guardado en BD local se retrasará hasta este valor tras dejar de escribir/guardar",ko:"초 단위입니다. 타이핑이나 저장을 중단한 후 이 시간동안 로컬 데이터베이스 저장이 지연됩니다.",zh:"秒。在我们停止输入或保存后,保存到本地数据库将延迟此值。"},"Secret Key":{def:"Secret Key",es:"Clave secreta",ja:"シークレットキー",ko:"시크릿 키",zh:"Secret Key"},"Server URI":{def:"Server URI",es:"URI del servidor",ja:"URI",ko:"서버 URI",zh:"服务器 URI"},"Setting.GenerateKeyPair.Desc":{def:'We have generated a key pair!\n\nNote: This key pair will never be shown again. Please save it in a safe place. If you have lost it, you need to generate a new key pair.\nNote 2: The public key is in spki format, and the Private key is in pkcs8 format. For the sake of convenience, newlines are converted to `\\n` in public key.\nNote 3: The public key should be configured in the remote database, and the private key should be configured in local devices.\n\n>[!FOR YOUR EYES ONLY]-\n>
\n>\n> ### Public Key\n> ```\n${public_key}\n> ```\n>\n> ### Private Key\n> ```\n${private_key}\n> ```\n>\n>
\n\n>[!Both for copying]-\n>\n>
\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n>
\n\n',ko:'키 페어를 생성했습니다!\n\n참고: 이 키 페어는 다시 표시되지 않습니다. 안전한 곳에 저장해 주세요. 분실하면 새 키 페어를 생성해야 합니다.\n참고 2: 공개 키는 spki 형식이고, 개인 키는 pkcs8 형식입니다. 편의상 공개 키의 줄 바꿈은 `\\n`으로 변환됩니다.\n참고 3: 공개 키는 원격 데이터베이스에서 구성되어야 하고, 개인 키는 로컬 기기에서 구성되어야 합니다.\n\n>[!FOR YOUR EYES ONLY]-\n>
\n>\n> ### 공개 키\n> ```\n${public_key}\n> ```\n>\n> ### 개인 키\n> ```\n${private_key}\n> ```\n>\n>
\n\n>[!Both for copying]-\n>\n>
\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n>
\n\n\n'},"Setting.GenerateKeyPair.Title":{def:"New key pair has been generated!",ko:"새 키 페어가 생성되었습니다!"},"Setting.TroubleShooting":{def:"TroubleShooting",ko:"문제 해결"},"Setting.TroubleShooting.Doctor":{def:"Setting Doctor",ko:"설정 진단 마법사"},"Setting.TroubleShooting.Doctor.Desc":{def:"Detects non optimal settings. (Same as during migration)",ko:"최적화되지 않은 설정을 감지합니다. (데이터 구조 전환 시와 동일)"},"SettingTab.Message.AskRebuild":{def:"Your changes require fetching from the remote database. Do you want to proceed?",ko:"변경 사항을 적용하려면 원격 데이터베이스에서 가져와야 합니다. 계속 진행하시겠습니까?"},"Setup.QRCode":{def:'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\nNote: The QR code is not encrypted, so be careful to open this.\n\n>[!FOR YOUR EYES ONLY]-\n>
${qr_image}
',ko:'설정을 전송하기 위한 QR 코드를 생성했습니다. 휴대폰이나 다른 기기로 QR 코드를 스캔해 주세요.\n참고: QR 코드는 암호화되지 않았으므로 열 때 주의하세요.\n\n>[!FOR YOUR EYES ONLY]-\n>
${qr_image}
'},"Setup.ShowQRCode":{def:"Show QR code",ko:"QR 코드 표시"},"Setup.ShowQRCode.Desc":{def:"Show QR code to transfer the settings.",ko:"설정을 전송하기 위한 QR 코드를 표시합니다."},"Should we keep folders that don't have any files inside?":{def:"Should we keep folders that don't have any files inside?",es:"¿Mantener carpetas vacías?",ko:"내부에 파일이 없는 폴더를 유지하시겠습니까?",zh:"我们是否应该保留内部没有任何文件的文件夹?"},"Should we only check for conflicts when a file is opened?":{def:"Should we only check for conflicts when a file is opened?",es:"¿Solo comprobar conflictos al abrir archivo?",ko:"파일을 열 때만 충돌을 확인하시겠습니까?",zh:"我们是否应该仅在文件打开时检查冲突?"},"Should we prompt you about conflicting files when a file is opened?":{def:"Should we prompt you about conflicting files when a file is opened?",es:"¿Notificar sobre conflictos al abrir archivo?",ko:"파일을 열 때 충돌하는 파일에 대해 알림을 표시하시겠습니까?",zh:"当文件打开时,是否提示冲突文件?"},"Should we prompt you for every single merge, even if we can safely merge automatcially?":{def:"Should we prompt you for every single merge, even if we can safely merge automatcially?",es:"¿Preguntar en cada fusión aunque sea automática?",ko:"안전하게 자동 병합할 수 있는 경우에도 모든 병합에 대해 알림을 받으시겠습니까?",zh:"即使我们可以安全地自动合并,是否也应该为每一次合并提示您?"},"Show only notifications":{def:"Show only notifications",es:"Mostrar solo notificaciones",ja:"通知のみ表示",ko:"알림만 표시",zh:"仅显示通知"},"Show status as icons only":{def:"Show status as icons only",es:"Mostrar estado solo con íconos",ja:"ステータス表示をアイコンのみにする",ko:"아이콘으로만 상태 표시",zh:"仅以图标显示状态"},"Show status inside the editor":{def:"Show status inside the editor",es:"Mostrar estado dentro del editor",ja:"ステータスをエディタ内に表示",ko:"편집기 내부에 상태 표시",zh:"在编辑器内显示状态"},"Show status on the status bar":{def:"Show status on the status bar",es:"Mostrar estado en la barra de estado",ja:"ステータスバーに、ステータスを表示",ko:"상태 바에 상태 표시",zh:"在状态栏上显示状态"},"Show verbose log. Please enable if you report an issue.":{def:"Show verbose log. Please enable if you report an issue.",es:"Mostrar registro detallado. Actívelo si reporta un problema.",ja:"エラー以外の詳細ログ項目も表示する。問題が発生した場合は有効にしてください。",ko:"자세한 로그를 표시합니다. 문제를 신고하는 경우 활성화해 주세요.",zh:"显示详细日志。如果您报告问题,请启用此选项。"},"Starts synchronisation when a file is saved.":{def:"Starts synchronisation when a file is saved.",es:"Inicia sincronización al guardar un archivo",ko:"파일이 저장될 때 동기화를 시작합니다.",zh:"当文件保存时启动同步。"},"Stop reflecting database changes to storage files.":{def:"Stop reflecting database changes to storage files.",es:"Dejar de reflejar cambios de BD en archivos",ja:"データベースの変更をストレージファイルに反映させない",ko:"데이터베이스 변경 사항을 스토리지 파일에 반영하는 것을 중단합니다.",zh:"停止将数据库更改反映到存储文件。"},"Stop watching for file changes.":{def:"Stop watching for file changes.",es:"Dejar de monitorear cambios en archivos",ja:"監視の停止",ko:"파일 변경 사항 감시를 중단합니다.",zh:"停止监视文件更改。"},"Suppress notification of hidden files change":{def:"Suppress notification of hidden files change",es:"Suprimir notificaciones de cambios en archivos ocultos",ko:"숨겨진 파일 변경 알림 억제",zh:"抑制隐藏文件更改的通知"},"Suspend database reflecting":{def:"Suspend database reflecting",es:"Suspender reflejo de base de datos",ja:"データベース反映の一時停止",ko:"데이터베이스 반영 일시 중단",zh:"暂停数据库反映"},"Suspend file watching":{def:"Suspend file watching",es:"Suspender monitorización de archivos",ja:"監視の一時停止",ko:"파일 감시 일시 중단",zh:"暂停文件监视"},"Sync after merging file":{def:"Sync after merging file",es:"Sincronizar tras fusionar archivo",ja:"ファイルがマージ(統合)された時に同期",ko:"파일 병합 후 동기화",zh:"合并文件后同步"},"Sync automatically after merging files":{def:"Sync automatically after merging files",es:"Sincronizar automáticamente tras fusionar archivos",ko:"파일 병합 후 자동으로 동기화",zh:"合并文件后自动同步"},"Sync Mode":{def:"Sync Mode",es:"Modo de sincronización",ja:"同期モード",ko:"동기화 모드",zh:"同步模式"},"Sync on Editor Save":{def:"Sync on Editor Save",es:"Sincronizar al guardar en editor",ja:"エディタでの保存時に、同期されます",ko:"편집기 저장 시 동기화",zh:"编辑器保存时同步"},"Sync on File Open":{def:"Sync on File Open",es:"Sincronizar al abrir archivo",ja:"ファイルを開いた時に同期",ko:"파일 열기 시 동기화",zh:"打开文件时同步"},"Sync on Save":{def:"Sync on Save",es:"Sincronizar al guardar",ja:"保存時に同期",ko:"저장 시 동기화",zh:"保存时同步"},"Sync on Startup":{def:"Sync on Startup",es:"Sincronizar al iniciar",ja:"起動時同期",ko:"시작 시 동기화",zh:"启动时同步"},"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.":{def:"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.",es:"Solo pruebas - Resolver conflictos sincronizando copias nuevas (puede sobrescribir modificaciones)",ko:"테스트 전용 - 파일의 새로운 사본을 동기화하여 파일 충돌을 해결하며, 수정된 파일을 덮어쓸 수 있습니다. 주의하세요.",zh:"仅供测试 - 通过同步文件的较新副本来解决文件冲突,这可能会覆盖修改过的文件。请注意。"},"The delay for consecutive on-demand fetches":{def:"The delay for consecutive on-demand fetches",es:"Retraso entre obtenciones consecutivas",ko:"연속 청크 요청 간 대기 시간",zh:"连续按需获取的延迟"},"The Hash algorithm for chunk IDs":{def:"The Hash algorithm for chunk IDs",es:"Algoritmo hash para IDs de chunks",ja:"チャンクIDのハッシュアルゴリズム",ko:"청크 ID용 해시 알고리즘",zh:"块 ID 的哈希算法(实验性)"},"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.":{def:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.",es:"Duración máxima para incubar chunks. Excedentes se independizan",ko:"변경 기록이 문서에 함께 보관될 수 있는 최대 시간입니다. 초과 시 문서에서 분리되어 개별로 저장됩니다.",zh:"文档中可以孵化的数据块的最大持续时间。超过此时间的数据块将成为独立数据块。"},"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.":{def:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.",es:"Número máximo de chunks que pueden incubarse en el documento. Excedentes se independizan",ko:"문서 안에 임시로 보관할 수 있는 변경 기록의 최대 개수입니다. 이 수를 초과하면 즉시 독립된 청크로 분리되어 저장됩니다.",zh:"文档中可以孵化的数据块的最大数量。超过此数量的数据块将立即成为独立数据块。"},"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.":{def:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.",es:"Tamaño total máximo de chunks incubados. Excedentes se independizan",ko:"문서 안에 임시로 보관할 수 있는 변경 기록의 전체 크기 제한입니다. 초과 시 자동으로 분리됩니다.",zh:"文档中可以孵化的数据块的最大总大小。超过此大小的数据块将立即成为独立数据块。"},"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.":{def:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.",es:"Esta frase no se copia a otros dispositivos. Usará `Default` hasta reconfigurar",ko:"이 패스프레이즈는 다른 기기로 복사되지 않습니다. 다시 구성할 때까지 `기본값`으로 설정됩니다.",zh:"此密码不会复制到另一台设备。在您再次配置之前,它将设置为 `Default`。"},"TweakMismatchResolve.Action.Dismiss":{def:"Dismiss",ko:"무시"},"TweakMismatchResolve.Action.UseConfigured":{def:"Use configured settings",ko:"구성된 설정 사용"},"TweakMismatchResolve.Action.UseMine":{def:"Update remote database settings",ko:"원격 데이터베이스 설정 업데이트"},"TweakMismatchResolve.Action.UseMineAcceptIncompatible":{def:"Update remote database settings but keep as is",ko:"원격 데이터베이스 설정 업데이트하지만 그대로 유지"},"TweakMismatchResolve.Action.UseMineWithRebuild":{def:"Update remote database settings and rebuild again",ko:"원격 데이터베이스 설정 업데이트하고 다시 재구축"},"TweakMismatchResolve.Action.UseRemote":{def:"Apply settings to this device",ko:"이 기기에 설정 적용"},"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible":{def:"Apply settings to this device, but and ignore incompatibility",ko:"이 기기에 설정 적용하지만 호환성 문제 무시"},"TweakMismatchResolve.Action.UseRemoteWithRebuild":{def:"Apply settings to this device, and fetch again",ko:"이 기기에 설정 적용하고 다시 가져오기"},"TweakMismatchResolve.Message.Main":{def:"\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\n\nIf you want to use these settings, please select %{TweakMismatchResolve.Action.UseConfigured}.\nIf you want to keep the settings of this device, please select %{TweakMismatchResolve.Action.Dismiss}.\n\n${table}\n\n>[!TIP]\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\n\n${additionalMessage}",ko:"\n원격 데이터베이스의 설정은 다음과 같습니다. 이 값들은 이 기기와 최소 한 번 동기화된 다른 기기에서 구성된 것입니다.\n\n이 설정을 사용하려면 %{TweakMismatchResolve.Action.UseConfigured}를 선택해 주세요.\n이 기기의 설정을 유지하려면 %{TweakMismatchResolve.Action.Dismiss}를 선택해 주세요.\n\n${table}\n\n>[!TIP]\n> 모든 설정을 동기화하려면 이 기능으로 최소 구성을 적용한 후 `마크다운을 통한 설정 동기화`를 사용해 주세요.\n\n${additionalMessage}"},"TweakMismatchResolve.Message.MainTweakResolving":{def:"Your configuration has not been matched with the one on the remote server.\n\nFollowing configuration should be matched:\n\n${table}\n\nLet us know your decision.\n\n${additionalMessage}",ko:"구성이 원격 서버의 것과 일치하지 않습니다.\n\n다음 구성이 일치해야 합니다:\n\n${table}\n\n결정을 알려주세요.\n\n${additionalMessage}"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended":{def:"\n>[!NOTICE]\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",ko:"\n>[!NOTICE]\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired":{def:"\n>[!WARNING]\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",ko:"\n>[!WARNING]\n> 일부 원격 구성이 이 기기의 로컬 데이터베이스와 호환되지 않습니다. 로컬 데이터베이스 재구축이 필요합니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended":{def:"\n>[!NOTICE]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**",ko:"\n>[!NOTICE]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> 재구축을 원한다면 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired":{def:"\n>[!WARNING]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**",ko:"\n>[!WARNING]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 로컬 또는 원격 재구축이 필요합니다. 둘 다 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**"},"TweakMismatchResolve.Table":{def:"| Value name | This device | On Remote |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",ko:"| 값 이름 | 이 기기 | 원격 |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n"},"TweakMismatchResolve.Table.Row":{def:"| ${name} | ${self} | ${remote} |",ko:"| ${name} | ${self} | ${remote} |"},"TweakMismatchResolve.Title":{def:"Configuration Mismatch Detected",ko:"구성 불일치 감지"},"TweakMismatchResolve.Title.TweakResolving":{def:"Configuration Mismatch Detected",ko:"구성 불일치 감지"},"TweakMismatchResolve.Title.UseRemoteConfig":{def:"Use Remote Configuration",ko:"원격 구성 사용"},"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.":{def:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.",es:"Nombre único entre dispositivos sincronizados. Para editarlo, desactive sincronización de personalización",ja:"一意の名称を、すべての端末に設定します。この設定を変更した場合、カスタマイズ同期機能を無効にしてください。",ko:"모든 동기화된 기기 간 고유 이름입니다. 이 설정을 편집하려면 사용자 설정 동기화를 한 번 비활성화해 주세요.",zh:"所有同步设备之间的唯一名称。要编辑此设置,请首先禁用自定义同步"},"Use Custom HTTP Handler":{def:"Use Custom HTTP Handler",es:"Usar manejador HTTP personalizado",ja:"カスタムHTTPハンドラーの利用",ko:"커스텀 HTTP 핸들러 사용",zh:"使用自定义 HTTP 处理程序"},"Use dynamic iteration count":{def:"Use dynamic iteration count",es:"Usar conteo de iteraciones dinámico",ja:"動的な繰り返し回数",ko:"동적 반복 횟수 사용",zh:"使用动态迭代次数"},"Use Segmented-splitter":{def:"Use Segmented-splitter",es:"Usar divisor segmentado",ko:"의미 기반 분할 사용",zh:"使用分段分割器"},"Use splitting-limit-capped chunk splitter":{def:"Use splitting-limit-capped chunk splitter",es:"Usar divisor de chunks con límite",ko:"분할 제한 상한 청크 분할기 사용",zh:"使用分割限制上限的块分割器"},"Use the trash bin":{def:"Use the trash bin",es:"Usar papelera",ja:"ゴミ箱を使用",ko:"휴지통 사용",zh:"使用回收站"},"Use timeouts instead of heartbeats":{def:"Use timeouts instead of heartbeats",es:"Usar timeouts en lugar de latidos",ja:"ハートビートの代わりにタイムアウトを使用",ko:"하트비트 대신 타임아웃 사용",zh:"使用超时而不是心跳"},username:{def:"username",es:"nombre de usuario",ja:"ユーザー名",ko:"사용자명",zh:"用户名"},Username:{def:"Username",es:"Usuario",ja:"ユーザー名",ko:"사용자명",zh:"用户名"},"Verbose Log":{def:"Verbose Log",es:"Registro detallado",ja:"エラー以外のログ項目",ko:"자세한 로그",zh:"详细日志"},"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.":{def:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.",es:"¡Advertencia! Impacta rendimiento. Los logs no se sincronizan con nombre predeterminado. Contienen información confidencial",ko:"경고! 이는 성능에 심각한 영향을 미칩니다. 로그는 기본 이름으로 동기화되지 않습니다. 로그에는 종종 기밀 정보가 포함되어 있으므로 주의해 주세요.",zh:"警告!这将严重影响性能。并且日志不会以默认名称同步。请小心处理日志;它们通常包含您的敏感信息。"},"When you save a file in the editor, start a sync automatically":{def:"When you save a file in the editor, start a sync automatically",es:"Iniciar sincronización automática al guardar en editor",ja:"エディタでファイルを保存すると、自動的に同期を開始します",ko:"편집기에서 파일을 저장할 때 자동으로 동기화를 시작합니다",zh:"当您在编辑器中保存文件时,自动开始同步"},"Write credentials in the file":{def:"Write credentials in the file",es:"Escribir credenciales en archivo",ja:"クレデンシャルのファイル内保存",ko:"파일에 자격 증명 저장",zh:"将凭据写入文件"},"Write logs into the file":{def:"Write logs into the file",es:"Escribir logs en archivo",ja:"ファイルにログを記録",ko:"파일에 로그 기록",zh:"将日志写入文件"},"Compute revisions for chunks (Previous behaviour)":{es:"Calcular revisiones para chunks (comportamiento anterior)",zh:"为 chunks 计算修订版本(以前的行为)"}},"def"),...expandKeywords(_allMessages,"es"),...expandKeywords(_allMessages,"ja"),...expandKeywords(_allMessages,"ko"),...expandKeywords(_allMessages,"ru"),...expandKeywords(_allMessages,"zh"),...expandKeywords(_allMessages,"zh-tw")};allMessages=expandedMessage;currentLang="";missingTranslations=[];__onMissingTranslations=key2=>console.warn(key2);msgCache=new Map;on_click=(_,closeDialogue)=>closeDialogue();root_1=template("
 
");root=template('
');$$css={hash:"svelte-47tukr",code:".svelte-47tukr {box-sizing:border-box;}.logpane.svelte-47tukr {display:flex;height:100%;flex-direction:column;}.log.svelte-47tukr {overflow-y:scroll;user-select:text;-webkit-user-select:text;padding-bottom:2em;}.log.svelte-47tukr > pre:where(.svelte-47tukr) {margin:0;}.log.svelte-47tukr > pre.wrap-right:where(.svelte-47tukr) {word-break:break-all;max-width:100%;width:100%;white-space:normal;}.row.svelte-47tukr {display:flex;flex-direction:row;justify-content:flex-end;}.row.svelte-47tukr > label:where(.svelte-47tukr) {display:flex;align-items:center;min-width:5em;margin-right:1em;}"};delegate(["click"]);import_obsidian3=require("obsidian");SvelteItemView=class extends import_obsidian3.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}}};require("obsidian");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")}};nodeCrypto=__toESM(require("crypto"),1);_0n=BigInt(0);_1n=BigInt(1);_2n=BigInt(2);_3n=BigInt(3);_8n=BigInt(8);CURVE=Object.freeze({a:_0n,b:BigInt(7),P:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:_1n,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")});divNearest=(a2,b3)=>(a2+b3/_2n)/b3;endo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar(k2){const{n:n3}=CURVE,a1=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),b1=-_1n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),a2=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),b22=a1,POW_2_128=BigInt("0x100000000000000000000000000000000"),c12=divNearest(b22*k2,n3),c22=divNearest(-b1*k2,n3);let k1=mod(k2-c12*a1-c22*a2,n3),k22=mod(-c12*b1-c22*b22,n3);const k1neg=k1>POW_2_128,k2neg=k22>POW_2_128;k1neg&&(k1=n3-k1);k2neg&&(k22=n3-k22);if(k1>POW_2_128||k22>POW_2_128)throw new Error("splitScalarEndo: Endomorphism failed, k="+k2);return{k1neg,k1,k2neg,k2:k22}}};groupLen=32;USE_ENDOMORPHISM=CURVE.a===_0n;ShaError=class extends Error{constructor(message){super(message)}};JacobianPoint=class _JacobianPoint{constructor(x2,y2,z2){this.x=x2;this.y=y2;this.z=z2}static fromAffine(p4){if(!(p4 instanceof Point))throw new TypeError("JacobianPoint#fromAffine: expected Point");return p4.equals(Point.ZERO)?_JacobianPoint.ZERO:new _JacobianPoint(p4.x,p4.y,_1n)}static toAffineBatch(points){const toInv=function invertBatch(nums,p4=CURVE.P){const scratch=new Array(nums.length),lastMultiplied=nums.reduce(((acc,num,i2)=>{if(num===_0n)return acc;scratch[i2]=acc;return mod(acc*num,p4)}),_1n),inverted=invert(lastMultiplied,p4);nums.reduceRight(((acc,num,i2)=>{if(num===_0n)return acc;scratch[i2]=mod(acc*scratch[i2],p4);return mod(acc*num,p4)}),inverted);return scratch}(points.map((p4=>p4.z)));return points.map(((p4,i2)=>p4.toAffine(toInv[i2])))}static normalizeZ(points){return _JacobianPoint.toAffineBatch(points).map(_JacobianPoint.fromAffine)}equals(other){assertJacPoint(other);const{x:X1,y:Y1,z:Z1}=this,{x:X2,y:Y2,z:Z2}=other,Z1Z1=mod(Z1*Z1),Z2Z2=mod(Z2*Z2),U1=mod(X1*Z2Z2),U2=mod(X2*Z1Z1),S1=mod(mod(Y1*Z2)*Z2Z2),S2=mod(mod(Y2*Z1)*Z1Z1);return U1===U2&&S1===S2}negate(){return new _JacobianPoint(this.x,mod(-this.y),this.z)}double(){const{x:X1,y:Y1,z:Z1}=this,A2=mod(X1*X1),B2=mod(Y1*Y1),C2=mod(B2*B2),x1b=X1+B2,D2=mod(_2n*(mod(x1b*x1b)-A2-C2)),E2=mod(_3n*A2),F2=mod(E2*E2),X3=mod(F2-_2n*D2),Y3=mod(E2*(D2-X3)-_8n*C2),Z3=mod(_2n*Y1*Z1);return new _JacobianPoint(X3,Y3,Z3)}add(other){assertJacPoint(other);const{x:X1,y:Y1,z:Z1}=this,{x:X2,y:Y2,z:Z2}=other;if(X2===_0n||Y2===_0n)return this;if(X1===_0n||Y1===_0n)return other;const Z1Z1=mod(Z1*Z1),Z2Z2=mod(Z2*Z2),U1=mod(X1*Z2Z2),U2=mod(X2*Z1Z1),S1=mod(mod(Y1*Z2)*Z2Z2),S2=mod(mod(Y2*Z1)*Z1Z1),H2=mod(U2-U1),r4=mod(S2-S1);if(H2===_0n)return r4===_0n?this.double():_JacobianPoint.ZERO;const HH=mod(H2*H2),HHH=mod(H2*HH),V2=mod(U1*HH),X3=mod(r4*r4-HHH-_2n*V2),Y3=mod(r4*(V2-X3)-S1*HHH),Z3=mod(Z1*Z2*H2);return new _JacobianPoint(X3,Y3,Z3)}subtract(other){return this.add(other.negate())}multiplyUnsafe(scalar){const P0=_JacobianPoint.ZERO;if("bigint"==typeof scalar&&scalar===_0n)return P0;let n3=normalizeScalar(scalar);if(n3===_1n)return this;if(!USE_ENDOMORPHISM){let p4=P0,d5=this;for(;n3>_0n;){n3&_1n&&(p4=p4.add(d5));d5=d5.double();n3>>=_1n}return p4}let{k1neg,k1,k2neg,k2}=endo.splitScalar(n3),k1p=P0,k2p=P0,d4=this;for(;k1>_0n||k2>_0n;){k1&_1n&&(k1p=k1p.add(d4));k2&_1n&&(k2p=k2p.add(d4));d4=d4.double();k1>>=_1n;k2>>=_1n}k1neg&&(k1p=k1p.negate());k2neg&&(k2p=k2p.negate());k2p=new _JacobianPoint(mod(k2p.x*endo.beta),k2p.y,k2p.z);return k1p.add(k2p)}precomputeWindow(W2){const windows=USE_ENDOMORPHISM?128/W2+1:256/W2+1,points=[];let p4=this,base=p4;for(let window2=0;window2>=shiftBy;if(wbits2>windowSize){wbits2-=maxNumber;n3+=_1n}const offset1=offset,offset2=offset+Math.abs(wbits2)-1,cond1=window2%2!=0,cond2=wbits2<0;0===wbits2?f4=f4.add(constTimeNegate(cond1,precomputes[offset1])):p4=p4.add(constTimeNegate(cond2,precomputes[offset2]))}return{p:p4,f:f4}}multiply(scalar,affinePoint){let point,fake,n3=normalizeScalar(scalar);if(USE_ENDOMORPHISM){const{k1neg,k1,k2neg,k2}=endo.splitScalar(n3);let{p:k1p,f:f1p}=this.wNAF(k1,affinePoint),{p:k2p,f:f2p}=this.wNAF(k2,affinePoint);k1p=constTimeNegate(k1neg,k1p);k2p=constTimeNegate(k2neg,k2p);k2p=new _JacobianPoint(mod(k2p.x*endo.beta),k2p.y,k2p.z);point=k1p.add(k2p);fake=f1p.add(f2p)}else{const{p:p4,f:f4}=this.wNAF(n3,affinePoint);point=p4;fake=f4}return _JacobianPoint.normalizeZ([point,fake])[0]}toAffine(invZ){const{x:x2,y:y2,z:z2}=this,is0=this.equals(_JacobianPoint.ZERO);null==invZ&&(invZ=is0?_8n:invert(z2));const iz1=invZ,iz2=mod(iz1*iz1),iz3=mod(iz2*iz1),ax2=mod(x2*iz2),ay2=mod(y2*iz3),zz=mod(z2*iz1);if(is0)return Point.ZERO;if(zz!==_1n)throw new Error("invZ was invalid");return new Point(ax2,ay2)}};JacobianPoint.BASE=new JacobianPoint(CURVE.Gx,CURVE.Gy,_1n);JacobianPoint.ZERO=new JacobianPoint(_0n,_1n,_0n);pointPrecomputes=new WeakMap;Point=class _Point{constructor(x2,y2){this.x=x2;this.y=y2}_setWindowSize(windowSize){this._WINDOW_SIZE=windowSize;pointPrecomputes.delete(this)}hasEvenY(){return this.y%_2n===_0n}static fromCompressedHex(bytes){const isShort=32===bytes.length,x2=bytesToNumber(isShort?bytes:bytes.subarray(1));if(!isValidFieldElement(x2))throw new Error("Point is not on curve");let y3=function sqrtMod(x2){const{P:P2}=CURVE,_6n=BigInt(6),_11n=BigInt(11),_22n=BigInt(22),_23n=BigInt(23),_44n=BigInt(44),_88n=BigInt(88),b22=x2*x2*x2%P2,b3=b22*b22*x2%P2,b6=pow2(b3,_3n)*b3%P2,b9=pow2(b6,_3n)*b3%P2,b11=pow2(b9,_2n)*b22%P2,b222=pow2(b11,_11n)*b11%P2,b44=pow2(b222,_22n)*b222%P2,b88=pow2(b44,_44n)*b44%P2,b176=pow2(b88,_88n)*b88%P2,b220=pow2(b176,_44n)*b44%P2,b223=pow2(b220,_3n)*b3%P2,t1=pow2(b223,_23n)*b222%P2,t22=pow2(t1,_6n)*b22%P2,rt=pow2(t22,_2n);if(rt*rt%P2!==x2)throw new Error("Cannot find square root");return rt}(weierstrass(x2));const isYOdd=(y3&_1n)===_1n;isShort?isYOdd&&(y3=mod(-y3)):!(1&~bytes[0])!==isYOdd&&(y3=mod(-y3));const point=new _Point(x2,y3);point.assertValidity();return point}static fromUncompressedHex(bytes){const x2=bytesToNumber(bytes.subarray(1,33)),y2=bytesToNumber(bytes.subarray(33,65)),point=new _Point(x2,y2);point.assertValidity();return point}static fromHex(hex){const bytes=ensureBytes(hex),len=bytes.length,header=bytes[0];if(32===len)return this.fromCompressedHex(bytes);if(33===len&&(2===header||3===header))return this.fromCompressedHex(bytes);if(65===len&&4===header)return this.fromUncompressedHex(bytes);throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`)}static fromPrivateKey(privateKey2){return _Point.BASE.multiply(normalizePrivateKey(privateKey2))}static fromSignature(msgHash,signature,recovery){const{r:r4,s:s2}=function normalizeSignature(signature){if(signature instanceof Signature){signature.assertValidity();return signature}try{return Signature.fromDER(signature)}catch(error){return Signature.fromCompact(signature)}}(signature);if(![0,1,2,3].includes(recovery))throw new Error("Cannot recover: invalid recovery bit");const h3=function truncateHash(hash2,truncateOnly=!1){const h3=function bits2int_2(bytes){const delta=8*bytes.length-8*groupLen,num=bytesToNumber(bytes);return delta>0?num>>BigInt(delta):num}(hash2);if(truncateOnly)return h3;const{n:n3}=CURVE;return h3>=n3?h3-n3:h3}(ensureBytes(msgHash)),{n:n3}=CURVE,radj=2===recovery||3===recovery?r4+n3:r4,rinv=invert(radj,n3),u1=mod(-h3*rinv,n3),u2=mod(s2*rinv,n3),prefix=1&recovery?"03":"02",R2=_Point.fromHex(prefix+numTo32bStr(radj)),Q2=_Point.BASE.multiplyAndAddUnsafe(R2,u1,u2);if(!Q2)throw new Error("Cannot recover signature: point at infinify");Q2.assertValidity();return Q2}toRawBytes(isCompressed=!1){return hexToBytes(this.toHex(isCompressed))}toHex(isCompressed=!1){const x2=numTo32bStr(this.x);return isCompressed?`${this.hasEvenY()?"02":"03"}${x2}`:`04${x2}${numTo32bStr(this.y)}`}toHexX(){return this.toHex(!0).slice(2)}toRawX(){return this.toRawBytes(!0).slice(1)}assertValidity(){const msg="Point is not on elliptic curve",{x:x2,y:y2}=this;if(!isValidFieldElement(x2)||!isValidFieldElement(y2))throw new Error(msg);const left=mod(y2*y2);if(mod(left-weierstrass(x2))!==_0n)throw new Error(msg)}equals(other){return this.x===other.x&&this.y===other.y}negate(){return new _Point(this.x,mod(-this.y))}double(){return JacobianPoint.fromAffine(this).double().toAffine()}add(other){return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine()}subtract(other){return this.add(other.negate())}multiply(scalar){return JacobianPoint.fromAffine(this).multiply(scalar,this).toAffine()}multiplyAndAddUnsafe(Q2,a2,b3){const P2=JacobianPoint.fromAffine(this),aP2=a2===_0n||a2===_1n||this!==_Point.BASE?P2.multiplyUnsafe(a2):P2.multiply(a2),bQ2=JacobianPoint.fromAffine(Q2).multiplyUnsafe(b3),sum2=aP2.add(bQ2);return sum2.equals(JacobianPoint.ZERO)?void 0:sum2.toAffine()}};Point.BASE=new Point(CURVE.Gx,CURVE.Gy);Point.ZERO=new Point(_0n,_0n);Signature=class _Signature{constructor(r4,s2){this.r=r4;this.s=s2;this.assertValidity()}static fromCompact(hex){const arr=isBytes(hex),name="Signature.fromCompact";if("string"!=typeof hex&&!arr)throw new TypeError(`${name}: Expected string or Uint8Array`);const str=arr?bytesToHex(hex):hex;if(128!==str.length)throw new Error(`${name}: Expected 64-byte hex`);return new _Signature(hexToNumber(str.slice(0,64)),hexToNumber(str.slice(64,128)))}static fromDER(hex){const arr=isBytes(hex);if("string"!=typeof hex&&!arr)throw new TypeError("Signature.fromDER: Expected string or Uint8Array");const{r:r4,s:s2}=function parseDERSignature(data){if(data.length<2||48!=data[0])throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);if(data[1]!==data.length-2)throw new Error("Invalid signature: incorrect length");const{data:r4,left:sBytes}=parseDERInt(data.subarray(2)),{data:s2,left:rBytesLeft}=parseDERInt(sBytes);if(rBytesLeft.length)throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);return{r:r4,s:s2}}(arr?hex:hexToBytes(hex));return new _Signature(r4,s2)}static fromHex(hex){return this.fromDER(hex)}assertValidity(){const{r:r4,s:s2}=this;if(!isWithinCurveOrder(r4))throw new Error("Invalid Signature: r must be 0 < r < n");if(!isWithinCurveOrder(s2))throw new Error("Invalid Signature: s must be 0 < s < n")}hasHighS(){const HALF=CURVE.n>>_1n;return this.s>HALF}normalizeS(){return this.hasHighS()?new _Signature(this.r,mod(-this.s,CURVE.n)):this}toDERRawBytes(){return hexToBytes(this.toDERHex())}toDERHex(){const sHex=sliceDER(numberToHexUnpadded(this.s)),rHex=sliceDER(numberToHexUnpadded(this.r)),sHexL=sHex.length/2,rHexL=rHex.length/2,sLen=numberToHexUnpadded(sHexL),rLen=numberToHexUnpadded(rHexL);return`30${numberToHexUnpadded(rHexL+sHexL+4)}02${rLen}${rHex}02${sLen}${sHex}`}toRawBytes(){return this.toDERRawBytes()}toHex(){return this.toDERHex()}toCompactRawBytes(){return hexToBytes(this.toCompactHex())}toCompactHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}};hexes=Array.from({length:256},((_,i2)=>i2.toString(16).padStart(2,"0")));asciis={_0:48,_9:57,A:65,F:70,a:97,f:102};POW_2_256=BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");SchnorrSignature=class _SchnorrSignature{constructor(r4,s2){this.r=r4;this.s=s2;this.assertValidity()}static fromHex(hex){const bytes=ensureBytes(hex);if(64!==bytes.length)throw new TypeError(`SchnorrSignature.fromHex: expected 64 bytes, not ${bytes.length}`);const r4=bytesToNumber(bytes.subarray(0,32)),s2=bytesToNumber(bytes.subarray(32,64));return new _SchnorrSignature(r4,s2)}assertValidity(){const{r:r4,s:s2}=this;if(!isValidFieldElement(r4)||!isWithinCurveOrder(s2))throw new Error("Invalid signature")}toHex(){return numTo32bStr(this.r)+numTo32bStr(this.s)}toRawBytes(){return hexToBytes(this.toHex())}};InternalSchnorrSignature=class{constructor(message,privateKey2,auxRand=utils.randomBytes()){if(null==message)throw new TypeError(`sign: Expected valid message, not "${message}"`);this.m=ensureBytes(message);const{x:x2,scalar}=this.getScalar(normalizePrivateKey(privateKey2));this.px=x2;this.d=scalar;this.rand=ensureBytes(auxRand);if(32!==this.rand.length)throw new TypeError("sign: Expected 32 bytes of aux randomness")}getScalar(priv){const point=Point.fromPrivateKey(priv),scalar=point.hasEvenY()?priv:CURVE.n-priv;return{point,scalar,x:point.toRawX()}}initNonce(d4,t0h){return numTo32b(d4^bytesToNumber(t0h))}finalizeNonce(k0h){const k0=mod(bytesToNumber(k0h),CURVE.n);if(k0===_0n)throw new Error("sign: Creation of signature failed. k is zero");const{point:R2,x:rx,scalar:k2}=this.getScalar(k0);return{R:R2,rx,k:k2}}finalizeSig(R2,k2,e3,d4){return new SchnorrSignature(R2.x,mod(k2+e3*d4,CURVE.n)).toRawBytes()}error(){throw new Error("sign: Invalid signature produced")}async calc(){const{m:m3,d:d4,px,rand}=this,tag2=utils.taggedHash,t3=this.initNonce(d4,await tag2(TAGS.aux,rand)),{R:R2,rx,k:k2}=this.finalizeNonce(await tag2(TAGS.nonce,t3,px,m3)),e3=schnorrChallengeFinalize(await tag2(TAGS.challenge,rx,px,m3)),sig=this.finalizeSig(R2,k2,e3,d4);await schnorrVerify(sig,m3,px)||this.error();return sig}calcSync(){const{m:m3,d:d4,px,rand}=this,tag2=utils.taggedHashSync,t3=this.initNonce(d4,tag2(TAGS.aux,rand)),{R:R2,rx,k:k2}=this.finalizeNonce(tag2(TAGS.nonce,t3,px,m3)),e3=schnorrChallengeFinalize(tag2(TAGS.challenge,rx,px,m3)),sig=this.finalizeSig(R2,k2,e3,d4);schnorrVerifySync(sig,m3,px)||this.error();return sig}};schnorr={Signature:SchnorrSignature,getPublicKey:function schnorrGetPublicKey(privateKey2){return Point.fromPrivateKey(privateKey2).toRawX()},sign:async function schnorrSign(msg,privKey,auxRand){return new InternalSchnorrSignature(msg,privKey,auxRand).calc()},verify:schnorrVerify,signSync:function schnorrSignSync(msg,privKey,auxRand){return new InternalSchnorrSignature(msg,privKey,auxRand).calcSync()},verifySync:schnorrVerifySync};Point.BASE._setWindowSize(8);crypto2={node:nodeCrypto,web:"object"==typeof self&&"crypto"in self?self.crypto:void 0};TAGS={challenge:"BIP0340/challenge",aux:"BIP0340/aux",nonce:"BIP0340/nonce"};TAGGED_HASH_PREFIXES={};utils={bytesToHex,hexToBytes,concatBytes,mod,invert,isValidPrivateKey(privateKey2){try{normalizePrivateKey(privateKey2);return!0}catch(error){return!1}},_bigintTo32Bytes:numTo32b,_normalizePrivateKey:normalizePrivateKey,hashToPrivateKey:hash2=>{hash2=ensureBytes(hash2);const minLen=groupLen+8;if(hash2.length1024)throw new Error("Expected valid bytes of private key as per FIPS 186");return numTo32b(mod(bytesToNumber(hash2),CURVE.n-_1n)+_1n)},randomBytes:(bytesLength=32)=>{if(crypto2.web)return crypto2.web.getRandomValues(new Uint8Array(bytesLength));if(crypto2.node){const{randomBytes}=crypto2.node;return Uint8Array.from(randomBytes(bytesLength))}throw new Error("The environment doesn't have randomBytes function")},randomPrivateKey:()=>utils.hashToPrivateKey(utils.randomBytes(groupLen+8)),precompute(windowSize=8,point=Point.BASE){const cached=point===Point.BASE?point:new Point(point.x,point.y);cached._setWindowSize(windowSize);cached.multiply(_3n);return cached},sha256:async(...messages)=>{if(crypto2.web){const buffer=await crypto2.web.subtle.digest("SHA-256",concatBytes(...messages));return new Uint8Array(buffer)}if(crypto2.node){const{createHash}=crypto2.node,hash2=createHash("sha256");messages.forEach((m3=>hash2.update(m3)));return Uint8Array.from(hash2.digest())}throw new Error("The environment doesn't have sha256 function")},hmacSha256:async(key2,...messages)=>{if(crypto2.web){const ckey=await crypto2.web.subtle.importKey("raw",key2,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),message=concatBytes(...messages),buffer=await crypto2.web.subtle.sign("HMAC",ckey,message);return new Uint8Array(buffer)}if(crypto2.node){const{createHmac}=crypto2.node,hash2=createHmac("sha256",key2);messages.forEach((m3=>hash2.update(m3)));return Uint8Array.from(hash2.digest())}throw new Error("The environment doesn't have hmac-sha256 function")},sha256Sync:void 0,hmacSha256Sync:void 0,taggedHash:async(tag2,...messages)=>{let tagP=TAGGED_HASH_PREFIXES[tag2];if(void 0===tagP){const tagH=await utils.sha256(Uint8Array.from(tag2,(c3=>c3.charCodeAt(0))));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag2]=tagP}return utils.sha256(tagP,...messages)},taggedHashSync:(tag2,...messages)=>{if("function"!=typeof _sha256Sync)throw new ShaError("sha256Sync is undefined, you need to set it");let tagP=TAGGED_HASH_PREFIXES[tag2];if(void 0===tagP){const tagH=_sha256Sync(Uint8Array.from(tag2,(c3=>c3.charCodeAt(0))));tagP=concatBytes(tagH,tagH);TAGGED_HASH_PREFIXES[tag2]=tagP}return _sha256Sync(tagP,...messages)},_JacobianPoint:JacobianPoint};Object.defineProperties(utils,{sha256Sync:{configurable:!1,get:()=>_sha256Sync,set(val2){_sha256Sync||(_sha256Sync=val2)}},hmacSha256Sync:{configurable:!1,get:()=>_hmacSha256Sync,set(val2){_hmacSha256Sync||(_hmacSha256Sync=val2)}}});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 defaultEndpointResolver2,createHttpAuthOptionFunctions,{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={};makeSocket=(url,onMessage)=>{const client={},init3=()=>{const socket=new WebSocket(url);socket.onclose=()=>{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])));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};sha12=async str=>strToSha1[str]||(strToSha1[str]=Array.from(new Uint8Array(await crypto.subtle.digest("SHA-1",encodeBytes(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"]);encrypt3=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)))};decrypt3=async(keyP,raw)=>{const[iv,c3]=raw.split("$");return decodeBytes(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(iv.split(","))},await keyP,unpack(c3)))};peer_default=(initiator,{rtcConfig,rtcPolyfill,turnConfig})=>{const pc=new(rtcPolyfill||RTCPeerConnection)({iceServers:defaultIceServers.concat(turnConfig||[]),...rtcConfig}),handlers2={};let makingOffer=!1,isSettingRemoteAnswerPending=!1,dataChannel=null;const setupDataChannel=channel=>{channel.binaryType="arraybuffer";channel.bufferedAmountLowThreshold=65535;channel.onmessage=e3=>{var _a8;return null==(_a8=handlers2.data)?void 0:_a8.call(handlers2,e3.data)};channel.onopen=()=>{var _a8;return null==(_a8=handlers2.connect)?void 0:_a8.call(handlers2)};channel.onclose=()=>{var _a8;return null==(_a8=handlers2.close)?void 0:_a8.call(handlers2)};channel.onerror=err2=>{var _a8;return null==(_a8=handlers2.error)?void 0:_a8.call(handlers2,err2)}},waitForIceGathering=pc2=>Promise.race([new Promise((res2=>{const checkState=()=>{if("complete"===pc2.iceGatheringState){pc2.removeEventListener("icegatheringstatechange",checkState);res2()}};pc2.addEventListener("icegatheringstatechange",checkState);checkState()})),new Promise((res2=>setTimeout(res2,5e3)))]).then((()=>({type:pc2.localDescription.type,sdp:pc2.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));if(initiator){dataChannel=pc.createDataChannel("data");setupDataChannel(dataChannel)}else pc.ondatachannel=({channel})=>{dataChannel=channel;setupDataChannel(channel)};pc.onnegotiationneeded=async()=>{var _a8,_b4;try{makingOffer=!0;await pc.setLocalDescription();const offer=await waitForIceGathering(pc);null==(_a8=handlers2.signal)||_a8.call(handlers2,offer)}catch(err2){null==(_b4=handlers2.error)||_b4.call(handlers2,err2)}finally{makingOffer=!1}};pc.onconnectionstatechange=()=>{var _a8;["disconnected","failed","closed"].includes(pc.connectionState)&&(null==(_a8=handlers2.close)||_a8.call(handlers2))};pc.ontrack=e3=>{var _a8,_b4;null==(_a8=handlers2.track)||_a8.call(handlers2,e3.track,e3.streams[0]);null==(_b4=handlers2.stream)||_b4.call(handlers2,e3.streams[0])};pc.onremovestream=e3=>{var _a8;return null==(_a8=handlers2.stream)?void 0:_a8.call(handlers2,e3.stream)};initiator&&(pc.canTrickleIceCandidates||pc.onnegotiationneeded());return{created:Date.now(),connection:pc,get channel(){return dataChannel},get isDead(){return"closed"===pc.connectionState},async signal(sdp){var _a8,_b4,_c3;if("open"!==(null==dataChannel?void 0:dataChannel.readyState)||(null==(_a8=sdp.sdp)?void 0:_a8.includes("a=rtpmap")))try{if("offer"===sdp.type){if(makingOffer||"stable"!==pc.signalingState&&!isSettingRemoteAnswerPending){if(initiator)return;await all([pc.setLocalDescription({type:"rollback"}),pc.setRemoteDescription(sdp)])}else await pc.setRemoteDescription(sdp);await pc.setLocalDescription();const answer=await waitForIceGathering(pc);null==(_b4=handlers2.signal)||_b4.call(handlers2,answer);return answer}if("answer"===sdp.type){isSettingRemoteAnswerPending=!0;try{await pc.setRemoteDescription(sdp)}finally{isSettingRemoteAnswerPending=!1}}}catch(err2){null==(_c3=handlers2.error)||_c3.call(handlers2,err2)}},sendData:data=>dataChannel.send(data),destroy:()=>{null==dataChannel||dataChannel.close();pc.close();makingOffer=!1;isSettingRemoteAnswerPending=!1},setHandlers:newHandlers=>Object.assign(handlers2,newHandlers),offerPromise:initiator?new Promise((res2=>handlers2.signal=sdp=>{"offer"===sdp.type&&res2(sdp)})):Promise.resolve(),addStream:stream=>stream.getTracks().forEach((track=>pc.addTrack(track,stream))),removeStream:stream=>pc.getSenders().filter((sender=>stream.getTracks().includes(sender.track))).forEach((sender=>pc.removeTrack(sender))),addTrack:(track,stream)=>pc.addTrack(track,stream),removeTrack:track=>{const sender=pc.getSenders().find((s2=>s2.track===track));sender&&pc.removeTrack(sender)},replaceTrack:(oldTrack,newTrack)=>{const sender=pc.getSenders().find((s2=>s2.track===oldTrack));if(sender)return sender.replaceTrack(newTrack)}}};defaultIceServers=[...alloc(3,((_,i2)=>`stun:stun${i2||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((url=>({urls:url})));TypedArray=Object.getPrototypeOf(Uint8Array);chunkSize=16384-(payloadIndex=1+(progressIndex=1+13));internalNs=ns=>"@_"+ns;room_default=(onPeer,onPeerLeave,onSelfLeave)=>{const peerMap={},actions={},actionsCache={},pendingTransmissions={},pendingPongs={},pendingStreamMetas={},pendingTrackMetas={},listeners={onPeerJoin:noOp,onPeerLeave:noOp,onPeerStream:noOp,onPeerTrack:noOp},iterate2=(targets,f4)=>(targets?Array.isArray(targets)?targets:[targets]:keys(peerMap)).flatMap((id=>{const peer=peerMap[id];if(!peer){console.warn(`Trystero: no peer with id ${id} found`);return[]}return f4(id,peer)})),exitPeer=id=>{if(peerMap[id]){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])},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=>((id,data)=>{var _a8,_b4;const buffer=new Uint8Array(data),type=decodeBytes(buffer.subarray(0,12)).replaceAll("\0",""),[nonce]=buffer.subarray(12,13),[tag2]=buffer.subarray(13,progressIndex),[progress]=buffer.subarray(progressIndex,payloadIndex),payload=buffer.subarray(payloadIndex),isLast=!!(1&tag2),isMeta=!!(2&tag2),isBinary=!!(4&tag2),isJson=!!(8&tag2);if(!actions[type]){console.warn(`Trystero: received message with unregistered type (${type})`);return}pendingTransmissions[id]||(pendingTransmissions[id]={});(_a8=pendingTransmissions[id])[type]||(_a8[type]={});const target=(_b4=pendingTransmissions[id][type])[nonce]||(_b4[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)}})(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:err2=>{console.error(err2);exitPeer(id)}});listeners.onPeerJoin(id)}}));getPing(((_,id)=>sendPong("",id)));getPong(((_,id)=>{var _a8;null==(_a8=pendingPongs[id])||_a8.call(pendingPongs);delete pendingPongs[id]}));getSignal(((sdp,id)=>{var _a8;return null==(_a8=peerMap[id])?void 0:_a8.signal(sdp)}));getStreamMeta(((meta,id)=>pendingStreamMetas[id]=meta));getTrackMeta(((meta,id)=>pendingTrackMetas[id]=meta));getLeave(((_,id)=>exitPeer(id)));isBrowser&&addEventListener("beforeunload",leave);return{makeAction,leave,ping:async id=>{if(!id)throw mkErr("ping() must be called with target peer ID");const start=Date.now();sendPing("",id);await new Promise((res2=>pendingPongs[id]=res2));return Date.now()-start},getPeers:()=>fromEntries(entries(peerMap).map((([id,peer])=>[id,peer.connection]))),addStream:(stream,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendStreamMeta(meta,id);peer.addStream(stream)})),removeStream:(stream,targets)=>iterate2(targets,((_,peer)=>peer.removeStream(stream))),addTrack:(track,stream,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendTrackMeta(meta,id);peer.addTrack(track,stream)})),removeTrack:(track,targets)=>iterate2(targets,((_,peer)=>peer.removeTrack(track))),replaceTrack:(oldTrack,newTrack,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendTrackMeta(meta,id);peer.replaceTrack(oldTrack,newTrack)})),onPeerJoin:f4=>listeners.onPeerJoin=f4,onPeerLeave:f4=>listeners.onPeerLeave=f4,onPeerStream:f4=>listeners.onPeerStream=f4,onPeerTrack:f4=>listeners.onPeerTrack=f4}};strategy_default=({init:init3,subscribe:subscribe2,announce})=>{const occupiedRooms={};let initPromises,offerPool,offerCleanupTimer,didInit=!1;return(config,roomId,onJoinError)=>{var _a8;const{appId}=config;if(null==(_a8=occupiedRooms[appId])?void 0:_a8[roomId])return occupiedRooms[appId][roomId];const pendingOffers={},connectedPeers={},rootTopicPlaintext=topicPath("Trystero",appId,roomId),rootTopicP=sha12(rootTopicPlaintext),selfTopicP=sha12(topicPath(rootTopicPlaintext,selfId)),key2=genKey(config.password||"",appId,roomId),withKey=f4=>async signal=>({type:signal.type,sdp:await f4(key2,signal.sdp)}),toPlain=withKey(decrypt3),toCipher=withKey(encrypt3),makeOffer=()=>peer_default(!0,config),connectPeer=(peer,peerId,relayId)=>{var _a9;if(connectedPeers[peerId])connectedPeers[peerId]!==peer&&peer.destroy();else{connectedPeers[peerId]=peer;onPeerConnect(peer,peerId);null==(_a9=pendingOffers[peerId])||_a9.forEach(((peer2,i2)=>{i2!==relayId&&peer2.destroy()}));delete pendingOffers[peerId]}},disconnectPeer=(peer,peerId)=>{connectedPeers[peerId]===peer&&delete connectedPeers[peerId]},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});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)}const announceIntervals=initPromises.map((()=>5333)),announceTimeouts=[],unsubFns=initPromises.map((async(relayP,i2)=>{return subscribe2(await relayP,await rootTopicP,await selfTopicP,(relayId=i2,async(topic,msg,signalPeer)=>{var _a9,_b4,_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==(_b4=pendingOffers[peerId])?void 0:_b4[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([sha12(topicPath(rootTopicPlaintext,peerId)),peer2.signal(plainOffer)]);signalPeer(topic2,toJson({peerId:selfId,answer:await toCipher(answer2)}))}else if(answer){let plainAnswer;try{plainAnswer=await toPlain(answer)}catch(e3){handleJoinError(peerId,"answer");return}if(peer){peer.setHandlers({connect:()=>connectPeer(peer,peerId,relayId),close:()=>disconnectPeer(peer,peerId)});peer.signal(plainAnswer)}else{const peer2=null==(_c3=pendingOffers[peerId])?void 0:_c3[relayId];peer2&&!peer2.isDead&&peer2.signal(plainAnswer)}}}else{if(null==(_a9=pendingOffers[peerId])?void 0:_a9[relayId])return;const[[{peer:peer2,offer:offer2}],topic2]=await all([getOffers(1),sha12(topicPath(rootTopicPlaintext,peerId))]);pendingOffers[peerId]||(pendingOffers[peerId]=[]);pendingOffers[peerId][relayId]=peer2;setTimeout((()=>((peerId,relayId)=>{var _a9;if(connectedPeers[peerId])return;const offer=null==(_a9=pendingOffers[peerId])?void 0:_a9[relayId];if(offer){delete pendingOffers[peerId][relayId];offer.destroy()}})(peerId,relayId)),.9*announceIntervals[relayId]);peer2.setHandlers({connect:()=>connectPeer(peer2,peerId,relayId),close:()=>disconnectPeer(peer2,peerId)});signalPeer(topic2,toJson({peerId:selfId,offer:offer2}))}}),getOffers);var relayId}));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)}))}};clients={};privateKey=utils.randomPrivateKey();publicKey=toHex(schnorr.getPublicKey(privateKey));subIdToTopic={};msgHandlers={};kindCache={};now2=()=>Math.floor(Date.now()/1e3);topicToKind=topic=>{var _a8;return null!=(_a8=kindCache[topic])?_a8:kindCache[topic]=strToNum(topic,1e4)+2e4};createEvent=async(topic,content)=>{const payload={kind:topicToKind(topic),content,pubkey:publicKey,created_at:now2(),tags:[["x",topic]]},id=toHex(new Uint8Array(await crypto.subtle.digest("SHA-256",encodeBytes(toJson([0,payload.pubkey,payload.created_at,payload.kind,payload.tags,payload.content])))));return toJson(["EVENT",{...payload,id,sig:toHex(await schnorr.sign(id,privateKey))}])};subscribe=(subId,topic)=>{subIdToTopic[subId]=topic;return toJson(["REQ",subId,{kinds:[topicToKind(topic)],since:now2(),["#x"]:[topic]}])};unsubscribe=subId=>{delete subIdToTopic[subId];return toJson(["CLOSE",subId])};joinRoom=strategy_default({init:config=>getRelays(config,defaultRelayUrls,5,!0).map((url=>{const client=makeSocket(url,(data=>{var _a8;const[msgType,subId,payload,relayMsg]=fromJson(data);if("EVENT"===msgType)null==(_a8=msgHandlers[subId])||_a8.call(msgHandlers,subIdToTopic[subId],payload.content);else{const prefix=`Trystero: relay failure from ${client.url} - `;"NOTICE"===msgType?console.warn(prefix+subId):"OK"!==msgType||payload||console.warn(prefix+relayMsg)}}));clients[url]=client;return client.ready})),subscribe:(client,rootTopic,selfTopic,onMessage)=>{const rootSubId=genId(64),selfSubId=genId(64);msgHandlers[rootSubId]=msgHandlers[selfSubId]=(topic,data)=>onMessage(topic,data,(async(peerTopic,signal)=>client.send(await createEvent(peerTopic,signal))));client.send(subscribe(rootSubId,rootTopic));client.send(subscribe(selfSubId,selfTopic));return()=>{client.send(unsubscribe(rootSubId));client.send(unsubscribe(selfSubId));delete msgHandlers[rootSubId];delete msgHandlers[selfSubId]}},announce:async(client,rootTopic)=>client.send(await createEvent(rootTopic,toJson({peerId:selfId})))});socketGetter(clients);defaultRelayUrls=["eu.purplerelay.com","ftp.halifax.rwth-aachen.de/nostr","multiplexer.huszonegy.world","nostr.cool110.xyz","nostr.data.haus","nostr.grooveix.com","nostr.huszonegy.world","nostr.mom","nostr.sathoarder.com","nostr.vulpem.com","relay.fountain.fm","relay.nostraddress.com","relay.nostromo.social","relay.snort.social","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(key2){return`${this._prefix}-${key2}`}async get(key2){if(this._cache.has(key2))return this._cache.get(key2);const value=await this._store.get(this.addPrefix(key2));void 0!==value&&this._cache.set(key2,value);return value}async set(key2,value){try{const ret=await this._store.set(this.addPrefix(key2),value);this._cache.set(key2,value);return ret}catch(e3){this._cache.delete(key2);throw e3}}async delete(key2){try{const ret=await this._store.delete(this.addPrefix(key2));this._cache.delete(key2);return ret}catch(e3){this._cache.delete(key2);throw e3}}async has(key2){return!!this._cache.has(key2)||(await this._store.keys(this.addPrefix(key2),key2)).length>0}};TrysteroReplicatorP2PClient=class{constructor(server,connectedPeerId){this._prevSeq=0;this.waitingInvocations=new Map;this.invocationTimeouts=new Map;this._server=server;this._connectedPeerId=connectedPeerId;this._remoteDB=this._bindRemoteDB()}get remoteDB(){return this._remoteDB}_bindRemoteDB(){return{info:this.bindRemoteFunction("info"),changes:this.bindRemoteFunction("changes"),revsDiff:this.bindRemoteFunction("revsDiff"),bulkDocs:this.bindRemoteFunction("bulkDocs"),bulkGet:this.bindRemoteFunction("bulkGet"),put:this.bindRemoteFunction("put"),get:this.bindRemoteFunction("get")}}get __send(){var _a8;return null==(_a8=this._server)?void 0:_a8.__send.bind(this._server)}generateNewSeq(){const seq=Math.floor(115*Math.random())+1+this._prevSeq;if(!this.waitingInvocations.has(seq)){this._prevSeq=seq%~~(Number.MAX_SAFE_INTEGER/2);return seq}return this.generateNewSeq()}_sendRPC(type,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");const seq=this.generateNewSeq(),p4=promiseWithResolver();this.waitingInvocations.set(seq,p4);const request2={type,direction:"request",seq,args};timeout&&timeout>0&&this.invocationTimeouts.set(seq,setTimeout((()=>{if(this.waitingInvocations.has(seq)){this.waitingInvocations.delete(seq);p4.reject(new Error(`Invocation Timed out: ${type} (${seq}) (Timeout: ${timeout}ms)`))}this.invocationTimeouts.delete(seq)}),timeout));this.__send(request2,this._connectedPeerId);return p4.promise}__onResponse(data){const seq=data.seq,type=data.type;if(this.invocationTimeouts.has(seq)){clearTimeout(this.invocationTimeouts.get(seq));this.invocationTimeouts.delete(seq)}const p4=this.waitingInvocations.get(seq);if(p4){this.waitingInvocations.delete(seq);if(data.error){p4.reject(data.error);Logger(`Invoking remote function [ DONE] : ${type} (${seq}) : (Error)`,LOG_LEVEL_VERBOSE)}else p4.resolve(data.data)}else Logger(`Invoking remote function [ERROR] : ${type} (${seq}) : No Handler left. Possibly timed out`,LOG_LEVEL_VERBOSE)}bindRemoteFunction(type,timeout=3e4){return async(...args)=>{if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(type,args,timeout)}}async invokeRemoteFunction(type,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(type,args,timeout)}bindRemoteObjectFunctions(key2,timeout=3e4){return async(...args)=>{if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(`${key2.toString()}`,args,timeout)}}async invokeRemoteObjectFunction(key2,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(`${key2.toString()}`,args,timeout)}close(){this._remoteDB=void 0;this._server=void 0}};EVENT_SERVER_STATUS="p2p-server-status";EVENT_REQUEST_STATUS="p2p-request-status";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 Refiner({evaluation:settings=>{var _a8;return`${null!=(_a8=null==settings?void 0:settings.P2P_AutoAcceptingPeers)?_a8:""}`.split(",").map((e3=>e3.trim())).filter((e3=>!!e3)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}});this._shouldDenyPeers=new Refiner({evaluation:settings=>{var _a8;return`${null!=(_a8=null==settings?void 0:settings.P2P_AutoDenyingPeers)?_a8:""}`.split(",").map((e3=>e3.trim())).filter((e3=>!!e3)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}});this.activePeer=new Map;this._env=env;this._serverPeerId=_serverPeerId;eventHub.onEvent("platform-unloaded",(()=>{this.shutdown()}));this.acceptedPeers=new StoredMapLike(this._env.simpleStore,"p2p-device-decisions")}get isDisposed(){return!this._room}get isServing(){return void 0!==this._room}async ensureLeaved(){var _a8;if(this._room){try{await(null==(_a8=this._room)?void 0:_a8.leave())}catch(ex){Logger("Some error has been occurred while leaving the room, but possibly can be ignored",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}this._room=void 0;eventHub.emitEvent("p2p-disconnected")}}async setRoom(room){var _a8;await(null==(_a8=this._room)?void 0:_a8.leave());this._room=room}async shutdown(){try{await this.close();await this.ensureLeaved()}catch(ex){Logger("Some error has been occurred while shutting down the server",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}}async dispatchConnectionStatus(){const adsTasks=[...this.knownAdvertisements].map((async e3=>{const isAccepted2=await this.acceptedPeers.get(e3.name),isTemporaryAccepted=this.temporaryAcceptedPeers.get(e3.peerId);return{...e3,isAccepted:isAccepted2,isTemporaryAccepted}})),ads=await Promise.all(adsTasks);eventHub.emitEvent(EVENT_SERVER_STATUS,{isConnected:this.isServing,knownAdvertisements:ads,serverPeerId:this.serverPeerId})}async makeDecision(decision){decision.decision?decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!0):await this.acceptedPeers.set(decision.name,!0):decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!1):await this.acceptedPeers.set(decision.name,!1);await this.dispatchConnectionStatus()}async revokeDecision(decision){this.temporaryAcceptedPeers.delete(decision.peerId);await this.acceptedPeers.delete(decision.name);await this.dispatchConnectionStatus()}get room(){return this._room}get serverPeerId(){return this._serverPeerId}get db(){return this._env.db}get confirm(){return this._env.confirm}get settings(){return this._env.settings}get isEnabled(){return this.settings.P2P_Enabled}get deviceInfo(){return{currentPeerId:this._serverPeerId,name:this._env.deviceName,platform:this._env.platform,version:"0.0.0"}}sendAdvertisement(peerId){if(!this.isEnabled)return;const devInfo=this.deviceInfo,data={peerId:devInfo.currentPeerId,name:devInfo.name,platform:devInfo.platform};if(this._sendAdvertisement){Logger(`peerId: ${this.serverPeerId} Sending Advertisement to ${null!=peerId?peerId:"All"}`,LOG_LEVEL_VERBOSE);this._sendAdvertisement(data,peerId)}}get knownAdvertisements(){return[...this._knownAdvertisements.values()]}onAdvertisement(data,peerId){if(this.isEnabled){Logger(`Advertisement from ${peerId}`,LOG_LEVEL_VERBOSE);if(peerId!==this.serverPeerId&&data.peerId!==this.serverPeerId&&data.name!==this.deviceInfo.name&&data.peerId===peerId){this._knownAdvertisements.set(peerId,data);this.dispatchConnectionStatus();eventHub.emitEvent("p2p-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("p2p-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=function createHostingDB(env){let db=env.db;return{info:()=>db.info(),changes:options=>db.changes(options),revsDiff:diff=>db.revsDiff(diff),bulkDocs:(docs,options)=>db.bulkDocs(docs,options),bulkGet:options=>db.bulkGet(options),put:(doc,options)=>db.put(doc,options),get:(id,options)=>db.get(id,options),_stopHosting:()=>{db=void 0}}}(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)),room=joinRoom({relayUrls:relays,appId:this.settings.P2P_AppID,password:passphrase},this.settings.P2P_roomID,(error=>{Logger("Some error has been occurred while connecting the signalling server.",LOG_LEVEL_INFO);Logger(`Error: ${JSON.stringify(error)}`,LOG_LEVEL_INFO);this.ensureLeaved()}));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((key2=>{if(key2.toString().startsWith("_"))return;const func=obj[key2].bind(obj);this.assignedFunctions.set(key2.toString(),func)}))}__onResponse(data,peerId){const peer=this.clients.get(peerId);peer?peer.__onResponse(data):Logger(`Response from unknown peer ${peerId}`,LOG_LEVEL_VERBOSE)}async __onRequest(data,peerId){try{const func=this.assignedFunctions.get(data.type);if("function"!=typeof func)throw new Error(`Cannot serve function ${data.type}, no function provided or I am only a client`);const r4=await Promise.resolve(func.apply(this,data.args));await this.__send({type:data.type,seq:data.seq,direction:"response",data:r4},peerId)}catch(e3){if(e3 instanceof ResponsePreventedError){Logger(`Serving function: [FAILED] ${data.type}: Response prevented.`,LOG_LEVEL_VERBOSE);return}Logger(`Serving function: [FAILED] ${data.type} sending back the failure information`,LOG_LEVEL_VERBOSE);Logger(e3 instanceof Error?e3.message:e3,LOG_LEVEL_VERBOSE);await this.__send({type:data.type,seq:data.seq,direction:"response",data:void 0,error:e3},peerId)}}async close(){var _a8,_b4;this.assignedFunctions.clear();const peers=null!=(_b4=null==(_a8=this.room)?void 0:_a8.getPeers())?_b4:{};this.clients.forEach((client=>client.close()));this.clients.clear();for(const[,peer]of Object.entries(peers))peer.close();await this.ensureLeaved();this._knownAdvertisements.clear();await this.dispatchConnectionStatus()}getConnection(peerId){if(this.clients.has(peerId))return this.clients.get(peerId);if(!this._knownAdvertisements.has(peerId))throw new Error(`Unknown Peer ${peerId}`);const client=new TrysteroReplicatorP2PClient(this,peerId);this.clients.set(peerId,client);return client}};p=promiseWithResolver();instance=void 0;eventHub.onceEvent("platform-unloaded",(()=>{instance=void 0;p.resolve(void 0)}));replicatorInstanceGetter=()=>{};LiveSyncTrysteroReplicator=class extends LiveSyncAbstractReplicator{terminateSync(){}async openReplication(setting,keepAlive,showResult,ignoreCleanLock){const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,r4=await this.getP2PConnection(logLevel);if(!r4)return!1;await r4.replicateFromCommand(showResult)}tryConnectRemote(setting,showResult){return Promise.resolve(!1)}replicateAllToServer(setting,showingNotice,sendChunksInBulkDisabled){return Promise.resolve(!1)}async openP2P(logLevel){const r4=getReplicatorInstance();if(!r4){Logger($msg("P2P.ReplicatorInstanceMissing"),logLevel);return!1}await r4.open();return r4}async getP2PConnection(logLevel){const r4=getReplicatorInstance();if(!r4){Logger($msg("P2P.ReplicatorInstanceMissing"),logLevel);return!1}await r4.makeSureOpened();return r4}async selectPeer(settingPeerName,r4,logLevel){var _a8,_b4,_c3,_d2,_e2;const knownPeersOrg=null!=(_b4=null==(_a8=r4.server)?void 0:_a8.knownAdvertisements)?_b4:[];let knownPeers;if(0!=knownPeersOrg.length)knownPeers=knownPeersOrg;else{Logger($msg("P2P.NoKnownPeers"),logLevel);await Promise.race([delay(5e3),eventHub.waitFor("p2p-advertisement-received")]);knownPeers=null!=(_d2=null==(_c3=r4.server)?void 0:_c3.knownAdvertisements)?_d2:[]}const message="Rebuild from which peer?"+(settingPeerName?"\n [*] indicates the peer you have selected before.":""),confirm=await getConfirmInstance(),options=[...knownPeers.map((e3=>`${e3.name} ${e3.name==settingPeerName?"[*]":""} (${e3.peerId})`)),"Refresh List","Cancel"],selected=await confirm.askSelectStringDialogue(message,options,{title:"Select a peer to fetch from",defaultAction:"Refresh List"});if(!selected||"Cancel"==selected)return!1;if("Refresh List"==selected){await Promise.race([delay(1e3),eventHub.waitFor("p2p-advertisement-received")]);return this.selectPeer(settingPeerName,r4,logLevel)}const selectedPeerName=selected.split(" ")[0],peerId=null==(_e2=knownPeers.find((e3=>e3.name==selectedPeerName)))?void 0:_e2.peerId;if(!peerId){Logger(`Failed to find peerId for ${selectedPeerName}`,logLevel);return!1}return peerId}async tryUntilSuccess(func,repeat,logLevel){if(!await getConfirmInstance()){Logger("Cannot find confirm instance.",logLevel);return Promise.reject("Cannot find confirm instance.")}let result;for(;!result;)for(let i2=0;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{instance3.clearOnSetup()}}closeReplication(){}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)}constructor(env){super(env);this.env=env}};__export({},{CBC:()=>CBC_exports});__export(CBC_exports={},{SALT_LENGTH:()=>SALT_LENGTH,SALT_PREFIX:()=>SALT_PREFIX,decryptCBC:()=>decryptCBC,encryptCBC:()=>encryptCBC,generateIV:()=>generateIV,generateOpenSSLCompatIvKey:()=>generateOpenSSLCompatIvKey,passphraseToKeyMaterial:()=>passphraseToKeyMaterial});KEY_LENGTH=32;ALGORITHM_NAME="AES-CBC";SALT_PREFIX=new Uint8Array([83,97,108,116,101,100,95,95]);SALT_LENGTH=8;TrysteroReplicator=class{constructor(env){this._onSetup=!1;this.lastSeq="";this._isBroadcasting=!1;this.availableReplicationPairs=new Set;this._replicateToPeers=new Set;this._replicateFromPeers=new Set;this._watchingPeers=new Set;this._env=env;try{if(!this.settings.P2P_Enabled){Logger("P2P is not enabled",LOG_LEVEL_VERBOSE);return}if(!this.settings.P2P_AppID)throw new Error("P2P App ID is not provided. We need it to establish the P2P connection");if(!this.settings.P2P_roomID||!this.settings.P2P_passphrase)throw new Error("Room ID and/or P2P Passphrase have not provided. We need them to establish the P2P connection");if(!this.settings.P2P_relays||0===this.settings.P2P_relays.length)throw new Error("No relay URIs provided. We need them to establish the P2P connection");this.server=new TrysteroReplicatorP2PServer(env)}catch(e3){Logger(e3 instanceof Error?e3.message:"Error while creating TrysteroReplicator",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);throw e3}}replicationStatus(){return{}}get settings(){return this._env.settings}get db(){return this._env.db}get deviceName(){return this._env.deviceName}get platform(){return this._env.platform}get confirm(){return this._env.confirm}async close(){var _a8;this.requestStatus();await(null==(_a8=this.server)?void 0:_a8.shutdown());this._replicateFromPeers.clear();this._replicateToPeers.clear();this._watchingPeers.clear();this.requestStatus()}async open(){var _a8;await(null==(_a8=this.server)?void 0:_a8.start([this.getCommands()]));this.dispatchStatus();this.settings.P2P_AutoBroadcast&&this.enableBroadcastChanges()}async makeSureOpened(){var _a8;(null==(_a8=this.server)?void 0:_a8.isServing)||await this.open()}get autoSyncPeers(){return this.settings.P2P_AutoSyncPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3.length>0)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}get autoWatchPeers(){return this.settings.P2P_AutoWatchPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3.length>0)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}async onNewPeer(peer){const peerName=peer.name;this.autoSyncPeers.some((e3=>e3.test(peerName)))&&await this.sync(peer.peerId);this.autoWatchPeers.some((e3=>e3.test(peerName)))&&this.watchPeer(peer.peerId)}onPeerLeaved(peerId){this.unwatchPeer(peerId)}setOnSetup(){this._onSetup=!0}clearOnSetup(){this._onSetup=!1}async getTweakSettings(fromPeerId){var _a8;const allSettings=JSON.parse(JSON.stringify(this.settings));for(const key2 in allSettings)"encrypt"!=key2&&("passphrase"!=key2?key2 in TweakValuesShouldMatchedTemplate||delete allSettings[key2]:allSettings[key2]=await getHashedStringWithCurrentTime(null!=(_a8=allSettings[key2])?_a8:""));return allSettings}getCommands(){return{reqSync:async fromPeerId=>this._onSetup?{error:new Error("The setup is in progress")}:await this.replicateFrom(fromPeerId),"!reqAuth":async fromPeerId=>{var _a8;return await(null==(_a8=this.server)?void 0:_a8.isAcceptablePeer(fromPeerId))},getTweakSettings:async fromPeerId=>await this.getTweakSettings(fromPeerId),onProgress:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};await this.onUpdateDatabase(fromPeerId)},getAllConfig:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};const passphrase=await skipIfDuplicated(`getAllConfig-${fromPeerId}`,(async()=>await this.confirm.askString("Passphrase required",$msg("P2P.AskPassphraseForShare"),"something you only know",!0))),setting={...this.settings,configPassphraseStore:"",encryptedCouchDBConnection:"",encryptedPassphrase:"",pluginSyncExtendedSetting:{}};if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.",LOG_LEVEL_NOTICE);return encrypt(JSON.stringify(Object.fromEntries(Object.entries(setting).map((([key2,value])=>[key2,"******".repeat(Math.ceil(10*Math.random())+2)])))),Math.random().toString(36).substring(7),!1)}return encrypt(JSON.stringify(setting),passphrase.trim(),!1)},onProgressAcknowledged:async(fromPeerId,info3)=>{try{await this.onProgressAcknowledged(fromPeerId,info3)}catch(e3){Logger("Error while acknowledging the progress",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}},getIsBroadcasting:()=>Promise.resolve(this._isBroadcasting),requestBroadcasting:async peerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};if(this._isBroadcasting)return!0;"yes"===await skipIfDuplicated(`requested-${peerId}`,(async()=>await this.confirm.askYesNoDialog("The remote peer requested to broadcast the changes. Do you want to allow it?",{defaultOption:"No"})))&&this.enableBroadcastChanges()}}}async requestAuthenticate(peerId){if(!this.server)return!1;try{const connection=this.server.getConnection(peerId),selfPeerId=this.server.serverPeerId;return await connection.invokeRemoteObjectFunction("!reqAuth",[selfPeerId],2e4)}catch(e3){Logger("Error while requesting authentication",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async selectPeer(){if(!this.server)return!1;const knownPeers=this.server.knownAdvertisements;if(0===knownPeers.length){Logger("No known peers",LOG_LEVEL_VERBOSE);return!1}const peers=[...Object.entries(knownPeers)].map((([peerId,info3])=>`${info3.peerId} : (${info3.name})`)),selectedPeer=await this.confirm.askSelectString("Select a peer to replicate",peers);return!!selectedPeer&&selectedPeer.split(" ")[0]}async requestSynchroniseToPeer(peerId){await delay(25);if(!this.server)throw new Error("Server is not available");const conn=this.server.getConnection(peerId);return await conn.invokeRemoteFunction("reqSync",[this.server.serverPeerId],0)}async requestSynchroniseToAllAvailablePeers(){await scheduleOnceIfDuplicated("requestSynchroniseToAllAvailablePeers",(async()=>{await delay(25);const replications=[...this.availableReplicationPairs].map((peerId=>this.requestSynchroniseToPeer(peerId)));await Promise.all(replications)}))}dispatchStatus(){eventHub.emitEvent(EVENT_P2P_REPLICATOR_STATUS,{isBroadcasting:this._isBroadcasting,replicatingTo:[...this._replicateToPeers],replicatingFrom:[...this._replicateFromPeers],watchingPeers:[...this._watchingPeers]})}requestStatus(){var _a8;this.dispatchStatus();null==(_a8=this.server)||_a8.dispatchConnectionStatus()}disableBroadcastChanges(){var _a8;null==(_a8=this.changes)||_a8.cancel();this._isBroadcasting=!1;this.dispatchStatus()}enableBroadcastChanges(){if(this._isBroadcasting)return;this._isBroadcasting=!0;this.dispatchStatus();if(this.changes){this.changes.cancel();this.changes.removeAllListeners()}this.changes=this.db.changes({since:"now",live:!0,include_docs:!1,selector:{_id:{$gt:"_local/"}}});this.changes.on("change",(async change=>{this.lastSeq=change.seq;await this.notifyProgress()}));const closeChanges=reason=>{var _a8,_b4;if(reason)if(reason instanceof Error){Logger("Error while broadcasting the changes",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}else{Logger("Broadcasting the changes has been finished",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}null==(_a8=this.changes)||_a8.cancel();null==(_b4=this.changes)||_b4.removeAllListeners();this.changes=void 0;this._isBroadcasting=!1;this.dispatchStatus()};this.changes.on("error",closeChanges);this.changes.on("complete",closeChanges);fireAndForget((async()=>await this.notifyProgress()))}get knownAdvertisements(){var _a8,_b4;return null!=(_b4=null==(_a8=this.server)?void 0:_a8.knownAdvertisements)?_b4:[]}async sync(remotePeer,showNotice=!1){const from=await this.replicateFrom(remotePeer,showNotice);if(!from||from.error){Logger("Error while replicating from the remote",LOG_LEVEL_VERBOSE);Logger(from.error,LOG_LEVEL_VERBOSE);return from}const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger(`P2P Replication has been requested to ${remotePeer}`,logLevel,"p2p-replicator");const res2=await this.requestSynchroniseToPeer(remotePeer);res2.ok&&Logger("P2P Replication has been done",logLevel,"p2p-replicator");if(res2.error){Logger("Error while syncing from the remote",logLevel,"p2p-replicator");Logger(res2.error,LOG_LEVEL_VERBOSE)}}async replicateTo(){await this.makeSureOpened();const remotePeer=await this.selectPeer();if(remotePeer){Logger(`P2P Replicating to ${remotePeer}`,LOG_LEVEL_INFO);try{if(this._replicateToPeers.has(remotePeer)){Logger(`Replication to ${remotePeer} is already in progress`,LOG_LEVEL_VERBOSE);return}this._replicateToPeers.add(remotePeer);this.dispatchStatus();return await this.requestSynchroniseToPeer(remotePeer)}finally{this._replicateToPeers.delete(remotePeer);this.dispatchStatus()}}else Logger("No peer selected",LOG_LEVEL_VERBOSE)}dispatchReplicationProgress(peerId,info3){this.onReplicationProgress(peerId,info3)}onReplicationProgress(peerId,info3){var _a8,_b4;const stat={peerId,peerName:(null==(_b4=null==(_a8=this.server)?void 0:_a8._knownAdvertisements.get(peerId))?void 0:_b4.name)||peerId,fetching:{max:0,current:0,isActive:!1}};info3&&(stat.fetching={max:info3.maxSeqInBatch,current:info3.lastSeq,isActive:!0});eventHub.emitEvent("p2p-replicator-progress",stat);return!0}onProgressAcknowledged(peerId,info3){var _a8,_b4;const ack={peerId,peerName:(null==(_b4=null==(_a8=this.server)?void 0:_a8._knownAdvertisements.get(peerId))?void 0:_b4.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 async function replicateShim(targetDB,sourceDB,progress,option={}){try{const targetDBInfo=await targetDB.info(),sourceDBInfo=await sourceDB.info(),sourceMaxSeq=sourceDBInfo.update_seq,maxNumSeq=Number.parseInt(`${sourceMaxSeq}`.split("-")[0]);await serialized(`replication-${targetDBInfo.db_name}-${sourceDBInfo.db_name}`,(async()=>{var _a8,_b4,_c3;Logger(`Replication from ${sourceDBInfo.db_name} to ${targetDBInfo.db_name}\nSource: ${sourceDBInfo.db_name} (${sourceDBInfo.update_seq})\nTarget: ${targetDBInfo.db_name} (${targetDBInfo.update_seq})`,LOG_LEVEL_VERBOSE);const targetDBName=targetDBInfo.db_name,sourceDBName=sourceDBInfo.db_name,sourceCheckpointID=`_local/replication-checkpoint-mark-${targetDBName}-${sourceDBName}`,sourceCheckpointData=await upsert(sourceDB,sourceCheckpointID,(doc=>{var _a9;const previousMark=null!=(_a9=doc.mark)?_a9:(new Date).getTime().toString(),mark2=option.rewind?(new Date).getTime().toString():previousMark;return{...doc,mark:mark2}}));Logger(`Replication from ${sourceDBName} to ${targetDBName} with mark ${sourceCheckpointData.mark}`,LOG_LEVEL_VERBOSE);const targetCheckpointID=`_local/replication-checkpoint-${targetDBName}-${sourceCheckpointData.mark}`;let since=(await upsert(targetDB,targetCheckpointID,(doc=>{var _a9;return{...doc,since:null!=(_a9=doc.since)?_a9:""}}))).since;Logger(`Replication from ${sourceDBName} to ${targetDBName} / since ${since}`,LOG_LEVEL_VERBOSE);const batch_size=null!=(_a8=option.batch_size)?_a8:33;for(;;){const changes3=await sourceDB.changes({since,style:"all_docs",limit:batch_size});if(0===changes3.results.length)break;if(null==(_c3=null==(_b4=option.controller)?void 0:_b4.signal)?void 0:_c3.aborted)break;const changesResults=changes3.results,diffCheckParam=changesResults.map((e3=>[e3.id,e3.changes.map((e4=>e4.rev))])).reduce(((acc,[id,revs])=>{var _a9;return{...acc,[id]:[...null!=(_a9=acc[id])?_a9:[],...revs]}}),{}),diff=await targetDB.revsDiff(diffCheckParam),request2=Object.entries(diff).filter((e3=>void 0!==e3[1].missing)).map((e3=>[e3[0],e3[1].missing])).map((([id,revs])=>revs.map((rev3=>({id,rev:rev3}))))).flat();if(0!==request2.length){const fetchedMissingDocs=(await sourceDB.bulkGet({docs:request2,revs:!0})).results.map((e3=>e3.docs)).flat().filter((e3=>"ok"in e3)).map((e3=>e3.ok)),processedDocs=(await targetDB.bulkDocs(fetchedMissingDocs,{new_edits:!1}),(await targetDB.bulkGet({docs:[...new Set(changesResults.map((e3=>({id:e3.id}))))]})).results.map((e3=>e3.docs)).flat().filter((e3=>"ok"in e3)).map((e3=>e3.ok)).map((e3=>({doc:e3,seq:Math.max.apply(void 0,[changesResults.filter((e22=>e22.id===e3._id)).map((e22=>`${e22.seq}`.split("-")[0])).map((e22=>parseInt(e22))).reduce(((a2,b3)=>Math.max(a2,b3)),0),0])}))).sort(((a2,b3)=>a2.seq-b3.seq)).map((e3=>e3.doc))),allSecs=Number.parseInt(`${changes3.last_seq}`.split("-")[0]);try{await progress(processedDocs,{lastSeq:allSecs,maxSeqInBatch:maxNumSeq})}catch(ex){Logger("Failed to process the progress on shim-replication");Logger(ex,LOG_LEVEL_VERBOSE)}since=changes3.last_seq}else since=changes3.last_seq;await upsert(targetDB,targetCheckpointID,(doc=>({...doc,since})))}}))}catch(ex){Logger("Failed to replicate the database",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}Logger("Replication has been completed",LOG_LEVEL_VERBOSE)}(this.db,remoteDB,(async(docs,info3)=>{await this._env.processReplicatedDocs(docs);this.dispatchReplicationProgress(remotePeer,info3);this.acknowledgeProgress(remotePeer,info3);this.notifyProgress(remotePeer);Logger(`P2P Replication from ${remotePeer}\n${info3.lastSeq} / ${info3.maxSeqInBatch})`,logLevel,"p2p-replicator")}),{live:!1,rewind:fromStart});this.acknowledgeProgress(remotePeer,void 0);Logger(`P2P Replication from ${remotePeer} has been completed`,logLevel,"p2p-replicator")}catch(e3){Logger("Error while P2P replicating",logLevel,"p2p-replicator");Logger(e3,LOG_LEVEL_VERBOSE);return{error:e3}}finally{this._replicateFromPeers.delete(remotePeer);this.dispatchStatus()}return{ok:!0}}notifyProgress(excludePeerId){if(this._isBroadcasting&&this.server){for(const peer of this.server.knownAdvertisements){const peerId=peer.peerId;peerId!==excludePeerId&&serialized(`notifyProgress-${peerId}`,(async()=>{var _a8,_b4,_c3;if(await(null==(_a8=this.server)?void 0:_a8.isAcceptablePeer(peerId)))try{return await(null==(_c3=this.server)?void 0:_c3.getConnection(peerId).invokeRemoteFunction("onProgress",[null==(_b4=this.server)?void 0:_b4.serverPeerId],0))}catch(e3){Logger(`Error while notifying progress to ${peerId}`,LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}else Logger(`Peer ${peerId} is not acceptable to notify progress`,LOG_LEVEL_VERBOSE)}))}return Promise.resolve()}}async requestBroadcastChanges(peerId){var _a8;return await(null==(_a8=this.server)?void 0:_a8.getConnection(peerId).invokeRemoteFunction("requestBroadcasting",[this.server.serverPeerId],0))}async getRemoteIsBroadcasting(peerId){var _a8;try{return await(null==(_a8=this.server)?void 0:_a8.getConnection(peerId).invokeRemoteFunction("getIsBroadcasting",[],0))}catch(e3){Logger("Error while getting remote is broadcasting",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}}watchPeer(peerId){this._watchingPeers.add(peerId);this.dispatchStatus()}unwatchPeer(peerId){this._watchingPeers.delete(peerId);this.dispatchStatus()}async onUpdateDatabase(fromPeerId){if(this._watchingPeers.has(fromPeerId)){Logger(`Progress notification from ${fromPeerId}`,LOG_LEVEL_VERBOSE);return await serialized(`onProgress-${fromPeerId}`,(async()=>await this.replicateFrom(fromPeerId)))}return!1}async getRemoteConfig(peerId){if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const connection=this.server.getConnection(peerId),encryptedConfig=await connection.invokeRemoteFunction("getAllConfig",[this.server.serverPeerId],0),passphrase=await this.confirm.askString("Passphrase required",$msg("P2P.AskPassphraseForDecrypt"),"something you only know",!0);if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to decrypt the configuration. The config cannot be decrypted",LOG_LEVEL_NOTICE);return!1}try{return JSON.parse(await decrypt(encryptedConfig,passphrase,!1))}catch(e3){Logger("Error while decrypting the configuration",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async checkTweakValues(peerId){var _a8;if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const peerPlatform=null==(_a8=this.server.knownAdvertisements.find((e3=>e3.peerId==peerId)))?void 0:_a8.platform;if(null==peerPlatform){Logger("Peer is not found",LOG_LEVEL_NOTICE);return!1}if("pseudo-replicator"===this.platform)return!0;if("pseudo-replicator"===peerPlatform)return!0;const connection=this.server.getConnection(peerId),tweakValues=await connection.invokeRemoteObjectFunction("getTweakSettings",[this.server.serverPeerId],5e3),thisTweakValues=await this.getTweakSettings("");if(!isObjectDifferent(thisTweakValues,tweakValues))return!0;if(thisTweakValues.passphrase!==tweakValues.passphrase){Logger("Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.",LOG_LEVEL_NOTICE);return!1}Logger("Some mismatched configuration have been detected... Please check settings for efficient replication.",LOG_LEVEL_NOTICE);return!0}async replicateFromCommand(showResult=!1){null===await skipIfDuplicated("replicateFromCommand",(async()=>{var _a8;const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if(!this._env.settings.P2P_Enabled){Logger($msg("P2P.NotEnabled"),logLevel);return Promise.resolve(!1)}const peers=this._env.settings.P2P_SyncOnReplication.split(",").map((e3=>e3.trim())).filter((e3=>e3));if(0==peers.length){Logger($msg("P2P.NoAutoSyncPeers"),logLevel);return Promise.resolve(!1)}for(const peer of peers){const peerId=null==(_a8=this.knownAdvertisements.find((e3=>e3.name==peer)))?void 0:_a8.peerId;if(peerId){Logger($msg("P2P.SyncStartedWith",{name:peer}),logLevel);await this.sync(peerId,showResult)}else Logger($msg("P2P.SeemsOffline",{name:peer}),logLevel)}Logger($msg("P2P.SyncCompleted"),logLevel);return Promise.resolve(!0)}))&&Logger($msg("P2P.SyncAlreadyRunning"),LOG_LEVEL_NOTICE)}};P2PLogCollector=class{constructor(){this.p2pReplicationResult=new Map;this.p2pReplicationLine=reactiveSource("");eventHub.onEvent("p2p-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("p2p-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}};(function setGlobalLogFunction(logger2){_logger=logger2})(((message,level,key2)=>{const entry={message,level,key:key2};logStore.enqueue(entry)}));recentLogs=[];recentLogProcessor=new QueueProcessor((logs=>{recentLogs=[...recentLogs,...logs].splice(-200);logMessages.value=recentLogs}),{batchSize:25,delay:10,suspended:!1,concurrentLimit:1}).resumePipeLine();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()}`)),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=queueCountLabelX.value,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.core.$$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((label=>{this.applyStatusBarText()}),20);statusBarLabels.onChanged((label=>applyToDisplay(label.value)))}$everyOnload(){eventHub.onEvent("leaf-active-changed",(()=>this.onActiveLeafChange()));eventHub.onceEvent(EVENT_LAYOUT_READY,(()=>this.onActiveLeafChange()));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 thisFile=this.app.workspace.getActiveFile();return thisFile?this.core.$$shouldCheckCaseInsensitive()&&this.core.storageAccess.getFiles().map((e3=>e3.path)).filter((e3=>e3.toLowerCase()==thisFile.path.toLowerCase())).length>1?"Not synchronised: There are multiple files with the same name":await this.core.$$isTargetFile(thisFile.path)?this.core.$$isFileSizeExceeded(thisFile.stat.size)?"Not synchronised: File size exceeded":"":"Not synchronised: not a target file":""}async setFileStatus(){const fileStatus=await this.getActiveFileStatus();this.activeFileStatus.value=fileStatus;this.messageArea.innerText=this.settings.hideFileWarningNotice?"":fileStatus}onActiveLeafChange(){fireAndForget((async()=>{this.adjustStatusDivPosition();await this.setFileStatus()}))}applyStatusBarText(){if(!this.nextFrameQueue){this.nextFrameQueue=requestAnimationFrame((()=>{var _a8,_b4,_c3;this.nextFrameQueue=void 0;const{message,status}=this.statusBarLabels.value,newMsg=message;let newLog=(null==(_a8=this.settings)?void 0:_a8.showOnlyIconsOnEditor)?"":status;const moduleTagEnd=newLog.indexOf("] ");-1!=moduleTagEnd&&(newLog=newLog.substring(moduleTagEnd+2));null==(_b4=this.statusBar)||_b4.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 _a8;this.statusDiv&&this.statusDiv.remove();null==(_a8=document.querySelectorAll(".livesync-status"))||_a8.forEach((e3=>e3.remove()));return Promise.resolve(!0)}$everyOnloadStart(){(0,import_obsidian.addIcon)("view-log",'\n \n \n ');this.addRibbonIcon("view-log",$msg("moduleLog.showLog"),(()=>{this.core.$$showView("log-log")})).addClass("livesync-ribbon-showlog");this.addCommand({id:"view-log",name:"Show log",callback:()=>{this.core.$$showView("log-log")}});this.registerView("log-log",(leaf=>new LogPaneView(leaf,this.plugin)));return Promise.resolve(!0)}$everyOnloadAfterLoadSettings(){var _a8;logStore.pipeTo(new QueueProcessor((logs=>logs.forEach((e3=>this.core.$$addLog(e3.message,e3.level,e3.key)))),{suspended:!1,batchSize:20,concurrentLimit:1,delay:0})).startPipeline();eventHub.onEvent("file-renamed",(data=>{this.setFileStatus()}));document.querySelectorAll(".livesync-status").forEach((e3=>e3.remove()));this.observeForLogs();this.statusDiv=this.app.workspace.containerEl.createDiv({cls:"livesync-status"});this.statusLine=this.statusDiv.createDiv({cls:"livesync-status-statusline"});this.messageArea=this.statusDiv.createDiv({cls:"livesync-status-messagearea"});this.logMessage=this.statusDiv.createDiv({cls:"livesync-status-logmessage"});this.logHistory=this.statusDiv.createDiv({cls:"livesync-status-loghistory"});eventHub.onEvent(EVENT_LAYOUT_READY,(()=>this.adjustStatusDivPosition()));if(null==(_a8=this.settings)?void 0:_a8.showStatusOnStatusbar){this.statusBar=this.core.addStatusBarItem();this.statusBar.addClass("syncstatusbar")}this.adjustStatusDivPosition();return Promise.resolve(!0)}writeLogToTheFile(now3,vaultName,newMessage){fireAndForget((()=>serialized("writeLog",(async()=>{const time=now3.toISOString().split("T")[0],logDate=`${PREFIXMD_LOGFILE}${time}.md`;await this.core.storageAccess.isExists(normalizePath(logDate))||await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),"```\n");await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),vaultName+":"+newMessage+"\n")}))))}$$addLog(message,level=LOG_LEVEL_INFO,key2=""){var _a8,_b4,_c3;if(-1==level)return;if(level"+messageContent;console.log(vaultName+":"+newMessage);(null==(_a8=this.settings)?void 0:_a8.showOnlyIconsOnEditor)||(this.statusLog.value=messageContent);(null==(_b4=this.settings)?void 0:_b4.writeLogToTheFile)&&this.writeLogToTheFile(now3,vaultName,newMessage);recentLogProcessor.enqueue(newMessage);this.logLines.push({ttl:now3.getTime()+3e3,message:newMessage});if(level>=LOG_LEVEL_NOTICE){key2||(key2=messageContent);if(key2 in this.notifies){(null==(_c3=this.notifies[key2].notice.noticeEl)?void 0:_c3.isShown())||(this.notifies[key2].notice=new import_obsidian.Notice(messageContent,0));cancelTask(`notify-${key2}`);if(key2==messageContent){this.notifies[key2].count++;this.notifies[key2].notice.setMessage(`(${this.notifies[key2].count}):${messageContent}`)}else this.notifies[key2].notice.setMessage(`${messageContent}`)}else{const notify=new import_obsidian.Notice(messageContent,0);this.notifies[key2]={count:0,notice:notify}}const timeout=5e3;key2.startsWith("keepalive-")&&-1===messageContent.indexOf("  ")||scheduleTask(`notify-${key2}`,timeout,(()=>{const notify=this.notifies[key2].notice;delete this.notifies[key2];try{notify.hide()}catch(e3){}}))}}};noticeIndex=0;LiveSyncCommands=class{constructor(plugin3){this._log=(msg,level=LOG_LEVEL_INFO,key2)=>{"string"==typeof msg&&level!==LOG_LEVEL_NOTICE&&(msg=`[${this.constructor.name}]  ${msg}`);Logger(msg,level,key2)};this._verbose=(msg,key2)=>{this._log(msg,LOG_LEVEL_VERBOSE,key2)};this._info=(msg,key2)=>{this._log(msg,LOG_LEVEL_INFO,key2)};this._notice=(msg,key2)=>{this._log(msg,LOG_LEVEL_NOTICE,key2)};this._progress=(prefix="",level=LOG_LEVEL_NOTICE)=>{const key2="keepalive-progress-"+noticeIndex++;return{log:msg=>{this._log(prefix+msg,level,key2)},once:msg=>{this._log(prefix+msg,level)},done:(msg="Done")=>{this._log(prefix+msg+"  ",level,key2)}}};this._debug=(msg,key2)=>{this._log(msg,LOG_LEVEL_VERBOSE,key2)};this.plugin=plugin3}get app(){return this.plugin.app}get settings(){return this.plugin.settings}get localDatabase(){return this.plugin.localDatabase}id2path(id,entry,stripPrefix2){return this.plugin.$$id2path(id,entry,stripPrefix2)}async path2id(filename,prefix){return await this.plugin.$$path2id(filename,prefix)}getPath(entry){return getPath2(entry)}_isMainReady(){return this.plugin.$$isReady()}_isMainSuspended(){return this.plugin.$$isSuspended()}_isDatabaseReady(){return this.plugin.$$isDatabaseReady()}};root_12=template('
Just for a minute, please!
',1);root_4=template('');root_6=template(" ");root_5=template('
');root_10=template('');root_2=template('
',1);root2=template('

',1);$$css2={hash:"svelte-dk5958",code:".spacer.svelte-dk5958 {flex-grow:1;}.infos.svelte-dk5958 {display:flex;justify-content:space-between;margin:4px 0.5em;}.deleted.svelte-dk5958 {text-decoration:line-through;}.svelte-dk5958 {box-sizing:border-box;}.scroller.svelte-dk5958 {display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text;-webkit-user-select:text;}.json-source.svelte-dk5958 {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(app2,filename,docs,callback,nameA,nameB,defaultSelect,keepOrder,hideLocal,title="Conflicted Setting"){super(app2);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;(async function waitForSignal(id,timeout){return await globalSlipBoard.awaitNext("x-compatibility-signal",id,{timeout})!==TIMED_OUT_SIGNAL})(`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}}};HiddenFileSync=class extends LiveSyncCommands{constructor(){super(...arguments);this.periodicInternalFileScanProcessor=new PeriodicProcessor(this.plugin,(async()=>this._isThisModuleEnabled()&&this._isDatabaseReady()&&await this.scanAllStorageChanges(!1)));this.shouldSkipFile=[];this.semaphore=Semaphore(10);this.conflictResolutionProcessor=new QueueProcessor((async paths=>{var _a8,_b4,_c3;const path2=paths[0];(function sendSignal(id){globalSlipBoard.submit("x-compatibility-signal",id)})(`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==(_b4=null==(_a8=(await this.localDatabase.getRaw(id,{revs_info:!0}))._revs_info)?void 0:_a8.filter((e3=>"available"==e3.status&&Number(e3.rev.split("-")[0]){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.queuedNotificationFiles=new Set;this.ignorePatterns=[];this.targetPatterns=[]}_isThisModuleEnabled(){return this.plugin.settings.syncInternalFiles}get kvDB(){return this.plugin.kvDB}getConflictedDoc(path2,rev3){return this.plugin.localDatabase.getConflictedDoc(path2,rev3)}onunload(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable()}onload(){this.plugin.addCommand({id:"livesync-sync-internal",name:"(re)initialise hidden files between storage and database",callback:()=>{this.isReady()&&this.initialiseInternalFileSync("safe",!0)}});this.plugin.addCommand({id:"livesync-scaninternal-storage",name:"Scan hidden file changes on the storage",callback:()=>{this.isReady()&&this.scanAllStorageChanges(!0)}});this.plugin.addCommand({id:"livesync-scaninternal-database",name:"Scan hidden file changes on the local database",callback:()=>{this.isReady()&&this.scanAllDatabaseChanges(!0)}});this.plugin.addCommand({id:"livesync-internal-scan-offline-changes",name:"Scan and apply all offline hidden-file changes",callback:()=>{this.isReady()&&this.applyOfflineChanges(!0)}});eventHub.onEvent("setting-saved",(()=>{this.updateSettingCache()}))}async $everyOnInitializeDatabase(db){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");return!0}async $everyOnDatabaseInitialized(showNotice){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(){const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns");this.ignorePatterns=ignorePatterns;const targetFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");this.targetPatterns=targetFilter;this.shouldSkipFile=[];const configDir=normalizePath(this.app.vault.configDir),shouldSKip=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.shouldSkipFile=shouldSKip;this._log(`Hidden file will skip ${this.shouldSkipFile.length} files`,LOG_LEVEL_INFO)}isReady(){return!!this._isMainReady&&!this._isMainSuspended()&&!!this._isThisModuleEnabled()}async performStartupScan(showNotice){await this.applyOfflineChanges(showNotice)}async $everyOnResumeProcess(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable();if(this._isMainSuspended())return!0;this._isThisModuleEnabled()&&await this.performStartupScan(!1);this.periodicInternalFileScanProcessor.enable(this._isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);return!0}$everyRealizeSettingSyncMode(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable();if(this._isMainSuspended())return Promise.resolve(!0);if(!this.plugin.$$isReady())return Promise.resolve(!0);this.periodicInternalFileScanProcessor.enable(this._isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns");this.ignorePatterns=ignorePatterns;const targetFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");this.targetPatterns=targetFilter;return Promise.resolve(!0)}async $anyProcessOptionalFileEvent(path2){if(this.isReady())return await this.trackStorageFileModification(path2)}$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.plugin.$$isTargetFile(filename)){await this.processReplicationResult(doc);return!0}this._log(`Skipped (Not target:${filename})`,LOG_LEVEL_VERBOSE);return!1}return!0}return!1}async loadFileWithInfo(path2){var _a8,_b4;const stat=await this.plugin.storageAccess.statHidden(path2);if(!stat)return{name:null!=(_a8=path2.split("/").pop())?_a8:"",path:path2,stat:{size:0,mtime:0,ctime:0,type:"file"},isInternal:!0,deleted:!0,body:createBlob(new Uint8Array(0))};const content=await this.plugin.storageAccess.readHiddenFileAuto(path2);return{name:null!=(_b4=path2.split("/").pop())?_b4:"",path:path2,stat,isInternal:!0,deleted:!1,body:createBlob(content)}}statToKey(stat){var _a8,_b4;return`${null!=(_a8=null==stat?void 0:stat.mtime)?_a8:0}-${null!=(_b4=null==stat?void 0:stat.size)?_b4: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 key2="string"==typeof keySrc?keySrc:this.statToKey(keySrc),splitted=key2.split("-");"0"!=splitted[0]&&this._fileInfoLastKnown.set(file,Number(splitted[0]));this._fileInfoLastProcessed.set(file,key2)}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 key2 of targetFiles)this._fileInfoLastProcessed.delete(key2);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 key2="string"==typeof keySrc?keySrc:this.docToKey(keySrc);this._databaseInfoLastProcessed.set(file,key2)}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 key2 of targetFiles)this._databaseInfoLastProcessed.delete(key2);else{this._log("Delete all processed mark.",LOG_LEVEL_VERBOSE);this._databaseInfoLastProcessed.clear()}}async adoptCurrentStorageFilesAsProcessed(targetFiles){const allFiles=await this.scanInternalFileNames(),files=targetFiles?allFiles.filter((e3=>targetFiles.some((t3=>-1!==e3.indexOf(t3))))):allFiles;for(const file of files)await this.updateLastProcessedAsActualFile(file)}async adoptCurrentDatabaseFilesAsProcessed(targetFiles){const allFiles=await this.getAllDatabaseFiles(),files=targetFiles?allFiles.filter((e3=>targetFiles.some((t3=>-1!==e3.path.indexOf(t3))))):allFiles;for(const file of files){const path2=stripAllPrefixes(this.getPath(file));await this.updateLastProcessedAsActualDatabase(path2,file)}}async serializedForEvent(file,fn){hiddenFilesEventCount.value++;const rel=await this.semaphore.acquire();try{return await serialized(`hidden-file-event:${file}`,(async()=>{hiddenFilesProcessingCount.value++;try{return await fn()}finally{hiddenFilesProcessingCount.value--}}))}finally{rel();hiddenFilesEventCount.value--}}async useStorageFiles(files,showNotice=!1,onlyNew=!1){return await this.trackScannedStorageChanges(files,showNotice,onlyNew,!0)}async trackScannedStorageChanges(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Storage -> DB ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p4.log(`${progress}/${processFiles.length}`))),processes=processFiles.map((async(file,i2)=>{try{await this.trackStorageFileModification(file,onlyNew,forceWriteAll,includeDeleted);notifyProgress()}catch(ex){p4.once(`Failed to process storage change file:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);p4.done()}async scanAllStorageChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){return await skipIfDuplicated("scanAllStorageChanges",(async()=>{const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Scanning Storage -> DB ]\n",logLevel);p4.log("Scanning storage files...");const knownNames=[...this._fileInfoLastProcessed.keys()],existNames=await this.scanInternalFileNames(),files=new Set([...knownNames,...existNames]);this._log(`Known/Exist ${knownNames.length}/${existNames.length}, Totally ${files.size} files.`,LOG_LEVEL_VERBOSE);const taskNameAndMeta=[...files].map((async e3=>[e3,await this.plugin.storageAccess.statHidden(e3)])),processFiles=(await Promise.all(taskNameAndMeta)).filter((([path2,stat])=>!!forceWriteAll||this.getLastProcessedFileKey(path2)!=this.statToKey(stat))).map((([path2,stat])=>path2)),staticsMessage=`[Storage hidden file statics]\nKnown files: ${knownNames.length}\nActual files: ${existNames.length}\nAll files: ${files.size}\nOffline Changed files: ${processFiles.length}`;p4.once(staticsMessage);await this.trackScannedStorageChanges(processFiles,showNotice,onlyNew,forceWriteAll,includeDeleted);p4.done()}))}async trackStorageFileModification(path2,onlyNew=!1,forceWrite=!1,includeDeleted=!0){if(this.shouldSkipFile.some((e3=>e3.startsWith(path2.toLowerCase())))){this._log(`Hidden file skipped: ${path2} is synchronized in customization sync.`,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 key2=await this.fileToStatKey(path2,stat),lastKey=this.getLastProcessedFileKey(path2);if(lastKey==key2){this._log(`${path2} Already processed.`,-1);return!0}const cache2=await this.loadFileWithInfo(path2);if(getComparingMTime(cache2.stat)!=getComparingMTime(stat)){this._log(`Hidden file:${path2} is changed.`,LOG_LEVEL_VERBOSE);stat=cache2.stat}this.updateLastProcessedFile(path2,stat);const lastIsNotFound=!lastKey||lastKey.endsWith("-0-0"),nowIsNotFound=cache2.deleted,type=lastIsNotFound&&nowIsNotFound?"invalid":nowIsNotFound?"delete":"modified";if("invalid"==type)return!1;const storageMTimeActual=getComparingMTime(stat),storageMTime=0==storageMTimeActual?this.getLastProcessedFileMTime(path2):storageMTimeActual;if(onlyNew){const prefixedFileName=addPrefix(path2,ICHeader),filesOnDB=await this.localDatabase.getDBEntryMeta(prefixedFileName);if(compareMTime(storageMTime,getComparingMTime(filesOnDB,includeDeleted))!=TARGET_IS_NEW){this._log(`Hidden file:${path2} is not new.`,LOG_LEVEL_VERBOSE);filesOnDB&&stat&&this.updateLastProcessed(path2,filesOnDB,stat);return!0}}if("delete"==type){this._log(`Deletion detected: ${path2}`);return await this.deleteInternalFileOnDatabase(path2,forceWrite)}if("modified"==type){this._log(`Modification detected:${path2}`,LOG_LEVEL_VERBOSE);const result=await this.storeInternalFileToDatabase(cache2,forceWrite),resultText=void 0===result?"Nothing changed":result?"Updated":"Failed";this._log(`${resultText}: ${path2} ${resultText}`,LOG_LEVEL_VERBOSE);return result}}))}catch(ex){this._log(`Failed to process hidden file:${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}queueConflictCheck(path2){this.conflictResolutionProcessor.enqueue(path2)}async resolveConflictOnInternalFiles(){const conflicted=this.localDatabase.findEntries(ICHeader,"i;",{conflicts:!0});this.conflictResolutionProcessor.suspend();try{for await(const doc of conflicted)"_conflicts"in doc&&isInternalMetadata(doc._id)&&this.conflictResolutionProcessor.enqueue(doc.path)}catch(ex){this._log("something went wrong on resolving all conflicted internal files");this._log(ex,LOG_LEVEL_VERBOSE)}await this.conflictResolutionProcessor.startPipeline().waitForAllProcessed()}async resolveByNewerEntry(id,path2,currentDoc,currentRev,conflictedRev){var _a8;const conflictedDoc=await this.localDatabase.getRaw(id,{rev:conflictedRev}),delRev=getComparingMTime(currentDoc,!0){this._log("Opening data-merging dialog",LOG_LEVEL_VERBOSE);const docs=[docA,docB],strippedPath=stripAllPrefixes(docA.path),storageFilePath=strippedPath,storeFilePath=strippedPath,displayFilename=`${storeFilePath}`;new JsonResolveModal(this.app,storageFilePath,[docA,docB],(async(keep,result)=>{var _a8,_b4;try{let needFlush=!1;if(!result&&!keep){this._log(`Skipped merging: ${displayFilename}`);res2(!1);return}if(result||keep)for(const doc of docs)if(doc._rev!=keep&&await this.localDatabase.deleteDBEntry(this.getPath(doc),{rev:doc._rev})){this._log(`Conflicted revision has been deleted: ${displayFilename}`);needFlush=!0}if(!keep&&result){await this.plugin.storageAccess.isExistsIncludeHidden(storageFilePath)||await this.plugin.storageAccess.ensureDir(storageFilePath);const stat=await this.writeFile(storageFilePath,result);if(!stat)throw new Error("Stat failed");const mtime=getComparingMTime(stat);await this.storeInternalFileToDatabase({path:storageFilePath,mtime,ctime:null!=(_a8=null==stat?void 0:stat.ctime)?_a8:mtime,size:null!=(_b4=null==stat?void 0:stat.size)?_b4: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=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}}(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}async trackScannedDatabaseChange(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ DB -> Storage ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p4.log(`${progress}/${processFiles.length}`))),processes=processFiles.map((async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.trackDatabaseFileModification(path2,"[Hidden file scan]",!forceWriteAll,onlyNew,file,includeDeletion);notifyProgress()}catch(ex){this._log(`Failed to process storage change file:${file}`,logLevel);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);p4.done()}async applyOfflineChanges(showNotice){const logLevel=getLogLevel(showNotice);return await serialized("applyOfflineChanges",(async()=>{const p4=this._progress("[⚙ Apply untracked changes ]\n",logLevel);this._log("Track changes.",logLevel);p4.log("Enumerating local files...");const currentStorageFiles=await this.scanInternalFileNames();p4.log("Enumerating database files...");const currentDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=Object.fromEntries(currentDatabaseFiles.map((e3=>[stripAllPrefixes(getPath2(e3)),e3]))),currentDatabaseFileNames=[...Object.keys(allDatabaseMap)],untrackedLocal=currentStorageFiles.filter((e3=>!this._fileInfoLastProcessed.has(e3))),untrackedDatabase=currentDatabaseFileNames.filter((e3=>!this._databaseInfoLastProcessed.has(e3))),bothUntracked=untrackedLocal.filter((e3=>-1!==untrackedDatabase.indexOf(e3)));p4.log("Applying untracked changes...");const stat=`Tracking statics:\nLocal files: ${currentStorageFiles.length}\nDatabase files: ${currentDatabaseFileNames.length}\nUntracked local files: ${untrackedLocal.length}\nUntracked database files: ${untrackedDatabase.length}\nCommon untracked files: ${bothUntracked.length}`;p4.once(stat);const semaphores=Semaphore(10),notifyProgress=onlyInNTimes(25,(progress=>p4.log(`${progress}/${bothUntracked.length}`))),allProcesses=bothUntracked.map((async file=>{notifyProgress();const rel=await semaphores.acquire();try{const fileStat=await this.plugin.storageAccess.statHidden(file);if(null==fileStat){this._log(`Unexpected error: Failed to stat file during applyOfflineChange :${file}`);return}const dbInfo=allDatabaseMap[file];if(dbInfo.deleted||dbInfo._deleted)return;const diff=compareMTime(getComparingMTime(fileStat),getComparingMTime(dbInfo));diff==BASE_IS_NEW?await this.trackStorageFileModification(file,!0):diff==TARGET_IS_NEW?await this.trackDatabaseFileModification(file,"[Apply]",!0,!0,dbInfo):diff==EVEN&&this.updateLastProcessed(file,dbInfo,fileStat)}finally{rel()}}));await Promise.all(allProcesses);await this.scanAllStorageChanges(showNotice);await this.scanAllDatabaseChanges(showNotice);p4.done()}))}async scanAllDatabaseChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){return await skipIfDuplicated("scanAllDatabaseChanges",(async()=>{const databaseFiles=await this.getAllDatabaseFiles(),files=databaseFiles.filter((e3=>{const doc=e3,key2=this.docToKey(doc),path2=stripAllPrefixes(this.getPath(doc));return this.getLastProcessedDatabaseKey(path2)!=key2})),logLevel=getLogLevel(showNotice),staticsMessage=`[Database hidden file statics]\nAll files: ${databaseFiles.length}\nOffline Changed files: ${files.length}`;this._log(staticsMessage,logLevel,"scan-changes");return await this.trackScannedDatabaseChange(files,showNotice,onlyNew,forceWriteAll,includeDeletion)}))}async useDatabaseFiles(files,showNotice=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Scanning DB -> Storage ]\n",logLevel);p4.log("Scanning database files...");const notifyProgress=onlyInNTimes(25,(progress=>p4.log(`${progress}/${files.length}`))),processFiles=files.map((async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.trackDatabaseFileModification(path2,"[Scanning]",!0,onlyNew,file);notifyProgress()}catch(ex){this._log(`Failed to process database changes:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processFiles);p4.done();return!0}async trackDatabaseFileModification(path2,headerLine,preventDoubleProcess=!1,onlyNew=!1,meta=!1,includeDeletion=!0){return await this.serializedForEvent(path2,(async()=>{try{const prefixedPath=addPrefix(path2,ICHeader),docMeta=meta||await this.localDatabase.getDBEntryMeta(prefixedPath,{conflicts:!0},!0);if(!1===docMeta){this._log(`${headerLine}: Failed to read detail of ${path2}`);throw new Error(`Failed to read detail ${path2}`)}if(docMeta._conflicts&&docMeta._conflicts.length>0){this.conflictResolutionProcessor.enqueue(path2);this._log(`${headerLine} Hidden file conflicted, enqueued to resolve`);return!0}await this.extractInternalFileFromDatabase(path2,!1,docMeta,preventDoubleProcess,onlyNew,includeDeletion)&&this._log(`${headerLine} Hidden file processed`)}catch(ex){this._log(`${headerLine} Failed to process hidden file`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}))}notifyConfigChange(){const updatedFolders=[...this.queuedNotificationFiles];this.queuedNotificationFiles.clear();try{const manifests=Object.values(this.app.plugins.manifests),enabledPlugins=this.app.plugins.enabledPlugins,modifiedManifests=manifests.filter((e3=>enabledPlugins.has(e3.id))).filter((e3=>{var _a8;return updatedFolders.indexOf(null!=(_a8=null==e3?void 0:e3.dir)?_a8:"")>=0}));for(const manifest of modifiedManifests){const updatePluginId=manifest.id,updatePluginName=manifest.name;this.plugin.confirm.askInPopup(`updated-${updatePluginId}`,`Files in ${updatePluginName} has been updated!\nPress {HERE} to reload ${updatePluginName}, or press elsewhere to dismiss this message.`,(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{fireAndForget((async()=>{this._log(`Unloading plugin: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId);await this.app.plugins.unloadPlugin(updatePluginId);await this.app.plugins.loadPlugin(updatePluginId);this._log(`Plugin reloaded: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId)}))}))}))}}catch(ex){this._log("Error on checking plugin status.");this._log(ex,LOG_LEVEL_VERBOSE)}updatedFolders.indexOf(this.plugin.app.vault.configDir)>=0&&(this.plugin.$$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.plugin.$$scheduleAppReload()}))})))}queueNotification(key2){if(this.settings.suppressNotifyHiddenFilesChange)return;const configDir=this.plugin.app.vault.configDir;if(!key2.startsWith(configDir))return;const dirName=key2.split("/").slice(0,-1).join("/");this.queuedNotificationFiles.add(dirName);scheduleTask("notify-config-change",1e3,(()=>{this.notifyConfigChange()}))}async rebuildMerging(showNotice,targetFiles=!1){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Rebuild by Merge ]\n",logLevel);this._log("Rebuilding hidden files from the storage and the local database.",logLevel);p4.log("Enumerating local files...");const currentStorageFilesAll=await this.scanInternalFileNames(),currentStorageFiles=targetFiles?currentStorageFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentStorageFilesAll;p4.log("Enumerating database files...");const allDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=new Map(allDatabaseFiles.map((e3=>[stripAllPrefixes(getPath2(e3)),e3]))),currentDatabaseFiles=targetFiles?allDatabaseFiles.filter((e3=>targetFiles.some((f4=>f4==stripAllPrefixes(getPath2(e3)))))):allDatabaseFiles,allFileNames=new Set([...currentStorageFiles,...currentDatabaseFiles.map((e3=>stripAllPrefixes(getPath2(e3))))]),storageToDatabase=[],databaseToStorage=[],eachProgress=onlyInNTimes(100,(progress=>p4.log(`Checking ${progress}/${allFileNames.size}`)));for(const file of allFileNames){eachProgress();const mtimeStorage=getComparingMTime(await this.plugin.storageAccess.statHidden(file)),dbEntry=allDatabaseMap.get(file),diff=compareMTime(mtimeStorage,getComparingMTime(dbEntry));diff==BASE_IS_NEW?storageToDatabase.push(file):diff==TARGET_IS_NEW?databaseToStorage.push(dbEntry):diff==EVEN&&storageToDatabase.push(file)}p4.once(`Storage to Database: ${storageToDatabase.length} files\n Database to Storage: ${databaseToStorage.length} files`);this.resetLastProcessedDatabase(targetFiles);this.resetLastProcessedFile(targetFiles);const processes=[this.useStorageFiles(storageToDatabase,showNotice,!1),this.useDatabaseFiles(databaseToStorage,showNotice,!1)];p4.log("Start processing...");await Promise.all(processes);p4.done();return[...allFileNames]}async rebuildFromStorage(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the storage.");this._log("Rebuilding hidden files from the storage.",logLevel);const p4=this._progress("[⚙ Rebuild by Storage ]\n",logLevel);p4.log("Enumerating local files...");const currentFilesAll=await this.scanInternalFileNames(),currentFiles=targetFiles?currentFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentFilesAll;p4.once(`Storage to Database: ${currentFiles.length} files.`);p4.log("Start processing...");this.resetLastProcessedFile(targetFiles);await this.useStorageFiles(currentFiles,showNotice,onlyNew);p4.done();return currentFiles}async getAllDatabaseFiles(){return(await this.localDatabase.allDocsRaw({startkey:ICHeader,endkey:"i;",include_docs:!0})).rows.filter((e3=>isInternalMetadata(e3.id))).map((e3=>e3.doc))}async rebuildFromDatabase(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the local database.");const p4=this._progress("[⚙ Rebuild by Database ]\n",logLevel);p4.log("Enumerating database files...");const allFiles=await this.getAllDatabaseFiles(),currentFiles=targetFiles?allFiles.filter((e3=>targetFiles.some((f4=>f4==stripAllPrefixes(getPath2(e3)))))):allFiles;p4.once(`Database to Storage: ${currentFiles.length} files.`);this.resetLastProcessedDatabase(targetFiles);p4.log("Start processing...");await this.useDatabaseFiles(currentFiles,showNotice,onlyNew);p4.done();return currentFiles}async initialiseInternalFileSync(direction,showMessage,targetFilesSrc=!1){const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,p4=this._progress("[⚙ Initialise]\n",logLevel);p4.log("Initialising hidden files sync...");const targetFiles=!!targetFilesSrc&&targetFilesSrc.map((e3=>stripAllPrefixes(e3)));if("pushForce"==direction||"push"==direction){const onlyNew="push"==direction;p4.log("Started: Storage --\x3e Database "+(onlyNew?"(Only New)":""));const updatedFiles=await this.rebuildFromStorage(showMessage,targetFiles,onlyNew);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllStorageChanges(showMessage,!0,!1);await this.scanAllDatabaseChanges(showMessage,!0,!1)}if("pullForce"==direction||"pull"==direction){const onlyNew="pull"==direction;p4.log("Started: Database --\x3e Storage "+(onlyNew?"(Only New)":""));const updatedFiles=(await this.rebuildFromDatabase(showMessage,targetFiles,onlyNew)).map((e3=>stripAllPrefixes(getPath2(e3))));await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllDatabaseChanges(showMessage,!0,!1);await this.scanAllStorageChanges(showMessage,!0,!1)}if("safe"==direction){p4.log("Started: Database <--\x3e Storage (by modified date)");const updatedFiles=await this.rebuildMerging(showMessage,targetFiles);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllStorageChanges(showMessage,!0,!1);await this.scanAllDatabaseChanges(showMessage,!0,!1)}p4.done()}async __loadBaseSaveData(file,includeContent=!0){const prefixedFileName=addPrefix(file,ICHeader),id=await this.path2id(prefixedFileName,ICHeader);try{const old=includeContent?await this.localDatabase.getDBEntry(prefixedFileName,void 0,!1,!0):await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);return!1===old?{_id:id,data:[],path:prefixedFileName,mtime:0,ctime:0,datatype:"newnote",children:[],size:0,deleted:!1,type:"newnote",eden:{}}:old}catch(ex){this._log("Getting base save data failed");this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async storeInternalFileToDatabase(file,forceWrite=!1){const storeFilePath=stripAllPrefixes(file.path),storageFilePath=file.path;if(await this.plugin.$$isIgnoredByIgnoreFiles(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.plugin.$$isIgnoredByIgnoreFiles(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.plugin.$$isIgnoredByIgnoreFiles(storageFilePath))return await serialized("file-"+prefixedFileName,(async()=>{var _a8,_b4;try{const metaOnDB=metaEntry||await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);if(!1===metaOnDB)throw new Error(`File not found on database.:${storageFilePath}`);if(null==(_a8=null==metaOnDB?void 0:metaOnDB._conflicts)?void 0:_a8.length){this._log(`Hidden file ${storageFilePath} has conflicted revisions, to keep in safe, writing to storage has been prevented`,LOG_LEVEL_INFO);return!1}if(preventDoubleProcess){const key2=this.docToKey(metaOnDB);if(this.getLastProcessedDatabaseKey(storageFilePath)==key2&&!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!=(_b4=null==storageStat?void 0:storageStat.mtime)?_b4: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`,-1);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 $anyConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode)}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 configDir=normalizePath(this.app.vault.configDir),ignoreFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns"),targetFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns"),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())):[],findRoot=this.app.vault.getRoot().path;return(await this.getFiles(findRoot,[],targetFilter,ignoreFilter)).filter((e3=>e3.startsWith("."))).filter((e3=>!e3.startsWith(".trash"))).filter((path2=>synchronisedInConfigSync.every((filterFile=>!path2.toLowerCase().startsWith(filterFile)))))}async scanInternalFiles(){var _a8,_b4,_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.plugin.$$isIgnoredByIgnoreFiles(w2.path))continue;const mtime=null!=(_b4=null==(_a8=w2.stat)?void 0:_a8.mtime)?_b4: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,ignoreList,filter4,ignoreFilter){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)ignoreList&&ignoreList.length>0&&ignoreList.some((e3=>file.endsWith(e3)))||filter4&&filter4.length>0&&!filter4.some((e3=>e3.test(file)))||ignoreFilter&&ignoreFilter.some((ee=>ee.test(file)))||await this.plugin.$$isIgnoredByIgnoreFiles(file)||files.push(file);L1:for(const v2 of w2.folders){for(const ignore of ignoreList)if(v2.endsWith(ignore))continue L1;ignoreFilter&&ignoreFilter.some((e3=>(e3.pattern.startsWith("/")||e3.pattern.startsWith("\\/"))&&e3.test(v2)))||await this.plugin.$$isIgnoredByIgnoreFiles(v2)||(files=files.concat(await this.getFiles(v2,ignoreList,filter4,ignoreFilter)))}return files}};import_diff_match_patch3=__toESM(require_diff_match_patch(),1);ConflictResolveModal=class extends import_obsidian.Modal{constructor(app2,filename,diff,pluginPickMode,remoteName){super(app2);this.response=CANCELLED;this.isClosed=!1;this.consumed=!1;this.title="Conflicting changes";this.pluginPickMode=!1;this.localName="Keep A";this.remoteName="Keep B";this.result=diff;this.filename=filename;this.pluginPickMode=pluginPickMode||!1;if(this.pluginPickMode){this.title="Pick a version";this.remoteName=`Use ${remoteName||"Remote"}`;this.localName="Use 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_patch3.DIFF_DELETE?diff+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"":x1==import_diff_match_patch3.DIFF_EQUAL?diff+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"":x1==import_diff_match_patch3.DIFF_INSERT&&(diff+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"")}diff=diff.replace(/\n/g,"
");div.innerHTML=diff;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=`\nA:${date1}
B:${date2}
\n `;contentEl.createEl("button",{text:this.localName},(e3=>e3.addEventListener("click",(()=>this.sendResponse(this.result.right.rev))))).style.marginRight="4px";contentEl.createEl("button",{text: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"}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})();import_obsidian5=require("obsidian");root_3=template("");root_62=template('');root_7=template('');root_8=template('');root_42=template(' ',1);root_9=template(' ',1);root_11=template('');root_122=template('');root_22=template(' ',1);root_13=template(' ',1);root_132=template(' All the same or non-existent ',1);$$css3={hash:"svelte-21bw70",code:'.spacer.svelte-21bw70 {min-width:1px;flex-grow:1;}button.svelte-21bw70 {margin:2px 4px;min-width:3em;max-width:4em;}button.svelte-21bw70:disabled {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}button.svelte-21bw70:disabled:hover {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}span.message.svelte-21bw70 {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-21bw70 {margin-left:auto;}.chip-wrap.svelte-21bw70 {display:flex;gap:2px;flex-direction:column;justify-content:center;align-items:flex-start;}.chip.svelte-21bw70 {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-21bw70:empty {display:none;}.chip.svelte-21bw70:not(:empty)::before {min-width:1.8em;display:inline-block;}.chip.content.svelte-21bw70:not(:empty)::before {content:"📄: ";}.chip.version.svelte-21bw70:not(:empty)::before {content:"🏷️: ";}.chip.modified.svelte-21bw70:not(:empty)::before {content:"📅: ";}'};import_obsidian6=require("obsidian");root_14=template('');root_23=template(" ");root_32=template('
No Items.
');root_82=template('
');root_63=template('
');root_52=template('

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

Plugins

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

Maintenance Commands

');root3=template('
',1);$$css4={hash:"svelte-1pucu7f",code:".buttonsWrap.svelte-1pucu7f {padding-bottom:4px;}h3.svelte-1pucu7f {position:sticky;top:0;background-color:var(--modal-background);}.labelrow.svelte-1pucu7f {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-1pucu7f {margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap;}.filerow.hideeven.svelte-1pucu7f:has(.even),\n .labelrow.hideeven.svelte-1pucu7f:has(.even) {display:none;}.noterow.svelte-1pucu7f {min-height:2em;display:flex;}button.status.svelte-1pucu7f {flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em;}.statusnote.svelte-1pucu7f {display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1;}.list.svelte-1pucu7f {overflow-y:auto;}.title.svelte-1pucu7f {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.body.svelte-1pucu7f {\n /* margin-left: 0.4em; */margin-left:auto;display:flex;justify-content:flex-start;align-items:center;\n /* flex-wrap: wrap; */}.filetitle.svelte-1pucu7f {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.buttons.svelte-1pucu7f {display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap;}.buttons.svelte-1pucu7f > button:where(.svelte-1pucu7f) {margin-left:4px;width:auto;}label.svelte-1pucu7f {display:flex;justify-content:center;align-items:center;}label.svelte-1pucu7f > span:where(.svelte-1pucu7f) {margin-right:0.25em;}.is-mobile .title.svelte-1pucu7f,\n .is-mobile .filetitle.svelte-1pucu7f {width:100%;}.center.svelte-1pucu7f {display:flex;justify-content:center;align-items:center;min-height:3em;}.maintenancerow.svelte-1pucu7f {display:flex;justify-content:flex-end;align-items:center;}.maintenancerow.svelte-1pucu7f label:where(.svelte-1pucu7f) {margin-right:0.5em;margin-left:0.5em;}.loading.svelte-1pucu7f {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-1pucu7f:empty {height:0px;transition:height 0.25s ease-in-out;transition-delay:1s;}.loading.svelte-1pucu7f: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(app2,plugin3){super(app2);this.plugin=plugin3}onOpen(){const{contentEl}=this;this.contentEl.style.overflow="auto";this.contentEl.style.display="flex";this.contentEl.style.flexDirection="column";this.titleEl.setText("Customization Sync (Beta3)");this.component||(this.component=mount(PluginPane,{target:contentEl,props:{plugin:this.plugin}}))}onClose(){if(this.component){unmount(this.component);this.component=void 0}}};d="​";d2="\n";DUMMY_HEAD=serialize({category:"CONFIG",name:"migrated",files:[],mtime:0,term:"-",displayName:"MIRAGED"});DUMMY_END=d+d2+"‌";pluginList=writable([]);pluginIsEnumerating=writable(!1);pluginV2Progress=writable(0);pluginManifestStore=writable(pluginManifests=new Map);PluginDataExDisplayV2=class{constructor(data){this.files=[];this.documentPath=`${data.documentPath}`;this.category=`${data.category}`;this.name=`${data.name}`;this.term=`${data.term}`;this.files=[...data.files];this.confKey=`${categoryToFolder(this.category,this.term)}${this.name}`;this.applyLoadedManifest()}async setFile(file){const old=this.files.find((e3=>e3.filename==file.filename));if(old){if(old.mtime==file.mtime&&await isDocContentSame(old.data,file.data))return;this.files=this.files.filter((e3=>e3.filename!=file.filename))}this.files.push(file);"manifest.json"==file.filename&&this.applyLoadedManifest()}deleteFile(filename){this.files=this.files.filter((e3=>e3.filename!=filename))}applyLoadedManifest(){const manifest=pluginManifests.get(this.confKey);if(manifest){this._displayName=manifest.name;"PLUGIN_MAIN"!=this.category&&"THEME"!=this.category||(this._version=null==manifest?void 0:manifest.version)}}get displayName(){return this._displayName||this.name}get version(){return this._version}get mtime(){return~~this.files.reduce(((a2,b3)=>a2+b3.mtime),0)/this.files.length}};ConfigSync=class extends LiveSyncCommands{constructor(plugin3){super(plugin3);this.pluginDialog=void 0;this.periodicPluginSweepProcessor=new PeriodicProcessor(this.plugin,(async()=>await this.scanAllConfigFiles(!1)));this.pluginList=[];this.addRibbonIcon=this.plugin.addRibbonIcon.bind(this.plugin);this.pluginScanProcessor=new QueueProcessor((async v2=>{const plugin3=v2[0];if(this.useV2){await this.migrateV1ToV2(!1,plugin3);return[]}const path2=plugin3.path||this.getPath(plugin3),oldEntry=this.pluginList.find((e3=>e3.documentPath==path2));if(oldEntry&&oldEntry.mtime==plugin3.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter((x2=>x2.documentPath!=pluginData.documentPath));newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.pluginScanProcessorV2=new QueueProcessor((async v2=>{const plugin3=v2[0],path2=plugin3.path||this.getPath(plugin3),oldEntry=this.pluginList.find((e3=>e3.documentPath==path2));if(oldEntry&&oldEntry.mtime==plugin3.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter((x2=>x2.documentPath!=pluginData.documentPath));newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.loadedManifest_mTime=new Map;this.updatingV2Count=0;this.recentProcessedInternalFiles=[];pluginScanningCount.onChanged((e3=>{const total=e3.value;pluginIsEnumerating.set(0!=total)}))}get kvDB(){return this.plugin.kvDB}get useV2(){return this.plugin.settings.usePluginSyncV2}get useSyncPluginEtc(){return this.plugin.settings.usePluginEtc}_isThisModuleEnabled(){return this.plugin.settings.usePluginSync}showPluginSyncModal(){if(this._isThisModuleEnabled())if(this.pluginDialog)this.pluginDialog.open();else{this.pluginDialog=new PluginDialogModal(this.app,this.plugin);this.pluginDialog.open()}}hidePluginSyncModal(){if(null!=this.pluginDialog){this.pluginDialog.close();this.pluginDialog=void 0}}onunload(){var _a8;this.hidePluginSyncModal();null==(_a8=this.periodicPluginSweepProcessor)||_a8.disable()}onload(){(0,import_obsidian.addIcon)("custom-sync",'\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 hash2=digestHash(getDocDataAsArray(work.data));file.hash=hash2;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(function createSavingEntryFromLoadedEntry(doc){const data=readAsBlob(doc),type=function determineType(path2,data){return data instanceof Blob?determineTypeFromBlob(data):isPlainText(path2)?"plain":data instanceof Uint8Array||data instanceof ArrayBuffer?"newnote":"plain"}(doc.path,data);return{...doc,data,datatype:type,type,children:[]}}(wx))))}return{...data,documentPath:this.getPath(wx),files:xFiles}}return!1}filenameToUnifiedKey(path2,termOverRide){const term=termOverRide||this.plugin.$$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.plugin.$$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.plugin.$$getDeviceAndVaultName();return`${ICXHeader}${term}/`}parseUnifiedPath(unifiedPath){const[device,category,...rest]=stripAllPrefixes(unifiedPath).split("/"),relativePath=rest.join("/"),[key2,filename]=relativePath.split("%");return{device,category,key:key2,filename,pathV1:unifiedPath.split("%")[0]+".md"}}async createPluginDataExFileV2(unifiedPathV2,loaded){const{category,key:key2,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(!function isLoadedEntry(doc){return"type"in doc&&("newnote"==doc.type||"plain"==doc.type)&&"data"in doc}(d4)){this._log(`The file ${unifiedPathV2} is not a note`,LOG_LEVEL_VERBOSE);return!1}loaded=d4}const confKey=`${categoryToFolder(category,device)}${key2}`,relativeFilename=`${categoryToFolder(category,"")}${"CONFIG"==category||"SNIPPET"==category?"":key2+"/"}${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));(function setManifest(key2,manifest){const old=pluginManifests.get(key2);if(!old||isObjectDifferent(manifest,old)){pluginManifests.set(key2,manifest);pluginManifestStore.set(pluginManifests)}})(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:key2,pathV1}=this.parseUnifiedPath(unifiedPathV2);if(""!=category)return new PluginDataExDisplayV2({documentPath:pathV1,category,name:key2,term:`${device}`,files:[],mtime:0})}async updatePluginListV2(showMessage,unifiedFilenameWithKey){try{this.updatingV2Count++;pluginV2Progress.set(this.updatingV2Count);const{pathV1}=this.parseUnifiedPath(unifiedFilenameWithKey),oldEntry=this.pluginList.find((e3=>e3.documentPath==pathV1));let entry;if(oldEntry&&oldEntry instanceof PluginDataExDisplayV2)oldEntry instanceof PluginDataExDisplayV2&&(entry=oldEntry);else{const newEntry=this.createPluginDataFromV2(unifiedFilenameWithKey);newEntry&&(entry=newEntry)}if(!entry)return;const file=await this.createPluginDataExFileV2(unifiedFilenameWithKey);if(file)await entry.setFile(file);else{entry.deleteFile(unifiedFilenameWithKey);0==entry.files.length&&(this.pluginList=this.pluginList.filter((e3=>e3.documentPath!=pathV1)))}const newList=this.pluginList.filter((e3=>e3.documentPath!=entry.documentPath));newList.push(entry);this.pluginList=newList;scheduleTask("updatePluginListV2",100,(()=>{pluginList.set(this.pluginList)}))}finally{this.updatingV2Count--;pluginV2Progress.set(this.updatingV2Count)}}async migrateV1ToV2(showMessage,entry){var _a8;const v1Path=entry.path;this._log(`Migrating ${entry.path} to V2`,showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);if(entry.deleted){this._log(`The entry ${v1Path} is already deleted`,LOG_LEVEL_VERBOSE);return}if(!v1Path.endsWith(".md")&&!v1Path.startsWith(ICXHeader)){this._log(`The entry ${v1Path} is not a customisation sync binder`,LOG_LEVEL_VERBOSE);return}if(-1!==v1Path.indexOf("%")){this._log(`The entry ${v1Path} is already migrated`,LOG_LEVEL_VERBOSE);return}const loadedEntry=await this.localDatabase.getDBEntry(v1Path);if(!loadedEntry){this._log(`The entry ${v1Path} is not found`,LOG_LEVEL_VERBOSE);return}const pluginData=deserialize(getDocDataAsArray(loadedEntry.data),{}),prefixPath=v1Path.slice(0,-3)+"%",category=pluginData.category;for(const f4 of pluginData.files){const stripTable={CONFIG:0,THEME:2,SNIPPET:1,PLUGIN_MAIN:2,PLUGIN_DATA:2,PLUGIN_ETC:2},deletePrefixCount=null!=(_a8=null==stripTable?void 0:stripTable[category])?_a8:1,relativeFilename=f4.filename.split("/").slice(deletePrefixCount).join("/"),v2Path=prefixPath+relativeFilename;this._log(`Migrating ${v1Path} / ${relativeFilename} to ${v2Path}`,LOG_LEVEL_VERBOSE);const newId=await this.plugin.$$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.plugin.$$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.plugin.$$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.plugin.$$askReload();return!0}catch(ex){this._log(`Applying ${data.displayName||data.name}.. Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async deleteData(data){try{if(data.documentPath){const delList=[];if(this.useV2){const deleteList=this.pluginList.filter((e3=>e3.documentPath==data.documentPath)).filter((e3=>e3 instanceof PluginDataExDisplayV2)).map((e3=>e3.files)).flat();for(const e3 of deleteList)delList.push(e3.path)}delList.push(data.documentPath);const p4=delList.map((async e3=>{await this.deleteConfigOnDatabase(e3);await this.updatePluginList(!1,e3)}));await Promise.allSettled(p4);this._log(`Deleted: ${data.category}/${data.name} of ${data.category} (${delList.length} items)`,LOG_LEVEL_NOTICE)}return!0}catch(ex){this._log(`Failed to delete: ${data.documentPath}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async $anyModuleParsedReplicationResultItem(docs){if(docs._id.startsWith(ICXHeader)){this._isThisModuleEnabled()&&await this.updatePluginList(!1,docs.path?docs.path:this.getPath(docs));if(this._isThisModuleEnabled()&&this.plugin.settings.notifyPluginOrSettingUpdated&&(!this.pluginDialog||this.pluginDialog&&!this.pluginDialog.isOpened())){const fragment=createFragment((doc=>{doc.createEl("span",void 0,(a2=>{a2.appendText("Some configuration has been arrived, Press ");a2.appendChild(a2.createEl("a",void 0,(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{this.showPluginSyncModal()}))})));a2.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.")}))})),updatedPluginKey="popupUpdated-plugins";scheduleTask(updatedPluginKey,1e3,(async()=>{var _a8;const popup=await memoIfNotExist(updatedPluginKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a8=null==popup?void 0:popup.noticeEl)?void 0:_a8.isShown())||memoObject(updatedPluginKey,new import_obsidian.Notice(fragment,0));scheduleTask(updatedPluginKey+"-close",2e4,(()=>{var _a9;const popup2=retrieveMemoObject(updatedPluginKey);if(popup2){(null==(_a9=null==popup2?void 0:popup2.noticeEl)?void 0:_a9.isShown())&&popup2.hide();disposeMemoObject(updatedPluginKey)}}))}))}return!0}}async $everyRealizeSettingSyncMode(){var _a8;null==(_a8=this.periodicPluginSweepProcessor)||_a8.disable();if(!this._isMainReady)return!0;if(!this._isMainSuspended())return!0;if(!this._isThisModuleEnabled())return!0;this.settings.autoSweepPlugins&&await this.scanAllConfigFiles(!1);this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic&&!this.settings.watchInternalFileChanges?6e4:0);return!0}async makeEntryFromFile(path2){const stat=await this.plugin.storageAccess.statHidden(path2);let version2,displayName;if(!stat)return!1;const contentBin=await this.plugin.storageAccess.readHiddenFileBinary(path2);let content;try{content=await arrayBufferToBase64(contentBin);if(path2.toLowerCase().endsWith("/manifest.json")){const v2=readString(new Uint8Array(contentBin));try{const json=JSON.parse(v2);"version"in json&&(version2=`${json.version}`);"name"in json&&(displayName=`${json.name}`)}catch(ex){this._log(`Configuration sync data: ${path2} looks like manifest, but could not read the version`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE)}}}catch(ex){this._log(`The file ${path2} could not be encoded`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}const mtime=stat.mtime;return{filename:path2.substring(this.app.vault.configDir.length+1),data:content,mtime,size:stat.size,version:version2,displayName}}async storeCustomisationFileV2(path2,term,force=!1){const vf=this.filenameWithUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,(async()=>{const prefixedFileName=vf,id=await this.path2id(prefixedFileName),stat=await this.plugin.storageAccess.statHidden(path2);if(!stat)return!1;const mtime=stat.mtime,content=await this.plugin.storageAccess.readHiddenFileBinary(path2),contentBlob=createBlob([DUMMY_HEAD,DUMMY_END,...await arrayBufferToBase64(content)]);try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:contentBlob,mtime,ctime:mtime,datatype:"plain",size:contentBlob.size,children:[],deleted:!1,type:"plain",eden:{}};else{if(isMarkedAsSameChanges(prefixedFileName,[old.mtime,mtime+1])==EVEN){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (Already checked the same)`,-1);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),oldContentArray=base64ToArrayBuffer(dataSrc.substring(dataStart+DUMMY_END.length));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.plugin.$$getDeviceAndVaultName();if(""==term){this._log("We have to configure the device name",LOG_LEVEL_NOTICE);return}if(this.useV2)return await this.storeCustomisationFileV2(path2,term);const vf=this.filenameToUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,(async()=>{const category=this.getFileCategory(path2);let mtime=0,fileTargets=[];const name="CONFIG"==category||"SNIPPET"==category?path2.split("/").reverse()[0]:path2.split("/").reverse()[1],parentPath=path2.split("/").slice(0,-1).join("/"),prefixedFileName=this.filenameToUnifiedKey(path2,term),id=await this.path2id(prefixedFileName),dt={category,files:[],name,mtime:0,term};if("CONFIG"==category||"SNIPPET"==category||"PLUGIN_ETC"==category||"PLUGIN_DATA"==category){fileTargets=[path2];"PLUGIN_ETC"==category&&(dt.displayName=path2.split("/").slice(-1).join("/"))}else"PLUGIN_MAIN"==category?fileTargets=["manifest.json","main.js","styles.css"].map((e3=>`${parentPath}/${e3}`)):"THEME"==category&&(fileTargets=["manifest.json","theme.css"].map((e3=>`${parentPath}/${e3}`)));for(const target of fileTargets){const data=await this.makeEntryFromFile(target);if(0!=data){data.version&&(dt.version=data.version);data.displayName&&(dt.displayName=data.displayName);mtime=0==mtime?data.mtime:(data.mtime+mtime)/2;dt.files.push(data)}else this._log(`Config: skipped (Possibly is not exist): ${target} `,LOG_LEVEL_VERBOSE)}dt.mtime=mtime;if(0==dt.files.length){this._log(`Nothing left: deleting.. ${path2}`);await this.deleteConfigOnDatabase(prefixedFileName);await this.updatePluginList(!1,prefixedFileName);return}const content=createTextBlob(serialize(dt));try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:content,mtime,ctime:mtime,datatype:"newnote",size:content.size,children:[],deleted:!1,type:"newnote",eden:{}};else{if(old.mtime==mtime)return!0;const oldC=await this.localDatabase.getDBEntryFromMeta(old,!1,!1);if(oldC){const d4=await deserialize(getDocDataAsArray(oldC.data),{});if(d4.files.length==dt.files.length){const diffs=d4.files.map((previous=>({prev:previous,curr:dt.files.find((e3=>e3.filename==previous.filename))}))).map((async e3=>{var _a8,_b4;try{return await isDocContentSame(null!=(_b4=null==(_a8=e3.curr)?void 0:_a8.data)?_b4:[],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),key2=`${path2}-${storageMTime}`;if(this.recentProcessedInternalFiles.contains(key2))return!0;this.recentProcessedInternalFiles=[key2,...this.recentProcessedInternalFiles].slice(0,100);scheduleTask(this.filenameToUnifiedKey(path2),100,(async()=>{await this.storeCustomizationFiles(path2)}));return!0}async scanAllConfigFiles(showMessage){await shareRunningResult("scanAllConfigFiles",(async()=>{var _a8;const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;this._log("Scanning customizing files.",logLevel,"scan-all-config");const term=this.plugin.$$getDeviceAndVaultName();if(""==term){this._log("We have to configure the device name",LOG_LEVEL_NOTICE);return}const filesAll=await this.scanInternalFiles();if(this.useV2){const filesAllUnified=filesAll.filter((e3=>this.isTargetPath(e3))).map((e3=>[this.filenameWithUnifiedKey(e3,term),e3])),localFileMap=new Map(filesAllUnified.map((e3=>[e3[0],e3[1]]))),prefix=this.unifiedKeyPrefixOfTerminal(term),entries2=this.localDatabase.findEntries(prefix+"",`${prefix}􏿿`,{include_docs:!0}),tasks3=[],semaphore=Semaphore(10);for await(const item of entries2)-1===item.path.indexOf("%")&&tasks3.push((async()=>{const releaser=await semaphore.acquire();try{const unifiedFilenameWithKey=`${item._id}`,localPath=localFileMap.get(unifiedFilenameWithKey);if(localPath){await this.storeCustomisationFileV2(localPath,term);localFileMap.delete(unifiedFilenameWithKey)}else await this.deleteConfigOnDatabase(unifiedFilenameWithKey)}catch(ex){this._log(`scanAllConfigFiles - Error: ${item._id}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}}));await Promise.all(tasks3.map((e3=>e3())));const taskExtra=[];for(const[,filePath]of localFileMap)taskExtra.push((async()=>{const releaser=await semaphore.acquire();try{await this.storeCustomisationFileV2(filePath,term)}catch(ex){this._log(`scanAllConfigFiles - Error: ${filePath}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}}));await Promise.all(taskExtra.map((e3=>e3())));fireAndForget((()=>this.updatePluginList(!1)))}else{const files=filesAll.filter((e3=>this.isTargetPath(e3))).map((e3=>({key:this.filenameToUnifiedKey(e3),file:e3}))),virtualPathsOfLocalFiles=[...new Set(files.map((e3=>e3.key)))];let deleteCandidate=(await this.localDatabase.allDocsRaw({startkey:ICXHeader+"",endkey:`${ICXHeader}􏿿`,include_docs:!0})).rows.map((e3=>e3.doc)).filter((e3=>!e3.deleted)).map((e3=>this.getPath(e3))).filter((e3=>e3.startsWith(`${ICXHeader}${term}/`)));for(const vp of virtualPathsOfLocalFiles){const p4=null==(_a8=files.find((e3=>e3.key==vp)))?void 0:_a8.file;if(p4){await this.storeCustomizationFiles(p4);deleteCandidate=deleteCandidate.filter((e3=>e3!=vp))}else this._log(`scanAllConfigFiles - File not found: ${vp}`,LOG_LEVEL_VERBOSE)}for(const vp of deleteCandidate)await this.deleteConfigOnDatabase(vp);fireAndForget((()=>this.updatePluginList(!1)))}}))}async deleteConfigOnDatabase(prefixedFileName,forceWrite=!1){const mtime=(new Date).getTime();return await serialized("file-x-"+prefixedFileName,(async()=>{try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted (Not found on database)`);return!0}if(old.deleted){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted`);return!0}saveData={...old,mtime,size:0,children:[],deleted:!0,type:"newnote"};await this.localDatabase.putRaw(saveData);await this.updatePluginList(!1,prefixedFileName);this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Done`);return!0}catch(ex){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async scanInternalFiles(){return(await this.getFiles(this.app.vault.configDir,2)).filter((e3=>e3.startsWith("."))).filter((e3=>!e3.startsWith(".trash")))}async $allAskUsingOptionalSyncFeature(opt){await this._askHiddenFileConfiguration(opt);return!0}async _askHiddenFileConfiguration(opt){const choices=[];choices.push("Yes, Enable it");choices.push("No, Disable it");choices.push("Later");const ret=await this.plugin.confirm.askSelectStringDialogue("Would you like to enable **Customization sync**?\n\n> [!DETAILS]-\n> This feature allows you to sync your customisations -- such as configurations, themes, snippets, and plugins -- across your devices in a fully controlled manner, unlike the fully automatic behaviour of hidden file synchronisation.\n> \n> You may use this feature alongside hidden file synchronisation. When both features are enabled, items configured as `Automatic` in this feature will be managed by **hidden file synchronisation**.\n> Do not worry, you will be prompted to enable or keep disabled **hidden file synchronisation** after this dialogue.\n",choices,{defaultAction:"Later",timeout:40,title:"Customisation sync"});"Yes, Enable it"==ret?await this.configureHiddenFileSync("CUSTOMIZE"):"No, Disable it"==ret&&await this.configureHiddenFileSync("DISABLE_CUSTOM")}$anyGetOptionalConflictCheckMethod(path2){return isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)?Promise.resolve("newer"):Promise.resolve(!1)}$allSuspendExtraSync(){if(this.plugin.settings.usePluginSync||this.plugin.settings.autoSweepPlugins){this._log("Customisation sync have been temporarily disabled. Please enable them after the fetching, if you need them.",LOG_LEVEL_NOTICE);this.plugin.settings.usePluginSync=!1;this.plugin.settings.autoSweepPlugins=!1}return Promise.resolve(!0)}async $anyConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode)}async configureHiddenFileSync(mode){if("DISABLE"!=mode){if("CUSTOMIZE"==mode){if(!this.plugin.$$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.plugin.$$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}};getHttpHandlerExtensionConfiguration=runtimeConfig=>({setHttpHandler(handler){runtimeConfig.httpHandler=handler},httpHandler:()=>runtimeConfig.httpHandler,updateHttpClientConfig(key2,value){var _a8;null==(_a8=runtimeConfig.httpHandler)||_a8.updateHttpClientConfig(key2,value)},httpHandlerConfigs:()=>runtimeConfig.httpHandler.httpHandlerConfigs()});resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>({httpHandler:httpHandlerExtensionConfiguration.httpHandler()});(function(HttpAuthLocation2){HttpAuthLocation2.HEADER="header";HttpAuthLocation2.QUERY="query"})(HttpAuthLocation||(HttpAuthLocation={}));(function(HttpApiKeyAuthLocation2){HttpApiKeyAuthLocation2.HEADER="header";HttpApiKeyAuthLocation2.QUERY="query"})(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={}));(function(EndpointURLScheme2){EndpointURLScheme2.HTTP="http";EndpointURLScheme2.HTTPS="https"})(EndpointURLScheme||(EndpointURLScheme={}));(function(AlgorithmId2){AlgorithmId2.MD5="md5";AlgorithmId2.CRC32="crc32";AlgorithmId2.CRC32C="crc32c";AlgorithmId2.SHA1="sha1";AlgorithmId2.SHA256="sha256"})(AlgorithmId||(AlgorithmId={}));(function(FieldPosition2){FieldPosition2[FieldPosition2.HEADER=0]="HEADER";FieldPosition2[FieldPosition2.TRAILER=1]="TRAILER"})(FieldPosition||(FieldPosition={}));SMITHY_CONTEXT_KEY="__smithy_context";(function(IniSectionType2){IniSectionType2.PROFILE="profile";IniSectionType2.SSO_SESSION="sso-session";IniSectionType2.SERVICES="services"})(IniSectionType||(IniSectionType={}));(function(RequestHandlerProtocol2){RequestHandlerProtocol2.HTTP_0_9="http/0.9";RequestHandlerProtocol2.HTTP_1_0="http/1.0";RequestHandlerProtocol2.TDS_8_0="tds/8.0"})(RequestHandlerProtocol||(RequestHandlerProtocol={}));HttpRequest=class _HttpRequest{constructor(options){this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?":"!==options.protocol.slice(-1)?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?"/"!==options.path.charAt(0)?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request2){const cloned=new _HttpRequest({...request2,headers:{...request2.headers}});cloned.query&&(cloned.query=function cloneQuery(query3){return Object.keys(query3).reduce(((carry,paramName)=>{const param=query3[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}}),{})}(cloned.query));return cloned}static isInstance(request2){if(!request2)return!1;const req=request2;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&"object"==typeof req.query&&"object"==typeof req.headers}clone(){return _HttpRequest.clone(this)}};HttpResponse=class{constructor(options){this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return!1;const resp=response;return"number"==typeof resp.statusCode&&"object"==typeof resp.headers}};addExpectContinueMiddlewareOptions={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0};getAddExpectContinuePlugin=options=>({applyToStack:clientStack=>{clientStack.add(function addExpectContinueMiddleware(options){return next2=>async args=>{var _a8,_b4;const{request:request2}=args;HttpRequest.isInstance(request2)&&request2.body&&"node"===options.runtime&&"FetchHttpHandler"!==(null==(_b4=null==(_a8=options.requestHandler)?void 0:_a8.constructor)?void 0:_b4.name)&&(request2.headers={...request2.headers,Expect:"100-continue"});return next2({...args,request:request2})}}(options),addExpectContinueMiddlewareOptions)}});DEFAULT_REQUEST_CHECKSUM_CALCULATION=(RequestChecksumCalculation={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"}).WHEN_SUPPORTED;ResponseChecksumValidation={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"};DEFAULT_RESPONSE_CHECKSUM_VALIDATION=RequestChecksumCalculation.WHEN_SUPPORTED;(function(ChecksumAlgorithm3){ChecksumAlgorithm3.MD5="MD5";ChecksumAlgorithm3.CRC32="CRC32";ChecksumAlgorithm3.CRC32C="CRC32C";ChecksumAlgorithm3.CRC64NVME="CRC64NVME";ChecksumAlgorithm3.SHA1="SHA1";ChecksumAlgorithm3.SHA256="SHA256"})(ChecksumAlgorithm||(ChecksumAlgorithm={}));(function(ChecksumLocation2){ChecksumLocation2.HEADER="header";ChecksumLocation2.TRAILER="trailer"})(ChecksumLocation||(ChecksumLocation={}));DEFAULT_CHECKSUM_ALGORITHM=ChecksumAlgorithm.CRC32;(function(SelectorType3){SelectorType3.ENV="env";SelectorType3.CONFIG="shared config entry"})(SelectorType||(SelectorType={}));getDateHeader=response=>{var _a8,_b4,_c3;return HttpResponse.isInstance(response)?null!=(_c3=null==(_a8=response.headers)?void 0:_a8.date)?_c3:null==(_b4=response.headers)?void 0:_b4.Date:void 0};getSkewCorrectedDate=systemClockOffset=>new Date(Date.now()+systemClockOffset);isClockSkewed=(clockTime,systemClockOffset)=>Math.abs(getSkewCorrectedDate(systemClockOffset).getTime()-clockTime)>=3e5;getUpdatedSystemClockOffset=(clockTime,currentSystemClockOffset)=>{const clockTimeInMs=Date.parse(clockTime);return isClockSkewed(clockTimeInMs,currentSystemClockOffset)?clockTimeInMs-Date.now():currentSystemClockOffset};throwSigningPropertyError=(name,property)=>{if(!property)throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);return property};validateSigningProperties=async signingProperties=>{var _a8,_b4,_c3;const context2=throwSigningPropertyError("context",signingProperties.context),config=throwSigningPropertyError("config",signingProperties.config),authScheme=null==(_c3=null==(_b4=null==(_a8=context2.endpointV2)?void 0:_a8.properties)?void 0:_b4.authSchemes)?void 0:_c3[0],signerFunction=throwSigningPropertyError("signer",config.signer);return{config,signer:await signerFunction(authScheme),signingRegion:null==signingProperties?void 0:signingProperties.signingRegion,signingRegionSet:null==signingProperties?void 0:signingProperties.signingRegionSet,signingName:null==signingProperties?void 0:signingProperties.signingName}};AwsSdkSigV4Signer=class{async sign(httpRequest,identity,signingProperties){var _a8,_b4,_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!=(_b4=null==(_a8=null==handlerExecutionContext?void 0:handlerExecutionContext.authSchemes)?void 0:_a8.length)&&_b4){const[first,second]=handlerExecutionContext.authSchemes;if("sigv4a"===(null==first?void 0:first.name)&&"sigv4"===(null==second?void 0:second.name)){signingRegion=null!=(_c3=null==second?void 0:second.signingRegion)?_c3:signingRegion;signingName=null!=(_d2=null==second?void 0:second.signingName)?_d2:signingName}}return await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion,signingService:signingName})}errorHandler(signingProperties){return error=>{var _a8;const serverTime=null!=(_a8=error.ServerTime)?_a8:getDateHeader(error.$response);if(serverTime){const config=throwSigningPropertyError("config",signingProperties.config),initialSystemClockOffset=config.systemClockOffset;config.systemClockOffset=getUpdatedSystemClockOffset(serverTime,config.systemClockOffset);config.systemClockOffset!==initialSystemClockOffset&&error.$metadata&&(error.$metadata.clockSkewCorrected=!0)}throw error}}successHandler(httpResponse,signingProperties){const dateHeader=getDateHeader(httpResponse);if(dateHeader){const config=throwSigningPropertyError("config",signingProperties.config);config.systemClockOffset=getUpdatedSystemClockOffset(dateHeader,config.systemClockOffset)}}};AwsSdkSigV4ASigner=class extends AwsSdkSigV4Signer{async sign(httpRequest,identity,signingProperties){var _a8,_b4;if(!HttpRequest.isInstance(httpRequest))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const{config,signer,signingRegion,signingRegionSet,signingName}=await validateSigningProperties(signingProperties),configResolvedSigningRegionSet=await(null==(_a8=config.sigv4aSigningRegionSet)?void 0:_a8.call(config)),multiRegionOverride=(null!=(_b4=null!=configResolvedSigningRegionSet?configResolvedSigningRegionSet:signingRegionSet)?_b4:[signingRegion]).join(",");return await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion:multiRegionOverride,signingService:signingName})}};getSmithyContext2=context2=>context2.__smithy_context||(context2.__smithy_context={});normalizeProvider=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};resolveAuthOptions=(candidateAuthOptions,authSchemePreference)=>{if(!authSchemePreference||0===authSchemePreference.length)return candidateAuthOptions;const preferredAuthOptions=[];for(const preferredSchemeName of authSchemePreference)for(const candidateAuthOption of candidateAuthOptions)candidateAuthOption.schemeId.split("#")[1]===preferredSchemeName&&preferredAuthOptions.push(candidateAuthOption);for(const candidateAuthOption of candidateAuthOptions)preferredAuthOptions.find((({schemeId})=>schemeId===candidateAuthOption.schemeId))||preferredAuthOptions.push(candidateAuthOption);return preferredAuthOptions};httpAuthSchemeMiddleware=(config,mwOptions)=>(next2,context2)=>async args=>{var _a8;const options=config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config,context2,args.input)),authSchemePreference=config.authSchemePreference?await config.authSchemePreference():[],resolvedOptions=resolveAuthOptions(options,authSchemePreference),authSchemes=function convertHttpAuthSchemesToMap(httpAuthSchemes){const map4=new Map;for(const scheme of httpAuthSchemes)map4.set(scheme.schemeId,scheme);return map4}(config.httpAuthSchemes),smithyContext=getSmithyContext2(context2),failureReasons=[];for(const option of resolvedOptions){const scheme=authSchemes.get(option.schemeId);if(!scheme){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);continue}const identityProvider=scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));if(!identityProvider){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties={},signingProperties={}}=(null==(_a8=option.propertiesExtractor)?void 0:_a8.call(option,config,context2))||{};option.identityProperties=Object.assign(option.identityProperties||{},identityProperties);option.signingProperties=Object.assign(option.signingProperties||{},signingProperties);smithyContext.selectedHttpAuthScheme={httpAuthOption:option,identity:await identityProvider(option.identityProperties),signer:scheme.signer};break}if(!smithyContext.selectedHttpAuthScheme)throw new Error(failureReasons.join("\n"));return next2(args)};httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};getHttpAuthSchemeEndpointRuleSetPlugin=(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider})=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpAuthSchemeMiddleware(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}});deserializerMiddleware=(options,deserializer)=>(next2,context2)=>async args=>{var _a8,_b4,_c3,_d2;const{response}=await next2(args);try{return{response,output:await deserializer(response,options)}}catch(error){Object.defineProperty(error,"$response",{value:response});if(!("$metadata"in error)){const hint="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{error.message+="\n "+hint}catch(e3){context2.logger&&"NoOpLogger"!==(null==(_b4=null==(_a8=context2.logger)?void 0:_a8.constructor)?void 0:_b4.name)?null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,hint):console.warn(hint)}void 0!==error.$responseBodyText&&error.$response&&(error.$response.body=error.$responseBodyText);try{if(HttpResponse.isInstance(response)){const{headers={}}=response,headerEntries=Object.entries(headers);error.$metadata={httpStatusCode:response.statusCode,requestId:findHeader(/^x-[\w-]+-request-?id$/,headerEntries),extendedRequestId:findHeader(/^x-[\w-]+-id-2$/,headerEntries),cfId:findHeader(/^x-[\w-]+-cf-id$/,headerEntries)}}}catch(e3){}}throw error}};findHeader=(pattern,headers)=>(headers.find((([k2])=>k2.match(pattern)))||[void 0,void 0])[1];serializerMiddleware=(options,serializer)=>(next2,context2)=>async args=>{var _a8;const endpoint=(null==(_a8=context2.endpointV2)?void 0:_a8.url)&&options.urlParser?async()=>options.urlParser(context2.endpointV2.url):options.endpoint;if(!endpoint)throw new Error("No valid endpoint provider available.");const request2=await serializer(args.input,{...options,endpoint});return next2({...args,request:request2})};deserializerMiddlewareOption={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0};(serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}).name;defaultErrorHandler=signingProperties=>error=>{throw error};defaultSuccessHandler=(httpResponse,signingProperties)=>{};httpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const scheme=getSmithyContext2(context2).selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme,output=await next2({...args,request:await signer.sign(args.request,identity,signingProperties)}).catch((signer.errorHandler||defaultErrorHandler)(signingProperties));(signer.successHandler||defaultSuccessHandler)(output.response,signingProperties);return output};httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"};getHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpSigningMiddleware(),httpSigningMiddlewareOptions)}});normalizeProvider2=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};alphabetByEncoding={};alphabetByValue=new Array(64);for(let i2=0,start="A".charCodeAt(0),limit="Z".charCodeAt(0);i2+start<=limit;i2++){const char=String.fromCharCode(i2+start);alphabetByEncoding[char]=i2;alphabetByValue[i2]=char}for(let i2=0,start="a".charCodeAt(0),limit="z".charCodeAt(0);i2+start<=limit;i2++){const char=String.fromCharCode(i2+start),index6=i2+26;alphabetByEncoding[char]=index6;alphabetByValue[index6]=char}for(let i2=0;i2<10;i2++){alphabetByEncoding[i2.toString(10)]=i2+52;const char=i2.toString(10),index6=i2+52;alphabetByEncoding[char]=index6;alphabetByValue[index6]=char}alphabetByEncoding["+"]=62;alphabetByValue[62]="+";alphabetByEncoding["/"]=63;alphabetByValue[63]="/";bitsPerLetter=6;bitsPerByte=8;maxLetterValue=63;fromBase64=input=>{let totalByteLength=input.length/4*3;"=="===input.slice(-2)?totalByteLength-=2:"="===input.slice(-1)&&totalByteLength--;const out=new ArrayBuffer(totalByteLength),dataView=new DataView(out);for(let i2=0;i2>=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)};fromUtf8=input=>(new TextEncoder).encode(input);toUint8Array=data=>"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data);toUtf8=input=>{if("string"==typeof input)return input;if("object"!=typeof input||"number"!=typeof input.byteOffset||"number"!=typeof input.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(input)};Uint8ArrayBlobAdapter=class _Uint8ArrayBlobAdapter extends Uint8Array{static fromString(source2,encoding="utf-8"){switch(typeof source2){case"string":return function transformFromString(str,encoding){return"base64"===encoding?Uint8ArrayBlobAdapter.mutate(fromBase64(str)):Uint8ArrayBlobAdapter.mutate(fromUtf8(str))}(source2,encoding);default:throw new Error(`Unsupported conversion from ${typeof source2} to Uint8ArrayBlobAdapter.`)}}static mutate(source2){Object.setPrototypeOf(source2,_Uint8ArrayBlobAdapter.prototype);return source2}transformToString(encoding="utf-8"){return function transformToString(payload,encoding="utf-8"){return"base64"===encoding?toBase64(payload):toUtf8(payload)}(this,encoding)}};ReadableStreamRef="function"==typeof ReadableStream?ReadableStream:function(){};ChecksumStream=class extends ReadableStreamRef{};isReadableStream=stream=>{var _a8;return"function"==typeof ReadableStream&&((null==(_a8=null==stream?void 0:stream.constructor)?void 0:_a8.name)===ReadableStream.name||stream instanceof ReadableStream)};createChecksumStream=({expectedChecksum,checksum,source:source2,checksumSourceLocation,base64Encoder})=>{var _a8,_b4;if(!isReadableStream(source2))throw new Error(`@smithy/util-stream: unsupported source type ${null!=(_b4=null==(_a8=null==source2?void 0:source2.constructor)?void 0:_a8.name)?_b4:source2} in ChecksumStream.`);const encoder2=null!=base64Encoder?base64Encoder:toBase64;if("function"!=typeof TransformStream)throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");const transform2=new TransformStream({start(){},async transform(chunk,controller){checksum.update(chunk);controller.enqueue(chunk)},async flush(controller){const digest=await checksum.digest(),received=encoder2(digest);if(expectedChecksum!==received){const error=new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);controller.error(error)}else controller.terminate()}});source2.pipeThrough(transform2);const readable2=transform2.readable;Object.setPrototypeOf(readable2,ChecksumStream.prototype);return readable2};ByteArrayCollector=class{constructor(allocByteArray){this.allocByteArray=allocByteArray;this.byteLength=0;this.byteArrays=[]}push(byteArray){this.byteArrays.push(byteArray);this.byteLength+=byteArray.byteLength}flush(){if(1===this.byteArrays.length){const bytes=this.byteArrays[0];this.reset();return bytes}const aggregation=this.allocByteArray(this.byteLength);let cursor=0;for(let i2=0;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=function modeOf(chunk,allowBuffer=!0){return allowBuffer&&"undefined"!=typeof Buffer&&chunk instanceof Buffer?2:chunk instanceof Uint8Array?1:"string"==typeof chunk?0:-1}(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=function merge(buffers,mode,chunk){switch(mode){case 0:buffers[0]+=chunk;return sizeOf(buffers[0]);case 1:case 2:buffers[mode].push(chunk);return sizeOf(buffers[mode])}}(buffers,mode,chunk);if(!streamBufferingLoggedWarning&&bytesSeen>2*size){streamBufferingLoggedWarning=!0;null==logger2||logger2.warn(`@smithy/util-stream - stream chunk size ${chunkSize2} is below threshold of ${size}, automatically buffering.`)}newSize>=size?controller.enqueue(flush(buffers,mode)):await pull(controller)}}};return new ReadableStream({pull})};getAwsChunkedEncodingStream=(readableStream,options)=>{const{base64Encoder,bodyLengthChecker,checksumAlgorithmFn,checksumLocationName,streamHasher}=options,checksumRequired=void 0!==base64Encoder&&void 0!==bodyLengthChecker&&void 0!==checksumAlgorithmFn&&void 0!==checksumLocationName&&void 0!==streamHasher,digest=checksumRequired?streamHasher(checksumAlgorithmFn,readableStream):void 0,reader=readableStream.getReader();return new ReadableStream({async pull(controller){const{value,done}=await reader.read();if(done){controller.enqueue("0\r\n");if(checksumRequired){const checksum=base64Encoder(await digest);controller.enqueue(`${checksumLocationName}:${checksum}\r\n`);controller.enqueue("\r\n")}controller.close()}else controller.enqueue(`${(bodyLengthChecker(value)||0).toString(16)}\r\n${value}\r\n`)}})};escapeUri=uri=>encodeURIComponent(uri).replace(/[!'()*]/g,hexEncode);hexEncode=c3=>`%${c3.charCodeAt(0).toString(16).toUpperCase()}`;keepAliveSupport={supported:void 0};FetchHttpHandler=class _FetchHttpHandler{static create(instanceOrOptions){return"function"==typeof(null==instanceOrOptions?void 0:instanceOrOptions.handle)?instanceOrOptions:new _FetchHttpHandler(instanceOrOptions)}constructor(options){if("function"==typeof options)this.configProvider=options().then((opts=>opts||{}));else{this.config=null!=options?options:{};this.configProvider=Promise.resolve(this.config)}void 0===keepAliveSupport.supported&&(keepAliveSupport.supported=Boolean("undefined"!=typeof Request&&"keepalive"in createRequest("https://[::1]")))}destroy(){}async handle(request2,{abortSignal}={}){var _a8,_b4,_c3;this.config||(this.config=await this.configProvider);const requestTimeoutInMs=this.config.requestTimeout,keepAlive=!0===this.config.keepAlive,credentials=this.config.credentials;if(null==abortSignal?void 0:abortSignal.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path2=request2.path;const queryString=buildQueryString(request2.query||{});queryString&&(path2+=`?${queryString}`);request2.fragment&&(path2+=`#${request2.fragment}`);let auth="";null==request2.username&&null==request2.password||(auth=`${null!=(_a8=request2.username)?_a8:""}:${null!=(_b4=request2.password)?_b4:""}@`);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(key2,value){this.config=void 0;this.configProvider=this.configProvider.then((config=>{config[key2]=value;return config}))}httpHandlerConfigs(){var _a8;return null!=(_a8=this.config)?_a8:{}}};streamCollector=async stream=>{var _a8;return"function"==typeof Blob&&stream instanceof Blob||"Blob"===(null==(_a8=stream.constructor)?void 0:_a8.name)?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await stream.arrayBuffer()):async function collectBlob(blob){const base64=await function readToBase64(blob){return new Promise(((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{var _a8;if(2!==reader.readyState)return reject(new Error("Reader aborted too early"));const result=null!=(_a8=reader.result)?_a8:"",commaIndex=result.indexOf(","),dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)}))}(blob),arrayBuffer=fromBase64(base64);return new Uint8Array(arrayBuffer)}(stream):async function collectStream(stream){const chunks=[],reader=stream.getReader();let isDone=!1,length=0;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}(stream)};SHORT_TO_HEX={};HEX_TO_SHORT={};for(let i2=0;i2<256;i2++){let encodedByte=i2.toString(16).toLowerCase();1===encodedByte.length&&(encodedByte=`0${encodedByte}`);SHORT_TO_HEX[i2]=encodedByte;HEX_TO_SHORT[encodedByte]=i2}sdkStreamMixin=stream=>{var _a8,_b4;if(!isBlobInstance(stream)&&!isReadableStream(stream)){const name=(null==(_b4=null==(_a8=null==stream?void 0:stream.__proto__)?void 0:_a8.constructor)?void 0:_b4.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)};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(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()})(stream);if(isReadableStream(stream))return stream;throw new Error(`Cannot transform payload to web stream, got ${stream}`)}})};isBlobInstance=stream=>"function"==typeof Blob&&stream instanceof Blob;collectBody=async(streamBody=new Uint8Array,context2)=>{if(streamBody instanceof Uint8Array)return Uint8ArrayBlobAdapter.mutate(streamBody);if(!streamBody)return Uint8ArrayBlobAdapter.mutate(new Uint8Array);const fromContext=context2.streamCollector(streamBody);return Uint8ArrayBlobAdapter.mutate(await fromContext)};resolvedPath=(resolvedPath2,input,memberName,labelValueProvider,uriLabel,isGreedyLabel)=>{if(null==input||void 0===input[memberName])throw new Error("No value provided for input HTTP label: "+memberName+".");{const labelValue=labelValueProvider();if(labelValue.length<=0)throw new Error("Empty value provided for input HTTP label: "+memberName+".");resolvedPath2=resolvedPath2.replace(uriLabel,isGreedyLabel?labelValue.split("/").map((segment=>extendedEncodeURIComponent(segment))).join("/"):extendedEncodeURIComponent(labelValue))}return resolvedPath2};RequestBuilder=class{constructor(input,context2){this.input=input;this.context=context2;this.query={};this.method="";this.headers={};this.path="";this.body=null;this.hostname="";this.resolvePathStack=[]}async build(){const{hostname,protocol="https",port,path:basePath}=await this.context.endpoint();this.path=basePath;for(const resolvePath of this.resolvePathStack)resolvePath(this.path);return new HttpRequest({protocol,hostname:this.hostname||hostname,port,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(hostname){this.hostname=hostname;return this}bp(uriLabel){this.resolvePathStack.push((basePath=>{this.path=`${(null==basePath?void 0:basePath.endsWith("/"))?basePath.slice(0,-1):basePath||""}`+uriLabel}));return this}p(memberName,labelValueProvider,uriLabel,isGreedyLabel){this.resolvePathStack.push((path2=>{this.path=resolvedPath(path2,this.input,memberName,labelValueProvider,uriLabel,isGreedyLabel)}));return this}h(headers){this.headers=headers;return this}q(query3){this.query=query3;return this}b(body){this.body=body;return this}m(method){this.method=method;return this}};DefaultIdentityProviderConfig=class{constructor(config){this.authSchemes=new Map;for(const[key2,value]of Object.entries(config))void 0!==value&&this.authSchemes.set(key2,value)}getIdentityProvider(schemeId){return this.authSchemes.get(schemeId)}};isIdentityExpired=identity=>doesIdentityRequireRefresh(identity)&&identity.expiration.getTime()-Date.now()<3e5;doesIdentityRequireRefresh=identity=>void 0!==identity.expiration;memoizeIdentityProvider=(provider,isExpired,requiresRefresh)=>{if(void 0===provider)return;const normalizedProvider="function"!=typeof provider?async()=>Promise.resolve(provider):provider;let resolved,pending2,hasResult,isConstant=!1;const coalesceProvider=async options=>{pending2||(pending2=normalizedProvider(options));try{resolved=await pending2;hasResult=!0;isConstant=!1}finally{pending2=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,pending2,hasResult,isConstant=!1;const coalesceProvider=async()=>{pending2||(pending2=provider());try{resolved=await pending2;hasResult=!0;isConstant=!1}finally{pending2=void 0}return resolved};return void 0===isExpired?async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());return resolved}:async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());if(isConstant)return resolved;if(requiresRefresh&&!requiresRefresh(resolved)){isConstant=!0;return resolved}if(isExpired(resolved)){await coalesceProvider();return resolved}return resolved}};resolveAwsSdkSigV4AConfig=config=>{config.sigv4aSigningRegionSet=normalizeProvider2(config.sigv4aSigningRegionSet);return config};AMZ_DATE_HEADER=(AMZ_DATE_QUERY_PARAM="X-Amz-Date").toLowerCase();GENERATED_HEADERS=["authorization",AMZ_DATE_HEADER,"date"];SIGNATURE_HEADER="X-Amz-Signature".toLowerCase();TOKEN_HEADER="X-Amz-Security-Token".toLowerCase();ALWAYS_UNSIGNABLE_HEADERS={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0};PROXY_HEADER_PATTERN=/^proxy-/;SEC_HEADER_PATTERN=/^sec-/;EVENT_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256-PAYLOAD";signingKeyCache={};cacheQueue=[];createScope=(shortDate,region,service)=>`${shortDate}/${region}/${service}/aws4_request`;getSigningKey=async(sha256Constructor,credentials,shortDate,region,service)=>{const cacheKey=`${shortDate}:${region}:${service}:${toHex2(await hmac(sha256Constructor,credentials.secretAccessKey,credentials.accessKeyId))}:${credentials.sessionToken}`;if(cacheKey in signingKeyCache)return signingKeyCache[cacheKey];cacheQueue.push(cacheKey);for(;cacheQueue.length>50;)delete signingKeyCache[cacheQueue.shift()];let key2=`AWS4${credentials.secretAccessKey}`;for(const signable of[shortDate,region,service,"aws4_request"])key2=await hmac(sha256Constructor,key2,signable);return signingKeyCache[cacheKey]=key2};hmac=(ctor,secret,data)=>{const hash2=new ctor(secret);hash2.update(toUint8Array(data));return hash2.digest()};getCanonicalHeaders=({headers},unsignableHeaders,signableHeaders)=>{const canonical={};for(const headerName of Object.keys(headers).sort()){if(null==headers[headerName])continue;const canonicalHeaderName=headerName.toLowerCase();(canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS||(null==unsignableHeaders?void 0:unsignableHeaders.has(canonicalHeaderName))||PROXY_HEADER_PATTERN.test(canonicalHeaderName)||SEC_HEADER_PATTERN.test(canonicalHeaderName))&&(!signableHeaders||signableHeaders&&!signableHeaders.has(canonicalHeaderName))||(canonical[canonicalHeaderName]=headers[headerName].trim().replace(/\s+/g," "))}return canonical};isArrayBuffer=arg=>"function"==typeof ArrayBuffer&&arg instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(arg);getPayloadHash=async({headers,body},hashConstructor)=>{for(const headerName of Object.keys(headers))if("x-amz-content-sha256"===headerName.toLowerCase())return headers[headerName];if(null==body)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hashCtor=new hashConstructor;hashCtor.update(toUint8Array(body));return toHex2(await hashCtor.digest())}return"UNSIGNED-PAYLOAD"};HeaderFormatter=class{format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce(((carry,bytes)=>carry+bytes.byteLength),0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}};(function(HEADER_VALUE_TYPE3){HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byte=2]="byte";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.short=3]="short";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.integer=4]="integer";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.long=5]="long";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byteArray=6]="byteArray";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.string=7]="string";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.timestamp=8]="timestamp";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.uuid=9]="uuid"})(HEADER_VALUE_TYPE||(HEADER_VALUE_TYPE={}));UUID_PATTERN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;Int64=class _Int64{constructor(bytes){this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i2=7,remaining=Math.abs(Math.round(number));i2>-1&&remaining>0;i2--,remaining/=256)bytes[i2]=remaining;number<0&&negate(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate(bytes);return parseInt(toHex2(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};hasHeader=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};moveHeadersToQuery=(request2,options={})=>{var _a8,_b4;const{headers,query:query3={}}=HttpRequest.clone(request2);for(const name of Object.keys(headers)){const lname=name.toLowerCase();if("x-amz-"===lname.slice(0,6)&&!(null==(_a8=options.unhoistableHeaders)?void 0:_a8.has(lname))||(null==(_b4=options.hoistableHeaders)?void 0:_b4.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 key2 of Object.keys(query3)){if(key2.toLowerCase()===SIGNATURE_HEADER)continue;const encodedKey=escapeUri(key2);keys3.push(encodedKey);const value=query3[key2];"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((key2=>serialized2[key2])).filter((serialized3=>serialized3)).join("&")};iso8601=time=>toDate(time).toISOString().replace(/\.\d{3}Z$/,"Z");toDate=time=>"number"==typeof time?new Date(1e3*time):"string"==typeof time?Number(time)?new Date(1e3*Number(time)):new Date(time):time;SignatureV4Base=class{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){this.service=service;this.sha256=sha256;this.uriEscapePath=uriEscapePath;this.applyChecksum="boolean"!=typeof applyChecksum||applyChecksum;this.regionProvider=normalizeProvider(region);this.credentialProvider=normalizeProvider(credentials)}createCanonicalRequest(request2,canonicalHeaders,payloadHash){const sortedHeaders=Object.keys(canonicalHeaders).sort();return`${request2.method}\n${this.getCanonicalPath(request2)}\n${getCanonicalQuery(request2)}\n${sortedHeaders.map((name=>`${name}:${canonicalHeaders[name]}`)).join("\n")}\n\n${sortedHeaders.join(";")}\n${payloadHash}`}async createStringToSign(longDate,credentialScope,canonicalRequest,algorithmIdentifier){const hash2=new this.sha256;hash2.update(toUint8Array(canonicalRequest));return`${algorithmIdentifier}\n${longDate}\n${credentialScope}\n${toHex2(await hash2.digest())}`}getCanonicalPath({path:path2}){if(this.uriEscapePath){const normalizedPathSegments=[];for(const pathSegment of path2.split("/"))0!==(null==pathSegment?void 0:pathSegment.length)&&"."!==pathSegment&&(".."===pathSegment?normalizedPathSegments.pop():normalizedPathSegments.push(pathSegment));const normalizedPath=`${(null==path2?void 0:path2.startsWith("/"))?"/":""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length>0&&(null==path2?void 0:path2.endsWith("/"))?"/":""}`;return escapeUri(normalizedPath).replace(/%2F/g,"/")}return path2}validateResolvedCredentials(credentials){if("object"!=typeof credentials||"string"!=typeof credentials.accessKeyId||"string"!=typeof credentials.secretAccessKey)throw new Error("Resolved credential object is not valid")}formatDate(now3){const longDate=iso8601(now3).replace(/[\-:]/g,"");return{longDate,shortDate:longDate.slice(0,8)}}getCanonicalHeaderList(headers){return Object.keys(headers).sort().join(";")}};SignatureV4=class extends SignatureV4Base{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){super({applyChecksum,credentials,region,service,sha256,uriEscapePath});this.headerFormatter=new HeaderFormatter}async presign(originalRequest,options={}){const{signingDate=new Date,expiresIn=3600,unsignableHeaders,unhoistableHeaders,signableHeaders,hoistableHeaders,signingRegion,signingService}=options,credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),{longDate,shortDate}=this.formatDate(signingDate);if(expiresIn>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const scope=createScope(shortDate,region,null!=signingService?signingService:this.service),request2=moveHeadersToQuery(prepareRequest(originalRequest),{unhoistableHeaders,hoistableHeaders});credentials.sessionToken&&(request2.query["X-Amz-Security-Token"]=credentials.sessionToken);request2.query["X-Amz-Algorithm"]="AWS4-HMAC-SHA256";request2.query["X-Amz-Credential"]=`${credentials.accessKeyId}/${scope}`;request2.query[AMZ_DATE_QUERY_PARAM]=longDate;request2.query["X-Amz-Expires"]=expiresIn.toString(10);const canonicalHeaders=getCanonicalHeaders(request2,unsignableHeaders,signableHeaders);request2.query["X-Amz-SignedHeaders"]=this.getCanonicalHeaderList(canonicalHeaders);request2.query["X-Amz-Signature"]=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request2,canonicalHeaders,await getPayloadHash(originalRequest,this.sha256)));return request2}async sign(toSign,options){return"string"==typeof toSign?this.signString(toSign,options):toSign.headers&&toSign.payload?this.signEvent(toSign,options):toSign.message?this.signMessage(toSign,options):this.signRequest(toSign,options)}async signEvent({headers,payload},{signingDate=new Date,priorSignature,signingRegion,signingService}){const region=null!=signingRegion?signingRegion:await this.regionProvider(),{shortDate,longDate}=this.formatDate(signingDate),scope=createScope(shortDate,region,null!=signingService?signingService:this.service),hashedPayload=await getPayloadHash({headers:{},body:payload},this.sha256),hash2=new this.sha256;hash2.update(headers);const hashedHeaders=toHex2(await hash2.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),hash2=new this.sha256(await this.getSigningKey(credentials,region,shortDate,signingService));hash2.update(toUint8Array(stringToSign));return toHex2(await hash2.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"),hash2=new this.sha256(await keyPromise);hash2.update(toUint8Array(stringToSign));return toHex2(await hash2.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=function normalizeCredentialProvider(config,{credentials,credentialDefaultProvider}){let credentialsProvider;credentialsProvider=credentials?(null==credentials?void 0:credentials.memoized)?credentials:memoizeIdentityProvider(credentials,isIdentityExpired,doesIdentityRequireRefresh):credentialDefaultProvider?normalizeProvider2(credentialDefaultProvider(Object.assign({},config,{parentClientConfig:config}))):async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};credentialsProvider.memoized=!0;return credentialsProvider}(config,{credentials:inputCredentials,credentialDefaultProvider:config.credentialDefaultProvider}),boundProvider=function bindCallerConfig(config,credentialsProvider){if(credentialsProvider.configBound)return credentialsProvider;const fn=async options=>credentialsProvider({...options,callerClientConfig:config});fn.memoized=credentialsProvider.memoized;fn.configBound=!0;return fn}(config,memoizedProvider);if(isUserSupplied&&!boundProvider.attributed){resolvedCredentials=async options=>boundProvider(options).then((creds=>function setCredentialFeature(credentials,feature,value){credentials.$source||(credentials.$source={});credentials.$source[feature]=value;return credentials}(creds,"CREDENTIALS_CODE","e")));resolvedCredentials.memoized=boundProvider.memoized;resolvedCredentials.configBound=boundProvider.configBound;resolvedCredentials.attributed=!0}else resolvedCredentials=boundProvider},get:()=>resolvedCredentials,enumerable:!0,configurable:!0});config.credentials=inputCredentials;const{signingEscapePath=!0,systemClockOffset=config.systemClockOffset||0,sha256}=config;let signer;signer=config.signer?normalizeProvider2(config.signer):config.regionInfoProvider?()=>normalizeProvider2(config.region)().then((async region=>[await config.regionInfoProvider(region,{useFipsEndpoint:await config.useFipsEndpoint(),useDualstackEndpoint:await config.useDualstackEndpoint()})||{},region])).then((([regionInfo,region])=>{const{signingRegion,signingService}=regionInfo;config.signingRegion=config.signingRegion||signingRegion||region;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};return new(config.signerConstructor||SignatureV4)(params)})):async authScheme=>{const signingRegion=(authScheme=Object.assign({},{name:"sigv4",signingName:config.signingName||config.defaultSigningName,signingRegion:await normalizeProvider2(config.region)(),properties:{}},authScheme)).signingRegion,signingService=authScheme.signingName;config.signingRegion=config.signingRegion||signingRegion;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};return new(config.signerConstructor||SignatureV4)(params)};return Object.assign(config,{systemClockOffset,signingEscapePath,signer})};getAllAliases=(name,aliases)=>{const _aliases=[];name&&_aliases.push(name);if(aliases)for(const alias of aliases)_aliases.push(alias);return _aliases};getMiddlewareNameWithAliases=(name,aliases)=>`${name||"anonymous"}${aliases&&aliases.length>0?` (a.k.a. ${aliases.join(",")})`:""}`;constructStack=()=>{let absoluteEntries=[],relativeEntries=[],identifyOnResolve=!1;const entriesNameSet=new Set,cloneTo=toStack=>{var _a8;absoluteEntries.forEach((entry=>{toStack.add(entry.middleware,{...entry})}));relativeEntries.forEach((entry=>{toStack.addRelativeTo(entry.middleware,{...entry})}));null==(_a8=toStack.identifyOnResolve)||_a8.call(toStack,stack2.identifyOnResolve());return toStack},expandRelativeMiddlewareList=from=>{const expandedMiddlewareList=[];from.before.forEach((entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}));expandedMiddlewareList.push(from);from.after.reverse().forEach((entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}));return expandedMiddlewareList},getMiddlewareList=(debug2=!1)=>{const normalizedAbsoluteEntries=[],normalizedRelativeEntries=[],normalizedEntriesNameMap={};absoluteEntries.forEach((entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedAbsoluteEntries.push(normalizedEntry)}));relativeEntries.forEach((entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedRelativeEntries.push(normalizedEntry)}));normalizedRelativeEntries.forEach((entry=>{if(entry.toMiddleware){const toMiddleware=normalizedEntriesNameMap[entry.toMiddleware];if(void 0===toMiddleware){if(debug2)return;throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name,entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`)}"after"===entry.relation&&toMiddleware.after.push(entry);"before"===entry.relation&&toMiddleware.before.push(entry)}}));var entries2;return(entries2=normalizedAbsoluteEntries,entries2.sort(((a2,b3)=>stepWeights[b3.step]-stepWeights[a2.step]||priorityWeights[b3.priority||"normal"]-priorityWeights[a2.priority||"normal"]))).map(expandRelativeMiddlewareList).reduce(((wholeList,expandedMiddlewareList)=>{wholeList.push(...expandedMiddlewareList);return wholeList}),[])},stack2={add:(middleware,options={})=>{const{name,override,aliases:_aliases}=options,entry={step:"initialize",priority:"normal",middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some((alias=>entriesNameSet.has(alias)))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=absoluteEntries.findIndex((entry2=>{var _a8;return entry2.name===alias||(null==(_a8=entry2.aliases)?void 0:_a8.some((a2=>a2===alias)))}));if(-1===toOverrideIndex)continue;const toOverride=absoluteEntries[toOverrideIndex];if(toOverride.step!==entry.step||entry.priority!==toOverride.priority)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);absoluteEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}absoluteEntries.push(entry)},addRelativeTo:(middleware,options)=>{const{name,override,aliases:_aliases}=options,entry={middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some((alias=>entriesNameSet.has(alias)))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=relativeEntries.findIndex((entry2=>{var _a8;return entry2.name===alias||(null==(_a8=entry2.aliases)?void 0:_a8.some((a2=>a2===alias)))}));if(-1===toOverrideIndex)continue;const toOverride=relativeEntries[toOverrideIndex];if(toOverride.toMiddleware!==entry.toMiddleware||toOverride.relation!==entry.relation)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);relativeEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}relativeEntries.push(entry)},clone:()=>cloneTo(constructStack()),use:plugin3=>{plugin3.applyToStack(stack2)},remove:toRemove=>"string"==typeof toRemove?(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})(toRemove):(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})(toRemove),removeByTag:toRemove=>{let isRemoved=!1;const filterCb=entry=>{const{tags,name,aliases:_aliases}=entry;if(tags&&tags.includes(toRemove)){const aliases=getAllAliases(name,_aliases);for(const alias of aliases)entriesNameSet.delete(alias);isRemoved=!0;return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},concat:from=>{var _a8,_b4;const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||null!=(_b4=null==(_a8=from.identifyOnResolve)?void 0:_a8.call(from))&&_b4);return cloned},applyToStack:cloneTo,identify:()=>getMiddlewareList(!0).map((mw=>{var _a8;const step=null!=(_a8=mw.step)?_a8:mw.relation+" "+mw.toMiddleware;return getMiddlewareNameWithAliases(mw.name,mw.aliases)+" - "+step})),identifyOnResolve(toggle){"boolean"==typeof toggle&&(identifyOnResolve=toggle);return identifyOnResolve},resolve:(handler,context2)=>{for(const middleware of getMiddlewareList().map((entry=>entry.middleware)).reverse())handler=middleware(handler,context2);identifyOnResolve&&console.log(stack2.identify());return handler}};return stack2};stepWeights={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1};priorityWeights={high:3,normal:2,low:1};Client=class{constructor(config){this.config=config;this.middlewareStack=constructStack()}send(command,optionsOrCb,cb2){const options="function"!=typeof optionsOrCb?optionsOrCb:void 0,callback="function"==typeof optionsOrCb?optionsOrCb:cb2;let handler;if(void 0===options&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);const handlers2=this.handlers;if(handlers2.has(command.constructor))handler=handlers2.get(command.constructor);else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers2.set(command.constructor,handler)}}else{delete this.handlers;handler=command.resolveMiddleware(this.middlewareStack,this.config,options)}if(!callback)return handler(command).then((result=>result.output));handler(command).then((result=>callback(null,result.output)),(err2=>callback(err2))).catch((()=>{}))}destroy(){var _a8,_b4,_c3;null==(_c3=null==(_b4=null==(_a8=this.config)?void 0:_a8.requestHandler)?void 0:_b4.destroy)||_c3.call(_b4);delete this.handlers}};Command=class{constructor(){this.middlewareStack=constructStack()}static classBuilder(){return new ClassBuilder}resolveMiddlewareWithContext(clientStack,configuration,options,{middlewareFn,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,smithyContext,additionalContext,CommandCtor}){for(const mw of middlewareFn.bind(this)(CommandCtor,clientStack,configuration,options))this.middlewareStack.use(mw);const stack2=clientStack.concat(this.middlewareStack),{logger:logger2}=configuration,handlerExecutionContext={logger:logger2,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,[SMITHY_CONTEXT_KEY]:{commandInstance:this,...smithyContext},...additionalContext},{requestHandler}=configuration;return stack2.resolve((request2=>requestHandler.handle(request2.request,options||{})),handlerExecutionContext)}};ClassBuilder=class{constructor(){this._init=()=>{};this._ep={};this._middlewareFn=()=>[];this._commandName="";this._clientName="";this._additionalContext={};this._smithyContext={};this._inputFilterSensitiveLog=_=>_;this._outputFilterSensitiveLog=_=>_;this._serializer=null;this._deserializer=null}init(cb2){this._init=cb2}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation,smithyContext={}){this._smithyContext={service,operation,...smithyContext};return this}c(additionalContext={}){this._additionalContext=additionalContext;return this}n(clientName,commandName){this._clientName=clientName;this._commandName=commandName;return this}f(inputFilter=_=>_,outputFilter=_=>_){this._inputFilterSensitiveLog=inputFilter;this._outputFilterSensitiveLog=outputFilter;return this}ser(serializer){this._serializer=serializer;return this}de(deserializer){this._deserializer=deserializer;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{static getEndpointParameterInstructions(){return closure._ep}constructor(...[input]){super();this.serialize=closure._serializer;this.deserialize=closure._deserializer;this.input=null!=input?input:{};closure._init(this)}resolveMiddleware(stack2,configuration,options){return this.resolveMiddlewareWithContext(stack2,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:closure._inputFilterSensitiveLog,outputFilterSensitiveLog:closure._outputFilterSensitiveLog,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}};SENSITIVE_STRING="***SensitiveInformation***";createAggregatedClient=(commands2,Client2)=>{for(const command of Object.keys(commands2)){const CommandCtor=commands2[command],methodImpl=async function(args,optionsOrCb,cb2){const command2=new CommandCtor(args);if("function"==typeof optionsOrCb)this.send(command2,optionsOrCb);else{if("function"!=typeof cb2)return this.send(command2,optionsOrCb);if("object"!=typeof optionsOrCb)throw new Error("Expected http options but got "+typeof optionsOrCb);this.send(command2,optionsOrCb||{},cb2)}},methodName=(command[0].toLowerCase()+command.slice(1)).replace(/Command$/,"");Client2.prototype[methodName]=methodImpl}};parseBoolean=value=>{switch(value){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${value}"`)}};expectNumber=value=>{if(null!=value){if("string"==typeof value){const parsed=parseFloat(value);if(!Number.isNaN(parsed)){String(parsed)!==String(value)&&logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));return parsed}}if("number"==typeof value)return value;throw new TypeError(`Expected number, got ${typeof value}: ${value}`)}};MAX_FLOAT=Math.ceil(2**127*(2-2**-23));expectFloat32=value=>{const expected=expectNumber(value);if(void 0!==expected&&!Number.isNaN(expected)&&expected!==1/0&&expected!==-1/0&&Math.abs(expected)>MAX_FLOAT)throw new TypeError(`Expected 32-bit float, got ${value}`);return expected};expectLong=value=>{if(null!=value){if(Number.isInteger(value)&&!Number.isNaN(value))return value;throw new TypeError(`Expected integer, got ${typeof value}: ${value}`)}};expectInt32=value=>expectSizedInt(value,32);expectShort=value=>expectSizedInt(value,16);expectByte=value=>expectSizedInt(value,8);expectSizedInt=(value,size)=>{const expected=expectLong(value);if(void 0!==expected&&castInt(expected,size)!==expected)throw new TypeError(`Expected ${size}-bit integer, got ${value}`);return expected};castInt=(value,size)=>{switch(size){case 32:return Int32Array.of(value)[0];case 16:return Int16Array.of(value)[0];case 8:return Int8Array.of(value)[0]}};expectNonNull=(value,location)=>{if(null==value){if(location)throw new TypeError(`Expected a non-null value for ${location}`);throw new TypeError("Expected a non-null value")}return value};expectObject=value=>{if(null==value)return;if("object"==typeof value&&!Array.isArray(value))return value;const receivedType=Array.isArray(value)?"array":typeof value;throw new TypeError(`Expected object, got ${receivedType}: ${value}`)};expectString=value=>{if(null!=value){if("string"==typeof value)return value;if(["boolean","number","bigint"].includes(typeof value)){logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));return String(value)}throw new TypeError(`Expected string, got ${typeof value}: ${value}`)}};expectUnion=value=>{if(null==value)return;const asObject=expectObject(value),setKeys=Object.entries(asObject).filter((([,v2])=>null!=v2)).map((([k2])=>k2));if(0===setKeys.length)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(setKeys.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);return asObject};strictParseFloat32=value=>expectFloat32("string"==typeof value?parseNumber(value):value);NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;parseNumber=value=>{const matches=value.match(NUMBER_REGEX);if(null===matches||matches[0].length!==value.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(value)};strictParseLong=value=>expectLong("string"==typeof value?parseNumber(value):value);strictParseInt32=value=>expectInt32("string"==typeof value?parseNumber(value):value);strictParseShort=value=>expectShort("string"==typeof value?parseNumber(value):value);strictParseByte=value=>expectByte("string"==typeof value?parseNumber(value):value);stackTraceWarning=message=>String(new TypeError(message).stack||message).split("\n").slice(0,5).filter((s2=>!s2.includes("stackTraceWarning"))).join("\n");logger={warn:console.warn};DAYS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);RFC3339_WITH_OFFSET=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);parseRfc3339DateTimeWithOffset=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC-3339 date-times must be expressed as strings");const match3=RFC3339_WITH_OFFSET.exec(value);if(!match3)throw new TypeError("Invalid RFC-3339 date-time value");const[_,yearStr,monthStr,dayStr,hours,minutes,seconds,fractionalMilliseconds,offsetStr]=match3,year=strictParseShort(stripLeadingZeroes(yearStr)),month=parseDateValue(monthStr,"month",1,12),day=parseDateValue(dayStr,"day",1,31),date=buildDate(year,month,day,{hours,minutes,seconds,fractionalMilliseconds});"Z"!=offsetStr.toUpperCase()&&date.setTime(date.getTime()-parseOffsetToMilliseconds(offsetStr));return date};IMF_FIXDATE=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);RFC_850_DATE=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);ASC_TIME=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);parseRfc7231DateTime=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC-7231 date-times must be expressed as strings");let match3=IMF_FIXDATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}match3=RFC_850_DATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds}))}match3=ASC_TIME.exec(value);if(match3){const[_,monthStr,dayStr,hours,minutes,seconds,fractionalMilliseconds,yearStr]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr.trimLeft(),"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}throw new TypeError("Invalid RFC-7231 date-time value")};buildDate=(year,month,day,time)=>{const adjustedMonth=month-1;validateDayOfMonth(year,adjustedMonth,day);return new Date(Date.UTC(year,adjustedMonth,day,parseDateValue(time.hours,"hour",0,23),parseDateValue(time.minutes,"minute",0,59),parseDateValue(time.seconds,"seconds",0,60),parseMilliseconds(time.fractionalMilliseconds)))};parseTwoDigitYear=value=>{const thisYear=(new Date).getUTCFullYear(),valueInThisCentury=100*Math.floor(thisYear/100)+strictParseShort(stripLeadingZeroes(value));return 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=(year,month,day)=>{let maxDays=DAYS_IN_MONTH[month];1===month&&isLeapYear(year)&&(maxDays=29);if(day>maxDays)throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`)};isLeapYear=year=>year%4==0&&(year%100!=0||year%400==0);parseDateValue=(value,type,lower,upper)=>{const dateVal=strictParseByte(stripLeadingZeroes(value));if(dateValupper)throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);return dateVal};parseMilliseconds=value=>null==value?0:1e3*strictParseFloat32("0."+value);parseOffsetToMilliseconds=value=>{const directionStr=value[0];let direction=1;if("+"==directionStr)direction=1;else{if("-"!=directionStr)throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);direction=-1}return direction*(60*Number(value.substring(1,3))+Number(value.substring(4,6)))*60*1e3};stripLeadingZeroes=value=>{let idx2=0;for(;idx2{Object.entries(additions).filter((([,v2])=>void 0!==v2)).forEach((([k2,v2])=>{null!=exception[k2]&&""!==exception[k2]||(exception[k2]=v2)}));const message=exception.message||exception.Message||"UnknownError";exception.message=message;delete exception.Message;return exception};throwDefaultError=({output,parsedBody,exceptionCtor,errorCode})=>{const $metadata=deserializeMetadata(output),statusCode=$metadata.httpStatusCode?$metadata.httpStatusCode+"":void 0,response=new exceptionCtor({name:(null==parsedBody?void 0:parsedBody.code)||(null==parsedBody?void 0:parsedBody.Code)||errorCode||statusCode||"UnknownError",$fault:"client",$metadata});throw decorateServiceException(response,parsedBody)};withBaseException=ExceptionCtor=>({output,parsedBody,errorCode})=>{throwDefaultError({output,parsedBody,exceptionCtor:ExceptionCtor,errorCode})};deserializeMetadata=output=>{var _a8,_b4;return{httpStatusCode:output.statusCode,requestId:null!=(_b4=null!=(_a8=output.headers["x-amzn-requestid"])?_a8:output.headers["x-amzn-request-id"])?_b4:output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]}};loadConfigsForDefaultMode=mode=>{switch(mode){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}};getChecksumConfiguration2=runtimeConfig=>{const checksumAlgorithms=[];for(const id in AlgorithmId){const algorithmId=AlgorithmId[id];void 0!==runtimeConfig[algorithmId]&&checksumAlgorithms.push({algorithmId:()=>algorithmId,checksumConstructor:()=>runtimeConfig[algorithmId]})}return{addChecksumAlgorithm(algo2){checksumAlgorithms.push(algo2)},checksumAlgorithms:()=>checksumAlgorithms}};resolveChecksumRuntimeConfig2=clientConfig=>{const runtimeConfig={};clientConfig.checksumAlgorithms().forEach((checksumAlgorithm=>{runtimeConfig[checksumAlgorithm.algorithmId()]=checksumAlgorithm.checksumConstructor()}));return runtimeConfig};getRetryConfiguration=runtimeConfig=>({setRetryStrategy(retryStrategy){runtimeConfig.retryStrategy=retryStrategy},retryStrategy:()=>runtimeConfig.retryStrategy});resolveRetryRuntimeConfig=retryStrategyConfiguration=>{const runtimeConfig={};runtimeConfig.retryStrategy=retryStrategyConfiguration.retryStrategy();return runtimeConfig};getDefaultExtensionConfiguration=runtimeConfig=>Object.assign(getChecksumConfiguration2(runtimeConfig),getRetryConfiguration(runtimeConfig));resolveDefaultRuntimeConfig2=config=>Object.assign(resolveChecksumRuntimeConfig2(config),resolveRetryRuntimeConfig(config));getArrayIfSingleItem=mayBeArray=>Array.isArray(mayBeArray)?mayBeArray:[mayBeArray];getValueFromTextNode=obj=>{for(const key2 in obj)obj.hasOwnProperty(key2)&&void 0!==obj[key2]["#text"]?obj[key2]=obj[key2]["#text"]:"object"==typeof obj[key2]&&null!==obj[key2]&&(obj[key2]=getValueFromTextNode(obj[key2]));return obj};isSerializableHeaderValue=value=>null!=value;(LazyJsonString=function LazyJsonString2(val2){return Object.assign(new String(val2),{deserializeJSON:()=>JSON.parse(String(val2)),toString:()=>String(val2),toJSON:()=>String(val2)})}).from=object=>object&&"object"==typeof object&&(object instanceof LazyJsonString||"deserializeJSON"in object)?object:"string"==typeof object||Object.getPrototypeOf(object)===String.prototype?LazyJsonString(String(object)):LazyJsonString(JSON.stringify(object));LazyJsonString.fromObject=LazyJsonString.from;NoOpLogger=class{trace(){}debug(){}info(){}warn(){}error(){}};mapWithFilter=(target,filter4,instructions)=>map2(target,Object.entries(instructions).reduce(((_instructions,[key2,value])=>{Array.isArray(value)?_instructions[key2]=value:_instructions[key2]="function"==typeof value?[filter4,value()]:[filter4,value];return _instructions}),{}));applyInstruction=(target,source2,instructions,targetKey)=>{if(null!==source2){let instruction=instructions[targetKey];"function"==typeof instruction&&(instruction=[,instruction]);const[filter5=nonNullish,valueFn=pass,sourceKey=targetKey]=instruction;("function"==typeof filter5&&filter5(source2[sourceKey])||"function"!=typeof filter5&&filter5)&&(target[targetKey]=valueFn(source2[sourceKey]));return}let[filter4,value]=instructions[targetKey];if("function"==typeof value){let _value;const defaultFilterPassed=void 0===filter4&&null!=(_value=value()),customFilterPassed="function"==typeof filter4&&!!filter4(void 0)||"function"!=typeof filter4&&!!filter4;defaultFilterPassed?target[targetKey]=_value:customFilterPassed&&(target[targetKey]=value())}else{const defaultFilterPassed=void 0===filter4&&null!=value,customFilterPassed="function"==typeof filter4&&!!filter4(value)||"function"!=typeof filter4&&!!filter4;(defaultFilterPassed||customFilterPassed)&&(target[targetKey]=value)}};nonNullish=_=>null!=_;pass=_=>_;serializeDateTime=date=>date.toISOString().replace(".000Z","Z");collectBodyString=(streamBody,context2)=>collectBody(streamBody,context2).then((body=>context2.utf8Encoder(body)));import_fast_xml_parser=__toESM(require_fxp());parseXmlBody=(streamBody,context2)=>collectBodyString(streamBody,context2).then((encoded=>{if(encoded.length){const parser2=new import_fast_xml_parser.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(_,val2)=>""===val2.trim()&&val2.includes("\n")?"":void 0});parser2.addEntity("#xD","\r");parser2.addEntity("#10","\n");let parsedObj;try{parsedObj=parser2.parse(encoded,!0)}catch(e3){e3&&"object"==typeof e3&&Object.defineProperty(e3,"$responseBodyText",{value:encoded});throw e3}const textNodeName="#text",key2=Object.keys(parsedObj)[0],parsedObjToReturn=parsedObj[key2];if(parsedObjToReturn[textNodeName]){parsedObjToReturn[key2]=parsedObjToReturn[textNodeName];delete parsedObjToReturn[textNodeName]}return getValueFromTextNode(parsedObjToReturn)}return{}}));parseXmlErrorBody=async(errorBody,context2)=>{var _a8;const value=await parseXmlBody(errorBody,context2);value.Error&&(value.Error.message=null!=(_a8=value.Error.message)?_a8:value.Error.Message);return value};loadRestXmlErrorCode=(output,data)=>{var _a8;return void 0!==(null==(_a8=null==data?void 0:data.Error)?void 0:_a8.Code)?data.Error.Code:void 0!==(null==data?void 0:data.Code)?data.Code:404==output.statusCode?"NotFound":void 0};CLIENT_SUPPORTED_ALGORITHMS=[ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.SHA256];PRIORITY_ORDER_ALGORITHMS=[ChecksumAlgorithm.SHA256,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME];getChecksumAlgorithmForRequest=(input,{requestChecksumRequired,requestAlgorithmMember,requestChecksumCalculation})=>{if(!requestAlgorithmMember)return requestChecksumCalculation===RequestChecksumCalculation.WHEN_SUPPORTED||requestChecksumRequired?DEFAULT_CHECKSUM_ALGORITHM:void 0;if(!input[requestAlgorithmMember])return;const checksumAlgorithm=input[requestAlgorithmMember];if(!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm))throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`);return checksumAlgorithm};getChecksumLocationName=algorithm=>algorithm===ChecksumAlgorithm.MD5?"content-md5":`x-amz-checksum-${algorithm.toLowerCase()}`;hasHeader2=(header,headers)=>{const soughtHeader=header.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};hasHeaderWithPrefix=(headerPrefix,headers)=>{const soughtHeaderPrefix=headerPrefix.toLowerCase();for(const headerName of Object.keys(headers))if(headerName.toLowerCase().startsWith(soughtHeaderPrefix))return!0;return!1};isStreaming=body=>void 0!==body&&"string"!=typeof body&&!ArrayBuffer.isView(body)&&!isArrayBuffer(body);__assign=function(){__assign=Object.assign||function __assign2(t3){var s2,i2,n3,p4;for(i2=1,n3=arguments.length;i2(new TextEncoder).encode(input);fromUtf83="undefined"!=typeof Buffer&&Buffer.from?function(input){return Buffer.from(input,"utf8")}:fromUtf82;AwsCrc32c=function(){function AwsCrc32c2(){this.crc32c=new Crc32c}AwsCrc32c2.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32c.update(convertToBuffer(toHash))};AwsCrc32c2.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,numToUint8(this.crc32c.digest())]}))}))};AwsCrc32c2.prototype.reset=function(){this.crc32c=new Crc32c};return AwsCrc32c2}();Crc32c=function(){function Crc32c2(){this.checksum=4294967295}Crc32c2.prototype.update=function(data){var e_1,_a8,data_1,data_1_1,byte;try{for(data_1_1=(data_1=__values(data)).next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a8=data_1.return)&&_a8.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc32c2.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc32c2}();lookupTable=uint32ArrayFrom([0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697]);AwsCrc32=function(){function AwsCrc322(){this.crc32=new Crc32}AwsCrc322.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32.update(convertToBuffer(toHash))};AwsCrc322.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,numToUint8(this.crc32.digest())]}))}))};AwsCrc322.prototype.reset=function(){this.crc32=new Crc32};return AwsCrc322}();Crc32=function(){function Crc322(){this.checksum=4294967295}Crc322.prototype.update=function(data){var e_1,_a8,data_1,data_1_1,byte;try{for(data_1_1=(data_1=__values(data)).next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable2[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a8=data_1.return)&&_a8.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc322.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc322}();lookupTable2=uint32ArrayFrom([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);getCrc32ChecksumAlgorithmFunction=()=>AwsCrc32;selectChecksumAlgorithmFunction=(checksumAlgorithm,config)=>{switch(checksumAlgorithm){case ChecksumAlgorithm.MD5:return config.md5;case ChecksumAlgorithm.CRC32:return getCrc32ChecksumAlgorithmFunction();case ChecksumAlgorithm.CRC32C:return AwsCrc32c;case ChecksumAlgorithm.CRC64NVME:throw new Error('Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly. \nYou must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";]. \nFor more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt');case ChecksumAlgorithm.SHA1:return config.sha1;case ChecksumAlgorithm.SHA256:return config.sha256;default:throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`)}};stringHasher=(checksumAlgorithmFn,body)=>{const hash2=new checksumAlgorithmFn;hash2.update(toUint8Array(body||""));return hash2.digest()};flexibleChecksumsMiddlewareOptions={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);if(hasHeaderWithPrefix("x-amz-checksum-",args.request.headers))return next2(args);const{request:request2,input}=args,{body:requestBody,headers}=request2,{base64Encoder,streamHasher}=config,{requestChecksumRequired,requestAlgorithmMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),requestAlgorithmMemberName=null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestAlgorithmMemberHttpHeader=null==requestAlgorithmMember?void 0:requestAlgorithmMember.httpHeader;if(requestAlgorithmMemberName&&!input[requestAlgorithmMemberName]&&(requestChecksumCalculation===RequestChecksumCalculation.WHEN_SUPPORTED||requestChecksumRequired)){input[requestAlgorithmMemberName]=DEFAULT_CHECKSUM_ALGORITHM;requestAlgorithmMemberHttpHeader&&(headers[requestAlgorithmMemberHttpHeader]=DEFAULT_CHECKSUM_ALGORITHM)}const checksumAlgorithm=getChecksumAlgorithmForRequest(input,{requestChecksumRequired,requestAlgorithmMember:null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestChecksumCalculation});let updatedBody=requestBody,updatedHeaders=headers;if(checksumAlgorithm){switch(checksumAlgorithm){case ChecksumAlgorithm.CRC32:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case ChecksumAlgorithm.CRC32C:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case ChecksumAlgorithm.CRC64NVME:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC64","W");break;case ChecksumAlgorithm.SHA1:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case ChecksumAlgorithm.SHA256:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y");break}const checksumLocationName=getChecksumLocationName(checksumAlgorithm),checksumAlgorithmFn=selectChecksumAlgorithmFunction(checksumAlgorithm,config);if(isStreaming(requestBody)){const{getAwsChunkedEncodingStream:getAwsChunkedEncodingStream2,bodyLengthChecker}=config;updatedBody=getAwsChunkedEncodingStream2("number"==typeof config.requestStreamBufferSize&&config.requestStreamBufferSize>=8192?createBufferedReadable(requestBody,config.requestStreamBufferSize,context2.logger):requestBody,{base64Encoder,bodyLengthChecker,checksumLocationName,checksumAlgorithmFn,streamHasher});updatedHeaders={...headers,"content-encoding":headers["content-encoding"]?`${headers["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":headers["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":checksumLocationName};delete updatedHeaders["content-length"]}else if(!hasHeader2(checksumLocationName,headers)){const rawChecksum=await stringHasher(checksumAlgorithmFn,requestBody);updatedHeaders={...headers,[checksumLocationName]:base64Encoder(rawChecksum)}}}return await next2({...args,request:{...request2,headers:updatedHeaders,body:updatedBody}})};flexibleChecksumsInputMiddlewareOptions={name:"flexibleChecksumsInputMiddleware",toMiddleware:"serializerMiddleware",relation:"before",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsInputMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{const input=args.input,{requestValidationModeMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),responseChecksumValidation=await config.responseChecksumValidation();switch(requestChecksumCalculation){case RequestChecksumCalculation.WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED","a");break;case RequestChecksumCalculation.WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED","Z");break}switch(responseChecksumValidation){case ResponseChecksumValidation.WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED","c");break;case ResponseChecksumValidation.WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED","b");break}requestValidationModeMember&&!input[requestValidationModeMember]&&responseChecksumValidation===ResponseChecksumValidation.WHEN_SUPPORTED&&(input[requestValidationModeMember]="ENABLED");return next2(args)};getChecksumAlgorithmListForResponse=(responseAlgorithms=[])=>{const validChecksumAlgorithms=[];for(const algorithm of PRIORITY_ORDER_ALGORITHMS)responseAlgorithms.includes(algorithm)&&CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)&&validChecksumAlgorithms.push(algorithm);return validChecksumAlgorithms};isChecksumWithPartNumber=checksum=>{const lastHyphenIndex=checksum.lastIndexOf("-");if(-1!==lastHyphenIndex){const numberPart=checksum.slice(lastHyphenIndex+1);if(!numberPart.startsWith("0")){const number=parseInt(numberPart,10);if(!isNaN(number)&&number>=1&&number<=1e4)return!0}}return!1};getChecksum=async(body,{checksumAlgorithmFn,base64Encoder})=>base64Encoder(await stringHasher(checksumAlgorithmFn,body));validateChecksumFromResponse=async(response,{config,responseAlgorithms,logger:logger2})=>{const checksumAlgorithms=getChecksumAlgorithmListForResponse(responseAlgorithms),{body:responseBody,headers:responseHeaders}=response;for(const algorithm of checksumAlgorithms){const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=responseHeaders[responseHeader];if(checksumFromResponse){let checksumAlgorithmFn;try{checksumAlgorithmFn=selectChecksumAlgorithmFunction(algorithm,config)}catch(error){if(algorithm===ChecksumAlgorithm.CRC64NVME){null==logger2||logger2.warn(`Skipping ${ChecksumAlgorithm.CRC64NVME} checksum validation: ${error.message}`);continue}throw error}const{base64Encoder}=config;if(isStreaming(responseBody)){response.body=createChecksumStream({expectedChecksum:checksumFromResponse,checksumSourceLocation:responseHeader,checksum:new checksumAlgorithmFn,source:responseBody,base64Encoder});return}const checksum=await getChecksum(responseBody,{checksumAlgorithmFn,base64Encoder});if(checksum===checksumFromResponse)break;throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`)}}};flexibleChecksumsResponseMiddlewareOptions={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsResponseMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const input=args.input,result=await next2(args),response=result.response,{requestValidationModeMember,responseAlgorithms}=middlewareConfig;if(requestValidationModeMember&&"ENABLED"===input[requestValidationModeMember]){const{clientName,commandName}=context2;if("S3Client"===clientName&&"GetObjectCommand"===commandName&&getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm=>{const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=response.headers[responseHeader];return!checksumFromResponse||isChecksumWithPartNumber(checksumFromResponse)})))return result;await validateChecksumFromResponse(response,{config,responseAlgorithms,logger:context2.logger})}return result};getFlexibleChecksumsPlugin=(config,middlewareConfig)=>({applyToStack:clientStack=>{clientStack.add(flexibleChecksumsMiddleware(config,middlewareConfig),flexibleChecksumsMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config,middlewareConfig),flexibleChecksumsInputMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config,middlewareConfig),flexibleChecksumsResponseMiddlewareOptions)}});resolveFlexibleChecksumsConfig=input=>{const{requestChecksumCalculation,responseChecksumValidation,requestStreamBufferSize}=input;return Object.assign(input,{requestChecksumCalculation:normalizeProvider(null!=requestChecksumCalculation?requestChecksumCalculation:DEFAULT_REQUEST_CHECKSUM_CALCULATION),responseChecksumValidation:normalizeProvider(null!=responseChecksumValidation?responseChecksumValidation:DEFAULT_RESPONSE_CHECKSUM_VALIDATION),requestStreamBufferSize:Number(null!=requestStreamBufferSize?requestStreamBufferSize:0)})};hostHeaderMiddleware=options=>next2=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const{request:request2}=args,{handlerProtocol=""}=options.requestHandler.metadata||{};if(handlerProtocol.indexOf("h2")>=0&&!request2.headers[":authority"]){delete request2.headers.host;request2.headers[":authority"]=request2.hostname+(request2.port?":"+request2.port:"")}else if(!request2.headers.host){let host=request2.hostname;null!=request2.port&&(host+=`:${request2.port}`);request2.headers.host=host}return next2(args)};hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0};getHostHeaderPlugin=options=>({applyToStack:clientStack=>{clientStack.add(hostHeaderMiddleware(options),hostHeaderMiddlewareOptions)}});loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0};getLoggerPlugin=options=>({applyToStack:clientStack=>{clientStack.add(((next2,context2)=>async args=>{var _a8,_b4;try{const response=await next2(args),{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog,overrideOutputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog,outputFilterSensitiveLog=null!=overrideOutputFilterSensitiveLog?overrideOutputFilterSensitiveLog:context2.outputFilterSensitiveLog,{$metadata,...outputWithoutMetadata}=response.output;null==(_a8=null==logger2?void 0:logger2.info)||_a8.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),output:outputFilterSensitiveLog(outputWithoutMetadata),metadata:$metadata});return response}catch(error){const{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog;null==(_b4=null==logger2?void 0:logger2.error)||_b4.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),error,metadata:error.$metadata});throw error}}),loggerMiddlewareOptions)}});recursionDetectionMiddleware=options=>next2=>async args=>{var _a8,_b4;const{request:request2}=args;if(!HttpRequest.isInstance(request2)||"node"!==options.runtime)return next2(args);const traceIdHeader=null!=(_b4=Object.keys(null!=(_a8=request2.headers)?_a8:{}).find((h3=>h3.toLowerCase()==="X-Amzn-Trace-Id".toLowerCase())))?_b4:"X-Amzn-Trace-Id";if(request2.headers.hasOwnProperty(traceIdHeader))return next2(args);const functionName=process.env.AWS_LAMBDA_FUNCTION_NAME,traceId=process.env._X_AMZN_TRACE_ID,nonEmptyString=str=>"string"==typeof str&&str.length>0;nonEmptyString(functionName)&&nonEmptyString(traceId)&&(request2.headers["X-Amzn-Trace-Id"]=traceId);return next2({...args,request:request2})};addRecursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"};getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(options),addRecursionDetectionMiddlewareOptions)}});checkContentLengthHeaderMiddlewareOptions={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0};getCheckContentLengthHeaderPlugin=unused=>({applyToStack:clientStack=>{clientStack.add(function checkContentLengthHeader(){return(next2,context2)=>async args=>{var _a8;const{request:request2}=args;if(HttpRequest.isInstance(request2)&&!("content-length"in request2.headers)&&!("x-amz-decoded-content-length"in request2.headers)){const message="Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";"function"!=typeof(null==(_a8=null==context2?void 0:context2.logger)?void 0:_a8.warn)||context2.logger instanceof NoOpLogger?console.warn(message):context2.logger.warn(message)}return next2({...args})}}(),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(function regionRedirectMiddleware(clientConfig){return(next2,context2)=>async args=>{var _a8,_b4,_c3;try{return await next2(args)}catch(err2){if(clientConfig.followRegionRedirects&&(301===(null==(_a8=null==err2?void 0:err2.$metadata)?void 0:_a8.httpStatusCode)||400===(null==(_b4=null==err2?void 0:err2.$metadata)?void 0:_b4.httpStatusCode)&&"IllegalLocationConstraintException"===(null==err2?void 0:err2.name))){try{const actualRegion=err2.$response.headers["x-amz-bucket-region"];null==(_c3=context2.logger)||_c3.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);context2.__s3RegionRedirect=actualRegion}catch(e3){throw new Error("Region redirect failed: "+e3)}return next2(args)}throw err2}}}(clientConfig),regionRedirectMiddlewareOptions);clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig),regionRedirectEndpointMiddlewareOptions)}});s3ExpiresMiddleware=config=>(next2,context2)=>async args=>{var _a8;const result=await next2(args),{response}=result;if(HttpResponse.isInstance(response)&&response.headers.expires){response.headers.expiresstring=response.headers.expires;try{parseRfc7231DateTime(response.headers.expires)}catch(e3){null==(_a8=context2.logger)||_a8.warn(`AWS SDK Warning for ${context2.clientName}::${context2.commandName} response parsing (${response.headers.expires}): ${e3}`);delete response.headers.expires}}return result};s3ExpiresMiddlewareOptions={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"};getS3ExpiresMiddlewarePlugin=clientConfig=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpiresMiddleware(),s3ExpiresMiddlewareOptions)}});_S3ExpressIdentityCache=class _S3ExpressIdentityCache{constructor(data={}){__publicField(this,"data");__publicField(this,"lastPurgeTime",Date.now());this.data=data}get(key2){const entry=this.data[key2];if(entry)return entry}set(key2,entry){this.data[key2]=entry;return entry}delete(key2){delete this.data[key2]}async purgeExpired(){const now3=Date.now();if(!(this.lastPurgeTime+_S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>now3))for(const key2 in this.data){const entry=this.data[key2];if(!entry.isRefreshing){const credential=await entry.identity;credential.expiration&&credential.expiration.getTime(){var _a8,_b4,_c3,_d2;if((null!=(_b4=null==(_a8=identity.expiration)?void 0:_a8.getTime())?_b4:0){cache2.set(key2,new S3ExpressIdentityCacheEntry(Promise.resolve(id)))}))}return identity})):cache2.set(key2,new S3ExpressIdentityCacheEntry(this.getIdentity(key2))).identity}async getIdentity(key2){var _a8,_b4;await this.cache.purgeExpired().catch((error=>{console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n"+error)}));const session=await this.createSessionFn(key2);if(!(null==(_a8=session.Credentials)?void 0:_a8.AccessKeyId)||!(null==(_b4=session.Credentials)?void 0:_b4.SecretAccessKey))throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");return{accessKeyId:session.Credentials.AccessKeyId,secretAccessKey:session.Credentials.SecretAccessKey,sessionToken:session.Credentials.SessionToken,expiration:session.Credentials.Expiration?new Date(session.Credentials.Expiration):void 0}}};__publicField(_S3ExpressIdentityProviderImpl,"REFRESH_WINDOW_MS",6e4);S3ExpressIdentityProviderImpl=_S3ExpressIdentityProviderImpl;(function(SelectorType3){SelectorType3.ENV="env";SelectorType3.CONFIG="shared config entry"})(SelectorType2||(SelectorType2={}));SESSION_TOKEN_HEADER=(SESSION_TOKEN_QUERY_PARAM="X-Amz-S3session-Token").toLowerCase();SignatureV4S3Express=class extends SignatureV4{async signWithCredentials(requestToSign,credentials,options){const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);requestToSign.headers[SESSION_TOKEN_HEADER]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.signRequest(requestToSign,null!=options?options:{})}async presignWithCredentials(requestToSign,credentials,options){var _a8;const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);delete requestToSign.headers[SESSION_TOKEN_HEADER];requestToSign.headers[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;requestToSign.query=null!=(_a8=requestToSign.query)?_a8:{};requestToSign.query[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.presign(requestToSign,options)}};s3ExpressMiddleware=options=>(next2,context2)=>async args=>{var _a8,_b4,_c3,_d2,_e2;if(context2.endpointV2){const endpoint=context2.endpointV2,isS3ExpressAuth="sigv4-s3express"===(null==(_c3=null==(_b4=null==(_a8=endpoint.properties)?void 0:_a8.authSchemes)?void 0:_b4[0])?void 0:_c3.name);if("S3Express"===(null==(_d2=endpoint.properties)?void 0:_d2.backend)||"Directory"===(null==(_e2=endpoint.properties)?void 0:_e2.bucketType)){setFeature(context2,"S3_EXPRESS_BUCKET","J");context2.isS3ExpressBucket=!0}if(isS3ExpressAuth){const requestBucket=args.input.Bucket;if(requestBucket){const s3ExpressIdentity=await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(),{Bucket:requestBucket});context2.s3ExpressIdentity=s3ExpressIdentity;HttpRequest.isInstance(args.request)&&s3ExpressIdentity.sessionToken&&(args.request.headers[SESSION_TOKEN_HEADER]=s3ExpressIdentity.sessionToken)}}}return next2(args)};s3ExpressMiddlewareOptions={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0};getS3ExpressPlugin=options=>({applyToStack:clientStack=>{clientStack.add(s3ExpressMiddleware(options),s3ExpressMiddlewareOptions)}});signS3Express=async(s3ExpressIdentity,signingOptions,request2,sigV4MultiRegionSigner)=>{const signedRequest=await sigV4MultiRegionSigner.signWithCredentials(request2,s3ExpressIdentity,{});if(signedRequest.headers["X-Amz-Security-Token"]||signedRequest.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");return signedRequest};defaultErrorHandler2=signingProperties=>error=>{throw error};defaultSuccessHandler2=(httpResponse,signingProperties)=>{};s3ExpressHttpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const scheme=getSmithyContext2(context2).selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme;let request2;request2=context2.s3ExpressIdentity?await signS3Express(context2.s3ExpressIdentity,0,args.request,await config.signer()):await signer.sign(args.request,identity,signingProperties);const output=await next2({...args,request:request2}).catch((signer.errorHandler||defaultErrorHandler2)(signingProperties));(signer.successHandler||defaultSuccessHandler2)(output.response,signingProperties);return output};getS3ExpressHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config),httpSigningMiddlewareOptions)}});resolveS3Config=(input,{session})=>{const[s3ClientProvider,CreateSessionCommandCtor]=session,{forcePathStyle,useAccelerateEndpoint,disableMultiregionAccessPoints,followRegionRedirects,s3ExpressIdentityProvider,bucketEndpoint}=input;return Object.assign(input,{forcePathStyle:null!=forcePathStyle&&forcePathStyle,useAccelerateEndpoint:null!=useAccelerateEndpoint&&useAccelerateEndpoint,disableMultiregionAccessPoints:null!=disableMultiregionAccessPoints&&disableMultiregionAccessPoints,followRegionRedirects:null!=followRegionRedirects&&followRegionRedirects,s3ExpressIdentityProvider:null!=s3ExpressIdentityProvider?s3ExpressIdentityProvider:new S3ExpressIdentityProviderImpl((async key2=>s3ClientProvider().send(new CreateSessionCommandCtor({Bucket:key2})))),bucketEndpoint:null!=bucketEndpoint&&bucketEndpoint})};THROW_IF_EMPTY_BODY={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0};throw200ExceptionsMiddleware=config=>(next2,context2)=>async args=>{const result=await next2(args),{response}=result;if(!HttpResponse.isInstance(response))return result;const{statusCode,body:sourceBody}=response;if(statusCode<200||statusCode>=300)return result;if("function"!=typeof(null==sourceBody?void 0:sourceBody.stream)&&"function"!=typeof(null==sourceBody?void 0:sourceBody.pipe)&&"function"!=typeof(null==sourceBody?void 0:sourceBody.tee))return result;let bodyCopy=sourceBody,body=sourceBody;!sourceBody||"object"!=typeof sourceBody||sourceBody instanceof Uint8Array||([bodyCopy,body]=await async function splitStream(stream){"function"==typeof stream.stream&&(stream=stream.stream());return stream.tee()}(sourceBody));response.body=body;const bodyBytes=await collectBody2(bodyCopy,{streamCollector:async stream=>async function headStream(stream,bytes){var _a8;let byteLengthCounter=0;const chunks=[],reader=stream.getReader();let isDone=!1;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);byteLengthCounter+=null!=(_a8=null==value?void 0:value.byteLength)?_a8:0}if(byteLengthCounter>=bytes)break;isDone=done}reader.releaseLock();const collected=new Uint8Array(Math.min(bytes,byteLengthCounter));let offset=0;for(const chunk of chunks){if(chunk.byteLength>collected.byteLength-offset){collected.set(chunk.subarray(0,collected.byteLength-offset),offset);break}collected.set(chunk,offset);offset+=chunk.length}return collected}(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 err2=new Error("S3 aborted request");err2.name="InternalError";throw err2}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(function validateBucketNameMiddleware({bucketEndpoint}){return next2=>async args=>{const{input:{Bucket}}=args;if(!bucketEndpoint&&"string"==typeof Bucket&&!validate(Bucket)&&Bucket.indexOf("/")>=0){const err2=new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);err2.name="InvalidBucketName";throw err2}return next2({...args})}}(options),validateBucketNameMiddlewareOptions);clientStack.addRelativeTo(function bucketEndpointMiddleware(options){return(next2,context2)=>async args=>{var _a8,_b4,_c3,_d2;if(options.bucketEndpoint){const endpoint=context2.endpointV2;if(endpoint){const bucket=args.input.Bucket;if("string"==typeof bucket)try{const bucketEndpointUrl=new URL(bucket);context2.endpointV2={...endpoint,url:bucketEndpointUrl}}catch(e3){const warning=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;"NoOpLogger"===(null==(_b4=null==(_a8=context2.logger)?void 0:_a8.constructor)?void 0:_b4.name)?console.warn(warning):null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,warning);throw e3}}}return next2(args)}}(options),bucketEndpointMiddlewareOptions)}});EndpointCache=class{constructor({size,params}){this.data=new Map;this.parameters=[];this.capacity=null!=size?size:50;params&&(this.parameters=params)}get(endpointParams,resolver){const key2=this.hash(endpointParams);if(!1===key2)return resolver();if(!this.data.has(key2)){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(key2,resolver())}return this.data.get(key2)}size(){return this.data.size}hash(endpointParams){var _a8;let buffer="";const{parameters}=this;if(0===parameters.length)return!1;for(const param of parameters){const val2=String(null!=(_a8=endpointParams[param])?_a8:"");if(val2.includes("|;"))return!1;buffer+=val2+"|;"}return buffer}};IP_V4_REGEX=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$");isIpAddress=value=>IP_V4_REGEX.test(value)||value.startsWith("[")&&value.endsWith("]");VALID_HOST_LABEL_REGEX=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$");isValidHostLabel=(value,allowSubDomains=!1)=>{if(!allowSubDomains)return VALID_HOST_LABEL_REGEX.test(value);const labels=value.split(".");for(const label of labels)if(!isValidHostLabel(label))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=(template2,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 callFunction(obj,options);if(obj.ref)return getReferenceValue(obj,options);throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`)};callFunction=({fn,argv},options)=>{const evaluatedArgs=argv.map((arg=>["boolean","number"].includes(typeof arg)?arg:evaluateExpression(arg,"arg",options))),fnSegments=fn.split(".");return fnSegments[0]in customEndpointFunctions&&null!=fnSegments[1]?customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs):endpointFunctions[fn](...evaluatedArgs)};evaluateCondition=({assign:assign2,...fnArgs},options)=>{var _a8,_b4;if(assign2&&assign2 in options.referenceRecord)throw new EndpointError(`'${assign2}' is already defined in Reference Record.`);const value=callFunction(fnArgs,options);null==(_b4=null==(_a8=options.logger)?void 0:_a8.debug)||_b4.call(_a8,`endpoints evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:""===value||!!value,...null!=assign2&&{toAssign:{name:assign2,value}}}};evaluateConditions=(conditions=[],options)=>{var _a8,_b4;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==(_b4=null==(_a8=options.logger)?void 0:_a8.debug)||_b4.call(_a8,`endpoints assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`)}}return{result:!0,referenceRecord:conditionsReferenceRecord}};getEndpointHeaders=(headers,options)=>Object.entries(headers).reduce(((acc,[headerKey,headerVal])=>({...acc,[headerKey]:headerVal.map((headerValEntry=>{const processedExpr=evaluateExpression(headerValEntry,"Header value entry",options);if("string"!=typeof processedExpr)throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);return processedExpr}))})),{});getEndpointProperty=(property,options)=>{if(Array.isArray(property))return property.map((propertyEntry=>getEndpointProperty(propertyEntry,options)));switch(typeof property){case"string":return evaluateTemplate(property,options);case"object":if(null===property)throw new EndpointError(`Unexpected endpoint property: ${property}`);return getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError("Unexpected endpoint property type: "+typeof property)}};getEndpointProperties=(properties,options)=>Object.entries(properties).reduce(((acc,[propertyKey,propertyVal])=>({...acc,[propertyKey]:getEndpointProperty(propertyVal,options)})),{});getEndpointUrl=(endpointUrl,options)=>{const expression=evaluateExpression(endpointUrl,"Endpoint URL",options);if("string"==typeof expression)try{return new URL(expression)}catch(error){console.error(`Failed to construct URL with ${expression}`,error);throw error}throw new EndpointError("Endpoint URL must be a string, got "+typeof expression)};evaluateEndpointRule=(endpointRule,options)=>{var _a8,_b4;const{conditions,endpoint}=endpointRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(!result)return;const endpointRuleOptions={...options,referenceRecord:{...options.referenceRecord,...referenceRecord}},{url,properties,headers}=endpoint;null==(_b4=null==(_a8=options.logger)?void 0:_a8.debug)||_b4.call(_a8,`endpoints Resolving endpoint from template: ${toDebugString(endpoint)}`);return{...null!=headers&&{headers:getEndpointHeaders(headers,endpointRuleOptions)},...null!=properties&&{properties:getEndpointProperties(properties,endpointRuleOptions)},url:getEndpointUrl(url,endpointRuleOptions)}};evaluateErrorRule=(errorRule,options)=>{const{conditions,error}=errorRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)throw new EndpointError(evaluateExpression(error,"Error",{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}}))};evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)return evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};evaluateRules=(rules,options)=>{for(const rule of rules)if("endpoint"===rule.type){const endpointOrUndefined=evaluateEndpointRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}else if("error"===rule.type)evaluateErrorRule(rule,options);else{if("tree"!==rule.type)throw new EndpointError(`Unknown endpoint rule: ${rule}`);{const endpointOrUndefined=evaluateTreeRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}}throw new EndpointError("Rules evaluation failed")};resolveEndpoint=(ruleSetObject,options)=>{var _a8,_b4,_c3,_d2,_e2;const{endpointParams,logger:logger2}=options,{parameters,rules}=ruleSetObject;null==(_b4=null==(_a8=options.logger)?void 0:_a8.debug)||_b4.call(_a8,`endpoints Initial EndpointParams: ${toDebugString(endpointParams)}`);const paramsWithDefault=Object.entries(parameters).filter((([,v2])=>null!=v2.default)).map((([k2,v2])=>[k2,v2.default]));if(paramsWithDefault.length>0)for(const[paramKey,paramDefaultValue]of paramsWithDefault)endpointParams[paramKey]=null!=(_c3=endpointParams[paramKey])?_c3:paramDefaultValue;const requiredParams=Object.entries(parameters).filter((([,v2])=>v2.required)).map((([k2])=>k2));for(const requiredParam of requiredParams)if(null==endpointParams[requiredParam])throw new EndpointError(`Missing required parameter: '${requiredParam}'`);const endpoint=evaluateRules(rules,{endpointParams,logger:logger2,referenceRecord:{}});null==(_e2=null==(_d2=options.logger)?void 0:_d2.debug)||_e2.call(_d2,`endpoints Resolved endpoint: ${toDebugString(endpoint)}`);return endpoint};selectedPartitionsInfo={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"AWS Standard global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"AWS China global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"AWS GovCloud (US) global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"c2s.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"AWS ISO (US) global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"sc2s.sgov.gov",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"AWS ISOB (US) global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"cloud.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"AWS ISOE (Europe) global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"csp.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"AWS ISOF global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"amazonaws.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"EU (Germany)"}}}],version:"1.1"};awsEndpointFunctions={isVirtualHostableS3Bucket:isVirtualHostableS3Bucket=(value,allowSubDomains=!1)=>{if(allowSubDomains){for(const label of value.split("."))if(!isVirtualHostableS3Bucket(label))return!1;return!0}return!(!isValidHostLabel(value)||value.length<3||value.length>63||value!==value.toLowerCase()||isIpAddress(value))},parseArn:value=>{const segments=value.split(":");if(segments.length<6)return null;const[arn,partition2,service,region,accountId,...resourcePath]=segments;return"arn"!==arn||""===partition2||""===service||""===resourcePath.join(":")?null:{partition:partition2,service,region,accountId,resourceId:resourcePath.map((resource=>resource.split("/"))).flat()}},partition:value=>{const{partitions}=selectedPartitionsInfo;for(const partition2 of partitions){const{regions,outputs}=partition2;for(const[region,regionData]of Object.entries(regions))if(region===value)return{...outputs,...regionData}}for(const partition2 of partitions){const{regionRegex,outputs}=partition2;if(new RegExp(regionRegex).test(value))return{...outputs}}const DEFAULT_PARTITION=partitions.find((partition2=>"aws"===partition2.id));if(!DEFAULT_PARTITION)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...DEFAULT_PARTITION.outputs}}};customEndpointFunctions.aws=awsEndpointFunctions;ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;UA_NAME_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;UA_VALUE_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;userAgentMiddleware=options=>(next2,context2)=>async args=>{var _a8,_b4,_c3,_d2;const{request:request2}=args;if(!HttpRequest.isInstance(request2))return next2(args);const{headers}=request2,userAgent=(null==(_a8=null==context2?void 0:context2.userAgent)?void 0:_a8.map(escapeUserAgent))||[],defaultUserAgent2=(await options.defaultUserAgentProvider()).map(escapeUserAgent);await async function checkFeatures(context2,config,args){var _a8,_b4,_c3,_d2,_e2,_f,_g,_h;const request2=args.request;"rpc-v2-cbor"===(null==(_a8=null==request2?void 0:request2.headers)?void 0:_a8["smithy-protocol"])&&setFeature(context2,"PROTOCOL_RPC_V2_CBOR","M");if("function"==typeof config.retryStrategy){const retryStrategy=await config.retryStrategy();"function"==typeof retryStrategy.acquireInitialRetryToken?(null==(_c3=null==(_b4=retryStrategy.constructor)?void 0:_b4.name)?void 0:_c3.includes("Adaptive"))?setFeature(context2,"RETRY_MODE_ADAPTIVE","F"):setFeature(context2,"RETRY_MODE_STANDARD","E"):setFeature(context2,"RETRY_MODE_LEGACY","D")}if("function"==typeof config.accountIdEndpointMode){const endpointV2=context2.endpointV2;String(null==(_d2=null==endpointV2?void 0:endpointV2.url)?void 0:_d2.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)&&setFeature(context2,"ACCOUNT_ID_ENDPOINT","O");switch(await(null==(_e2=config.accountIdEndpointMode)?void 0:_e2.call(config))){case"disabled":setFeature(context2,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":setFeature(context2,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":setFeature(context2,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const identity=null==(_g=null==(_f=context2.__smithy_context)?void 0:_f.selectedHttpAuthScheme)?void 0:_g.identity;if(null==identity?void 0:identity.$source){const credentials=identity;credentials.accountId&&setFeature(context2,"RESOLVED_ACCOUNT_ID","T");for(const[key2,value]of Object.entries(null!=(_h=credentials.$source)?_h:{}))setFeature(context2,key2,value)}}(context2,options,args);const awsContext=context2;defaultUserAgent2.push(`m/${function encodeFeatures(features){let buffer="";for(const key2 in features){const val2=features[key2];if(!(buffer.length+val2.length+1<=1024))break;buffer.length?buffer+=","+val2:buffer+=val2}return buffer}(Object.assign({},null==(_b4=context2.__smithy_context)?void 0:_b4.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 sdkUserAgentValue=[].concat([...defaultUserAgent2,...userAgent,...customUserAgent]).join(" "),normalUAValue=[...defaultUserAgent2.filter((section=>section.startsWith("aws-sdk-"))),...customUserAgent].join(" ");if("browser"!==options.runtime){normalUAValue&&(headers["x-amz-user-agent"]=headers["x-amz-user-agent"]?`${headers["user-agent"]} ${normalUAValue}`:normalUAValue);headers["user-agent"]=sdkUserAgentValue}else headers["x-amz-user-agent"]=sdkUserAgentValue;return next2({...args,request:request2})};escapeUserAgent=userAgentPair=>{var _a8;const name=userAgentPair[0].split("/").map((part=>part.replace(UA_NAME_ESCAPE_REGEX,"-"))).join("/"),version2=null==(_a8=userAgentPair[1])?void 0:_a8.replace(UA_VALUE_ESCAPE_REGEX,"-"),prefixSeparatorIndex=name.indexOf("/"),prefix=name.substring(0,prefixSeparatorIndex);let uaName=name.substring(prefixSeparatorIndex+1);"api"===prefix&&(uaName=uaName.toLowerCase());return[prefix,uaName,version2].filter((item=>item&&item.length>0)).reduce(((acc,item,index6)=>{switch(index6){case 0:return item;case 1:return`${acc}/${item}`;default:return`${acc}#${item}`}}),"")};getUserAgentMiddlewareOptions={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0};getUserAgentPlugin=config=>({applyToStack:clientStack=>{clientStack.add(userAgentMiddleware(config),getUserAgentMiddlewareOptions)}});isFipsRegion=region=>"string"==typeof region&&(region.startsWith("fips-")||region.endsWith("-fips"));getRealRegion=region=>isFipsRegion(region)?["fips-aws-global","aws-fips"].includes(region)?"us-east-1":region.replace(/fips-(dkr-|prod-)?|-fips/,""):region;resolveRegionConfig=input=>{const{region,useFipsEndpoint}=input;if(!region)throw new Error("Region is missing");return Object.assign(input,{region:async()=>{if("string"==typeof region)return getRealRegion(region);const providedRegion=await region();return getRealRegion(providedRegion)},useFipsEndpoint:async()=>{const providedRegion="string"==typeof region?region:await region();return!!isFipsRegion(providedRegion)||("function"!=typeof useFipsEndpoint?Promise.resolve(!!useFipsEndpoint):useFipsEndpoint())}})};resolveEventStreamSerdeConfig=input=>Object.assign(input,{eventStreamMarshaller:input.eventStreamSerdeProvider(input)});CONTENT_LENGTH_HEADER2="content-length";contentLengthMiddlewareOptions={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0};getContentLengthPlugin=options=>({applyToStack:clientStack=>{clientStack.add(function contentLengthMiddleware(bodyLengthChecker){return next2=>async args=>{const request2=args.request;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(body&&-1===Object.keys(headers).map((str=>str.toLowerCase())).indexOf("content-length"))try{const length=bodyLengthChecker(body);request2.headers={...request2.headers,[CONTENT_LENGTH_HEADER2]:String(length)}}catch(error){}}return next2({...args,request:request2})}}(options.bodyLengthChecker),contentLengthMiddlewareOptions)}});resolveParamsForS3=async endpointParams=>{const bucket=(null==endpointParams?void 0:endpointParams.Bucket)||"";"string"==typeof endpointParams.Bucket&&(endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?")));if(isArnBucketName(bucket)){if(!0===endpointParams.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!isDnsCompatibleBucketName(bucket)||-1!==bucket.indexOf(".")&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3)&&(endpointParams.ForcePathStyle=!0);if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=!0;endpointParams.DisableMRAP=!0}return endpointParams};DOMAIN_PATTERN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;IP_ADDRESS_PATTERN=/(\d+\.){3}\d+/;DOTS_PATTERN=/\.\./;isDnsCompatibleBucketName=bucketName=>DOMAIN_PATTERN.test(bucketName)&&!IP_ADDRESS_PATTERN.test(bucketName)&&!DOTS_PATTERN.test(bucketName);isArnBucketName=bucketName=>{const[arn,partition2,service,,,bucket]=bucketName.split(":"),isArn="arn"===arn&&bucketName.split(":").length>=6,isValidArn=Boolean(isArn&&partition2&&service&&bucket);if(isArn&&!isValidArn)throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);return isValidArn};createConfigValueProvider=(configKey,canonicalEndpointParamKey,config)=>{const configProvider=async()=>{var _a8;const configValue=null!=(_a8=config[configKey])?_a8:config[canonicalEndpointParamKey];return"function"==typeof configValue?configValue():configValue};return"credentialScope"===configKey||"CredentialScope"===canonicalEndpointParamKey?async()=>{var _a8;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a8=null==credentials?void 0:credentials.credentialScope)?_a8:null==credentials?void 0:credentials.CredentialScope}:"accountId"===configKey||"AccountId"===canonicalEndpointParamKey?async()=>{var _a8;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a8=null==credentials?void 0:credentials.accountId)?_a8:null==credentials?void 0:credentials.AccountId}:"endpoint"===configKey||"endpoint"===canonicalEndpointParamKey?async()=>{const endpoint=await configProvider();if(endpoint&&"object"==typeof endpoint){if("url"in endpoint)return endpoint.url.href;if("hostname"in endpoint){const{protocol,hostname,port,path:path2}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path2}`}}return endpoint}:configProvider};getEndpointFromConfig=async serviceId=>{};parseUrl=url=>{if("string"==typeof url)return parseUrl(new URL(url));const{hostname,pathname,port,protocol,search}=url;let query3;search&&(query3=function parseQueryString(querystring){const query3={};if(querystring=querystring.replace(/^\?/,""))for(const pair of querystring.split("&")){let[key2,value=null]=pair.split("=");key2=decodeURIComponent(key2);value&&(value=decodeURIComponent(value));key2 in query3?Array.isArray(query3[key2])?query3[key2].push(value):query3[key2]=[query3[key2],value]:query3[key2]=value}return query3}(search));return{hostname,port:port?parseInt(port):void 0,protocol,path:pathname,query:query3}};toEndpointV1=endpoint=>"object"==typeof endpoint?"url"in endpoint?parseUrl(endpoint.url):endpoint:parseUrl(endpoint);getEndpointFromInstructions=async(commandInput,instructionsSupplier,clientConfig,context2)=>{if(!clientConfig.endpoint){let endpointFromConfig;endpointFromConfig=clientConfig.serviceConfiguredEndpoint?await clientConfig.serviceConfiguredEndpoint():await getEndpointFromConfig(clientConfig.serviceId);endpointFromConfig&&(clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig)))}const endpointParams=await resolveParams(commandInput,instructionsSupplier,clientConfig);if("function"!=typeof clientConfig.endpointProvider)throw new Error("config.endpointProvider is not set.");return clientConfig.endpointProvider(endpointParams,context2)};resolveParams=async(commandInput,instructionsSupplier,clientConfig)=>{var _a8;const endpointParams={},instructions=(null==(_a8=null==instructionsSupplier?void 0:instructionsSupplier.getEndpointParameterInstructions)?void 0:_a8.call(instructionsSupplier))||{};for(const[name,instruction]of Object.entries(instructions))switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider(instruction.name,name,clientConfig)();break;case"operationContextParams":endpointParams[name]=instruction.get(commandInput);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}0===Object.keys(instructions).length&&Object.assign(endpointParams,clientConfig);"s3"===String(clientConfig.serviceId).toLowerCase()&&await resolveParamsForS3(endpointParams);return endpointParams};endpointMiddleware=({config,instructions})=>(next2,context2)=>async args=>{var _a8,_b4,_c3;config.endpoint&&function setFeature2(context2,feature,value){context2.__smithy_context?context2.__smithy_context.features||(context2.__smithy_context.features={}):context2.__smithy_context={features:{}};context2.__smithy_context.features[feature]=value}(context2,"ENDPOINT_OVERRIDE","N");const endpoint=await getEndpointFromInstructions(args.input,{getEndpointParameterInstructions:()=>instructions},{...config},context2);context2.endpointV2=endpoint;context2.authSchemes=null==(_a8=endpoint.properties)?void 0:_a8.authSchemes;const authScheme=null==(_b4=context2.authSchemes)?void 0:_b4[0];if(authScheme){context2.signing_region=authScheme.signingRegion;context2.signing_service=authScheme.signingName;const smithyContext=getSmithyContext2(context2),httpAuthOption=null==(_c3=null==smithyContext?void 0:smithyContext.selectedHttpAuthScheme)?void 0:_c3.httpAuthOption;httpAuthOption&&(httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties))}return next2({...args})};endpointMiddlewareOptions={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:serializerMiddlewareOption.name};getEndpointPlugin=(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware({config,instructions}),endpointMiddlewareOptions)}});resolveEndpointConfig=input=>{var _a8;const tls=null==(_a8=input.tls)||_a8,{endpoint,useDualstackEndpoint,useFipsEndpoint}=input,customEndpointProvider=null!=endpoint?async()=>toEndpointV1(await normalizeProvider(endpoint)()):void 0,isCustomEndpoint=!!endpoint,resolvedConfig=Object.assign(input,{endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider(null!=useDualstackEndpoint&&useDualstackEndpoint),useFipsEndpoint:normalizeProvider(null!=useFipsEndpoint&&useFipsEndpoint)});let configuredEndpointPromise;resolvedConfig.serviceConfiguredEndpoint=async()=>{input.serviceId&&!configuredEndpointPromise&&(configuredEndpointPromise=getEndpointFromConfig(input.serviceId));return configuredEndpointPromise};return resolvedConfig};(function(RETRY_MODES2){RETRY_MODES2.STANDARD="standard";RETRY_MODES2.ADAPTIVE="adaptive"})(RETRY_MODES||(RETRY_MODES={}));DEFAULT_RETRY_MODE=RETRY_MODES.STANDARD;CLOCK_SKEW_ERROR_CODES=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"];THROTTLING_ERROR_CODES=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];TRANSIENT_ERROR_CODES=["TimeoutError","RequestTimeout","RequestTimeoutException"];TRANSIENT_ERROR_STATUS_CODES=[500,502,503,504];NODEJS_TIMEOUT_ERROR_CODES=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];0;0;isClockSkewCorrectedError=error=>{var _a8;return null==(_a8=error.$metadata)?void 0:_a8.clockSkewCorrected};isBrowserNetworkError=error=>!!(error&&error instanceof TypeError)&&new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]).has(error.message);isThrottlingError=error=>{var _a8,_b4;return 429===(null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)||THROTTLING_ERROR_CODES.includes(error.name)||1==(null==(_b4=error.$retryable)?void 0:_b4.throttling)};isTransientError=(error,depth=0)=>{var _a8;return isClockSkewCorrectedError(error)||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes((null==error?void 0:error.code)||"")||TRANSIENT_ERROR_STATUS_CODES.includes((null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)||0)||isBrowserNetworkError(error)||void 0!==error.cause&&depth<=10&&isTransientError(error.cause,depth+1)};isServerError=error=>{var _a8;if(void 0!==(null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)){const statusCode=error.$metadata.httpStatusCode;return 500<=statusCode&&statusCode<=599&&!isTransientError(error)}return!1};(DefaultRateLimiter=class _DefaultRateLimiter{constructor(options){var _a8,_b4,_c3,_d2,_e2;this.currentCapacity=0;this.enabled=!1;this.lastMaxRate=0;this.measuredTxRate=0;this.requestCount=0;this.lastTimestamp=0;this.timeWindow=0;this.beta=null!=(_a8=null==options?void 0:options.beta)?_a8:.7;this.minCapacity=null!=(_b4=null==options?void 0:options.minCapacity)?_b4:1;this.minFillRate=null!=(_c3=null==options?void 0:options.minFillRate)?_c3:.5;this.scaleConstant=null!=(_d2=null==options?void 0:options.scaleConstant)?_d2:.4;this.smooth=null!=(_e2=null==options?void 0:options.smooth)?_e2:.8;const currentTimeInSeconds=this.getCurrentTimeInSeconds();this.lastThrottleTime=currentTimeInSeconds;this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds());this.fillRate=this.minFillRate;this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(amount){if(this.enabled){this.refillTokenBucket();if(amount>this.currentCapacity){const delay2=(amount-this.currentCapacity)/this.fillRate*1e3;await new Promise((resolve=>_DefaultRateLimiter.setTimeoutFn(resolve,delay2)))}this.currentCapacity=this.currentCapacity-amount}}refillTokenBucket(){const timestamp=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=timestamp;return}const fillAmount=(timestamp-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+fillAmount);this.lastTimestamp=timestamp}updateClientSendingRate(response){let calculatedRate;this.updateMeasuredRate();if(isThrottlingError(response)){const rateToUse=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=rateToUse;this.calculateTimeWindow();this.lastThrottleTime=this.getCurrentTimeInSeconds();calculatedRate=this.cubicThrottle(rateToUse);this.enableTokenBucket()}else{this.calculateTimeWindow();calculatedRate=this.cubicSuccess(this.getCurrentTimeInSeconds())}const newRate=Math.min(calculatedRate,2*this.measuredTxRate);this.updateTokenBucketRate(newRate)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(rateToUse){return this.getPrecise(rateToUse*this.beta)}cubicSuccess(timestamp){return this.getPrecise(this.scaleConstant*Math.pow(timestamp-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(newRate){this.refillTokenBucket();this.fillRate=Math.max(newRate,this.minFillRate);this.maxCapacity=Math.max(newRate,this.minCapacity);this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t3=this.getCurrentTimeInSeconds(),timeBucket=Math.floor(2*t3)/2;this.requestCount++;if(timeBucket>this.lastTxRateBucket){const currentRate=this.requestCount/(timeBucket-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(currentRate*this.smooth+this.measuredTxRate*(1-this.smooth));this.requestCount=0;this.lastTxRateBucket=timeBucket}}getPrecise(num){return parseFloat(num.toFixed(8))}}).setTimeoutFn=setTimeout;getDefaultRetryBackoffStrategy=()=>{let delayBase=100;return{computeNextBackoffDelay:attempts=>Math.floor(Math.min(2e4,Math.random()*2**attempts*delayBase)),setDelayBase:delay2=>{delayBase=delay2}}};createDefaultRetryToken=({retryDelay,retryCount,retryCost})=>({getRetryCount:()=>retryCount,getRetryDelay:()=>Math.min(2e4,retryDelay),getRetryCost:()=>retryCost});StandardRetryStrategy=class{constructor(maxAttempts){this.maxAttempts=maxAttempts;this.mode=RETRY_MODES.STANDARD;this.capacity=500;this.retryBackoffStrategy=getDefaultRetryBackoffStrategy();this.maxAttemptsProvider="function"==typeof maxAttempts?maxAttempts:async()=>maxAttempts}async acquireInitialRetryToken(retryTokenScope){return createDefaultRetryToken({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(token,errorInfo){const maxAttempts=await this.getMaxAttempts();if(this.shouldRetry(token,errorInfo,maxAttempts)){const errorType=errorInfo.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===errorType?500:100);const delayFromErrorType=this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()),retryDelay=errorInfo.retryAfterHint?Math.max(errorInfo.retryAfterHint.getTime()-Date.now()||0,delayFromErrorType):delayFromErrorType,capacityCost=this.getCapacityCost(errorType);this.capacity-=capacityCost;return createDefaultRetryToken({retryDelay,retryCount:token.getRetryCount()+1,retryCost:capacityCost})}throw new Error("No retry token available")}recordSuccess(token){var _a8;this.capacity=Math.max(500,this.capacity+(null!=(_a8=token.getRetryCost())?_a8:1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(error){console.warn("Max attempts provider could not resolve. Using default of 3");return 3}}shouldRetry(tokenToRenew,errorInfo,maxAttempts){return tokenToRenew.getRetryCount()+1=this.getCapacityCost(errorInfo.errorType)&&this.isRetryableError(errorInfo.errorType)}getCapacityCost(errorType){return"TRANSIENT"===errorType?10:5}isRetryableError(errorType){return"THROTTLING"===errorType||"TRANSIENT"===errorType}};AdaptiveRetryStrategy=class{constructor(maxAttemptsProvider,options){this.maxAttemptsProvider=maxAttemptsProvider;this.mode=RETRY_MODES.ADAPTIVE;const{rateLimiter}=null!=options?options:{};this.rateLimiter=null!=rateLimiter?rateLimiter:new DefaultRateLimiter;this.standardRetryStrategy=new StandardRetryStrategy(maxAttemptsProvider)}async acquireInitialRetryToken(retryTokenScope){await this.rateLimiter.getSendToken();return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope)}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){this.rateLimiter.updateClientSendingRate(errorInfo);return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew,errorInfo)}recordSuccess(token){this.rateLimiter.updateClientSendingRate({});this.standardRetryStrategy.recordSuccess(token)}};ConfiguredRetryStrategy=class extends StandardRetryStrategy{constructor(maxAttempts,computeNextBackoffDelay=100){super("function"==typeof maxAttempts?maxAttempts:async()=>maxAttempts);this.computeNextBackoffDelay="number"==typeof computeNextBackoffDelay?()=>computeNextBackoffDelay:computeNextBackoffDelay}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){const token=await super.refreshRetryTokenForRetry(tokenToRenew,errorInfo);token.getRetryDelay=()=>this.computeNextBackoffDelay(token.getRetryCount());return token}};rnds8=new Uint8Array(16);byteToHex=[];for(let i2=0;i2<256;++i2)byteToHex.push((i2+256).toString(16).slice(1));randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);native_default={randomUUID};v4_default=function v4(options,buf,offset){if(native_default.randomUUID&&!buf&&!options)return native_default.randomUUID();const rnds=(options=options||{}).random||(options.rng||rng)();rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;if(buf){offset=offset||0;for(let i2=0;i2<16;++i2)buf[offset+i2]=rnds[i2];return buf}return function unsafeStringify(arr,offset=0){return byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]}(rnds)};asSdkError=error=>error instanceof Error?error:error instanceof Object?Object.assign(new Error,error):"string"==typeof error?new Error(error):new Error(`AWS SDK error wrapper for ${error}`);resolveRetryConfig=input=>{const{retryStrategy,retryMode:_retryMode,maxAttempts:_maxAttempts}=input,maxAttempts=normalizeProvider(null!=_maxAttempts?_maxAttempts:3);return Object.assign(input,{maxAttempts,retryStrategy:async()=>retryStrategy||(await normalizeProvider(_retryMode)()===RETRY_MODES.ADAPTIVE?new AdaptiveRetryStrategy(maxAttempts):new StandardRetryStrategy(maxAttempts))})};isStreamingPayload=request2=>(null==request2?void 0:request2.body)instanceof ReadableStream;retryMiddleware=options=>(next2,context2)=>async args=>{var _a8;let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(!isRetryStrategyV2(retryStrategy)){(null==retryStrategy?void 0:retryStrategy.mode)&&(context2.userAgent=[...context2.userAgent||[],["cfg/retry-mode",retryStrategy.mode]]);return retryStrategy.retry(next2,args)}{let retryToken=await retryStrategy.acquireInitialRetryToken(context2.partition_id),lastError=new Error,attempts=0,totalRetryDelay=0;const{request:request2}=args,isRequest=HttpRequest.isInstance(request2);isRequest&&(request2.headers["amz-sdk-invocation-id"]=v4_default());for(;;)try{isRequest&&(request2.headers["amz-sdk-request"]=`attempt=${attempts+1}; max=${maxAttempts}`);const{response,output}=await next2(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e3){const retryErrorInfo=getRetryErrorInfo(e3);lastError=asSdkError(e3);if(isRequest&&isStreamingPayload(request2)){null==(_a8=context2.logger instanceof NoOpLogger?console:context2.logger)||_a8.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){lastError.$metadata||(lastError.$metadata={});lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay2=retryToken.getRetryDelay();totalRetryDelay+=delay2;await new Promise((resolve=>setTimeout(resolve,delay2)))}}};isRetryStrategyV2=retryStrategy=>void 0!==retryStrategy.acquireInitialRetryToken&&void 0!==retryStrategy.refreshRetryTokenForRetry&&void 0!==retryStrategy.recordSuccess;getRetryErrorInfo=error=>{const errorInfo={error,errorType:getRetryErrorType(error)},retryAfterHint=getRetryAfterHint(error.$response);retryAfterHint&&(errorInfo.retryAfterHint=retryAfterHint);return errorInfo};getRetryErrorType=error=>isThrottlingError(error)?"THROTTLING":isTransientError(error)?"TRANSIENT":isServerError(error)?"SERVER_ERROR":"CLIENT_ERROR";retryMiddlewareOptions={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};getRetryPlugin=options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware(options),retryMiddlewareOptions)}});getRetryAfterHint=response=>{if(!HttpResponse.isInstance(response))return;const retryAfterHeaderName=Object.keys(response.headers).find((key2=>"retry-after"===key2.toLowerCase()));if(!retryAfterHeaderName)return;const retryAfter=response.headers[retryAfterHeaderName],retryAfterSeconds=Number(retryAfter);return Number.isNaN(retryAfterSeconds)?new Date(retryAfter):new Date(1e3*retryAfterSeconds)};SignatureV4MultiRegion=class{constructor(options){__publicField(this,"sigv4aSigner");__publicField(this,"sigv4Signer");__publicField(this,"signerOptions");this.sigv4Signer=new SignatureV4S3Express(options);this.signerOptions=options}async sign(requestToSign,options={}){return"*"===options.signingRegion?this.getSigv4aSigner().sign(requestToSign,options):this.sigv4Signer.sign(requestToSign,options)}async signWithCredentials(requestToSign,credentials,options={}){if("*"===options.signingRegion){this.getSigv4aSigner();throw new Error('signWithCredentials with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.signWithCredentials(requestToSign,credentials,options)}async presign(originalRequest,options={}){if("*"===options.signingRegion){this.getSigv4aSigner();throw new Error('presign with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.presign(originalRequest,options)}async presignWithCredentials(originalRequest,credentials,options={}){if("*"===options.signingRegion)throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(originalRequest,credentials,options)}getSigv4aSigner(){if(!this.sigv4aSigner){const CrtSignerV4=null,JsSigV4aSigner=null;if("node"===this.signerOptions.runtime){if(!CrtSignerV4&&!JsSigV4aSigner)throw new Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(CrtSignerV4&&"function"==typeof CrtSignerV4)this.sigv4aSigner=new CrtSignerV4({...this.signerOptions,signingAlgorithm:1});else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}return this.sigv4aSigner}};cp="required",cq="type",cr="rules",cs="conditions",ct="fn",cu="argv",cv="ref",cw="assign",cx="url",cy="properties",cz="backend",cA="authSchemes",cB="disableDoubleEncoding",cC="signingName",cD="signingRegion",cE="headers",cF="signingRegionSet";c=!0,d3="isSet",e2="booleanEquals",f="error",g="aws.partition",h="stringEquals",i="getAttr",j="name",k="substring",l="bucketSuffix",m2="parseURL",n2="endpoint",o="tree",p2="aws.isVirtualHostableS3Bucket",q="{url#scheme}://{Bucket}.{url#authority}{url#path}",r3="not",s="accessPointSuffix",t2="{url#scheme}://{url#authority}{url#path}",u="hardwareType",v="regionPrefix",w="bucketAliasSuffix",x="outpostId",y="isValidHostLabel",z="sigv4a",A="s3-outposts",B="s3",C="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",D="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",E="https://{Bucket}.s3.{partitionResult#dnsSuffix}",F="aws.parseArn",G="bucketArn",H="arnType",J="s3-object-lambda",K="accesspoint",L="accessPointName",M="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",N="mrapPartition",O="outpostType",P="arnPrefix",Q="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",R="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",S="https://s3.{partitionResult#dnsSuffix}",T={[cp]:!1,[cq]:"String"},U={[cp]:!0,default:!1,[cq]:"Boolean"},V={[cp]:!1,[cq]:"Boolean"},W={[ct]:e2,[cu]:[{[cv]:"Accelerate"},!0]},X={[ct]:e2,[cu]:[{[cv]:"UseFIPS"},!0]},Y={[ct]:e2,[cu]:[{[cv]:"UseDualStack"},!0]},Z={[ct]:d3,[cu]:[{[cv]:"Endpoint"}]},aa={[ct]:g,[cu]:[{[cv]:"Region"}],[cw]:"partitionResult"},ab={[ct]:h,[cu]:[{[ct]:i,[cu]:[{[cv]:"partitionResult"},j]},"aws-cn"]},ac={[ct]:d3,[cu]:[{[cv]:"Bucket"}]},ad={[cv]:"Bucket"},ae={[cs]:[Y],[f]:"S3Express does not support Dual-stack.",[cq]:f},af={[cs]:[W],[f]:"S3Express does not support S3 Accelerate.",[cq]:f},ag={[cs]:[Z,{[ct]:m2,[cu]:[{[cv]:"Endpoint"}],[cw]:"url"}],[cr]:[{[cs]:[{[ct]:d3,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"}]},{[ct]:e2,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"},!0]}],[cr]:[{[cs]:[{[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]}],[cr]:[{[cs]:[{[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"}],[cr]:[{[n2]:{[cx]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:p2,[cu]:[ad,!1]}],[cr]:[{[n2]:{[cx]:q,[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f}],[cq]:o},{[cs]:[{[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]}],[cr]:[{[cs]:[{[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"}],[cr]:[{[n2]:{[cx]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:p2,[cu]:[ad,!1]}],[cr]:[{[n2]:{[cx]:q,[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f}],[cq]:o},ah={[ct]:m2,[cu]:[{[cv]:"Endpoint"}],[cw]:"url"},ai={[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]},aj={[cv]:"url"},ak={[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"},al={[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},am={},an={[ct]:p2,[cu]:[ad,!1]},ao={[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f},ap={[ct]:d3,[cu]:[{[cv]:"UseS3ExpressControlEndpoint"}]},aq={[ct]:e2,[cu]:[{[cv]:"UseS3ExpressControlEndpoint"},!0]},ar={[ct]:r3,[cu]:[Z]},as={[f]:"Unrecognized S3Express bucket name format.",[cq]:f},at={[ct]:r3,[cu]:[ac]},au={[cv]:u},av={[cs]:[ar],[f]:"Expected a endpoint to be specified but no endpoint was found",[cq]:f},aw={[cA]:[{[cB]:!0,[j]:z,[cC]:A,[cF]:["*"]},{[cB]:!0,[j]:"sigv4",[cC]:A,[cD]:"{Region}"}]},ax={[ct]:e2,[cu]:[{[cv]:"ForcePathStyle"},!1]},ay={[cv]:"ForcePathStyle"},az={[ct]:e2,[cu]:[{[cv]:"Accelerate"},!1]},aA={[ct]:h,[cu]:[{[cv]:"Region"},"aws-global"]},aB={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"us-east-1"}]},aC={[ct]:r3,[cu]:[aA]},aD={[ct]:e2,[cu]:[{[cv]:"UseGlobalEndpoint"},!0]},aE={[cx]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{Region}"}]},[cE]:{}},aF={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{Region}"}]},aG={[ct]:e2,[cu]:[{[cv]:"UseGlobalEndpoint"},!1]},aH={[ct]:e2,[cu]:[{[cv]:"UseDualStack"},!1]},aI={[cx]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aJ={[ct]:e2,[cu]:[{[cv]:"UseFIPS"},!1]},aK={[cx]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aL={[cx]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aM={[ct]:e2,[cu]:[{[ct]:i,[cu]:[aj,"isIp"]},!1]},aN={[cx]:C,[cy]:aF,[cE]:{}},aO={[cx]:q,[cy]:aF,[cE]:{}},aP={[n2]:aO,[cq]:n2},aQ={[cx]:D,[cy]:aF,[cE]:{}},aR={[cx]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aS={[f]:"Invalid region: region was not a valid DNS name.",[cq]:f},aT={[cv]:G},aU={[cv]:H},aV={[ct]:i,[cu]:[aT,"service"]},aW={[cv]:L},aX={[cs]:[Y],[f]:"S3 Object Lambda does not support Dual-stack",[cq]:f},aY={[cs]:[W],[f]:"S3 Object Lambda does not support S3 Accelerate",[cq]:f},aZ={[cs]:[{[ct]:d3,[cu]:[{[cv]:"DisableAccessPoints"}]},{[ct]:e2,[cu]:[{[cv]:"DisableAccessPoints"},!0]}],[f]:"Access points are not supported for this operation",[cq]:f},ba={[cs]:[{[ct]:d3,[cu]:[{[cv]:"UseArnRegion"}]},{[ct]:e2,[cu]:[{[cv]:"UseArnRegion"},!1]},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[aT,"region"]},"{Region}"]}]}],[f]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[cq]:f},bb={[ct]:i,[cu]:[{[cv]:"bucketPartition"},j]},bc={[ct]:i,[cu]:[aT,"accountId"]},bd={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:J,[cD]:"{bucketArn#region}"}]},be={[f]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[cq]:f},bf={[f]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[cq]:f},bg={[f]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[cq]:f},bh={[f]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[cq]:f},bi={[f]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[cq]:f},bj={[f]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[cq]:f},bk={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{bucketArn#region}"}]},bl={[cA]:[{[cB]:!0,[j]:z,[cC]:A,[cF]:["*"]},{[cB]:!0,[j]:"sigv4",[cC]:A,[cD]:"{bucketArn#region}"}]},bm={[ct]:F,[cu]:[ad]},bn={[cx]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bo={[cx]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bp={[cx]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bq={[cx]:Q,[cy]:aF,[cE]:{}},br={[cx]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bs={[cv]:"UseObjectLambdaEndpoint"},bt={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:J,[cD]:"{Region}"}]},bu={[cx]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bv={[cx]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bw={[cx]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bx={[cx]:t2,[cy]:aF,[cE]:{}},by={[cx]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bz=[{[cv]:"Region"}],bA=[{[cv]:"Endpoint"}],bB=[ad],bC=[Y],bD=[W],bE=[Z,ah],bF=[{[ct]:d3,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"}]},{[ct]:e2,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"},!0]}],bG=[ak],bH=[an],bI=[aa],bJ=[X],bK=[{[ct]:k,[cu]:[ad,6,14,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,14,16,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bL=[{[cs]:[X],[n2]:{[cx]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:{}},[cq]:n2},{[n2]:{[cx]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:{}},[cq]:n2}],bM=[{[ct]:k,[cu]:[ad,6,15,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,15,17,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bN=[{[ct]:k,[cu]:[ad,6,19,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,19,21,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bO=[{[ct]:k,[cu]:[ad,6,20,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,20,22,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bP=[{[ct]:k,[cu]:[ad,6,26,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,26,28,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bQ=[{[cs]:[X],[n2]:{[cx]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2},{[n2]:{[cx]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],bR=[ad,0,7,!0],bS=[{[ct]:k,[cu]:[ad,7,15,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,15,17,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bT=[{[ct]:k,[cu]:[ad,7,16,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,16,18,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bU=[{[ct]:k,[cu]:[ad,7,20,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,20,22,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bV=[{[ct]:k,[cu]:[ad,7,21,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,21,23,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bW=[{[ct]:k,[cu]:[ad,7,27,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,27,29,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bX=[ac],bY=[{[ct]:y,[cu]:[{[cv]:x},!1]}],bZ=[{[ct]:h,[cu]:[{[cv]:v},"beta"]}],ca=["*"],cb=[{[ct]:y,[cu]:[{[cv]:"Region"},!1]}],cc=[{[ct]:h,[cu]:[{[cv]:"Region"},"us-east-1"]}],cd=[{[ct]:h,[cu]:[aU,K]}],ce=[{[ct]:i,[cu]:[aT,"resourceId[1]"],[cw]:L},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[aW,""]}]}],cf=[aT,"resourceId[1]"],cg=[{[ct]:r3,[cu]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[aT,"region"]},""]}]}],ch3=[{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[{[ct]:i,[cu]:[aT,"resourceId[2]"]}]}]}],ci=[aT,"resourceId[2]"],cj=[{[ct]:g,[cu]:[{[ct]:i,[cu]:[aT,"region"]}],[cw]:"bucketPartition"}],ck=[{[ct]:h,[cu]:[bb,{[ct]:i,[cu]:[{[cv]:"partitionResult"},j]}]}],cl=[{[ct]:y,[cu]:[{[ct]:i,[cu]:[aT,"region"]},!0]}],cm=[{[ct]:y,[cu]:[bc,!1]}],cn=[{[ct]:y,[cu]:[aW,!1]}],co=[{[ct]:y,[cu]:[{[cv]:"Region"},!0]}];ruleSet={version:"1.0",parameters:{Bucket:T,Region:T,UseFIPS:U,UseDualStack:U,Endpoint:T,ForcePathStyle:U,Accelerate:U,UseGlobalEndpoint:U,UseObjectLambdaEndpoint:V,Key:T,Prefix:T,CopySource:T,DisableAccessPoints:V,DisableMultiRegionAccessPoints:U,UseArnRegion:V,UseS3ExpressControlEndpoint:V,DisableS3ExpressSessionAuth:V},[cr]:[{[cs]:[{[ct]:d3,[cu]:bz}],[cr]:[{[cs]:[W,X],error:"Accelerate cannot be used with FIPS",[cq]:f},{[cs]:[Y,Z],error:"Cannot set dual-stack in combination with a custom endpoint.",[cq]:f},{[cs]:[Z,X],error:"A custom endpoint cannot be combined with FIPS",[cq]:f},{[cs]:[Z,W],error:"A custom endpoint cannot be combined with S3 Accelerate",[cq]:f},{[cs]:[X,aa,ab],error:"Partition does not support FIPS",[cq]:f},{[cs]:[ac,{[ct]:k,[cu]:[ad,0,6,c],[cw]:l},{[ct]:h,[cu]:[{[cv]:l},"--x-s3"]}],[cr]:[ae,af,ag,{[cs]:[ap,aq],[cr]:[{[cs]:bI,[cr]:[{[cs]:[ak,ar],[cr]:[{[cs]:bJ,endpoint:{[cx]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:al,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:al,[cE]:am},[cq]:n2}],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:bH,[cr]:[{[cs]:bI,[cr]:[{[cs]:bF,[cr]:[{[cs]:bK,[cr]:bL,[cq]:o},{[cs]:bM,[cr]:bL,[cq]:o},{[cs]:bN,[cr]:bL,[cq]:o},{[cs]:bO,[cr]:bL,[cq]:o},{[cs]:bP,[cr]:bL,[cq]:o},as],[cq]:o},{[cs]:bK,[cr]:bQ,[cq]:o},{[cs]:bM,[cr]:bQ,[cq]:o},{[cs]:bN,[cr]:bQ,[cq]:o},{[cs]:bO,[cr]:bQ,[cq]:o},{[cs]:bP,[cr]:bQ,[cq]:o},as],[cq]:o}],[cq]:o},ao],[cq]:o},{[cs]:[ac,{[ct]:k,[cu]:bR,[cw]:s},{[ct]:h,[cu]:[{[cv]:s},"--xa-s3"]}],[cr]:[ae,af,ag,{[cs]:bH,[cr]:[{[cs]:bI,[cr]:[{[cs]:bF,[cr]:[{[cs]:bS,[cr]:bL,[cq]:o},{[cs]:bT,[cr]:bL,[cq]:o},{[cs]:bU,[cr]:bL,[cq]:o},{[cs]:bV,[cr]:bL,[cq]:o},{[cs]:bW,[cr]:bL,[cq]:o},as],[cq]:o},{[cs]:bS,[cr]:bQ,[cq]:o},{[cs]:bT,[cr]:bQ,[cq]:o},{[cs]:bU,[cr]:bQ,[cq]:o},{[cs]:bV,[cr]:bQ,[cq]:o},{[cs]:bW,[cr]:bQ,[cq]:o},as],[cq]:o}],[cq]:o},ao],[cq]:o},{[cs]:[at,ap,aq],[cr]:[{[cs]:bI,[cr]:[{[cs]:bE,endpoint:{[cx]:t2,[cy]:al,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:am},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[ac,{[ct]:k,[cu]:[ad,49,50,c],[cw]:u},{[ct]:k,[cu]:[ad,8,12,c],[cw]:v},{[ct]:k,[cu]:bR,[cw]:w},{[ct]:k,[cu]:[ad,32,49,c],[cw]:x},{[ct]:g,[cu]:bz,[cw]:"regionPartition"},{[ct]:h,[cu]:[{[cv]:w},"--op-s3"]}],[cr]:[{[cs]:bY,[cr]:[{[cs]:[{[ct]:h,[cu]:[au,"e"]}],[cr]:[{[cs]:bZ,[cr]:[av,{[cs]:bE,endpoint:{[cx]:"https://{Bucket}.ec2.{url#authority}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{endpoint:{[cx]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{[cs]:[{[ct]:h,[cu]:[au,"o"]}],[cr]:[{[cs]:bZ,[cr]:[av,{[cs]:bE,endpoint:{[cx]:"https://{Bucket}.op-{outpostId}.{url#authority}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{endpoint:{[cx]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[cq]:f}],[cq]:o},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[cq]:f}],[cq]:o},{[cs]:bX,[cr]:[{[cs]:[Z,{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[{[ct]:m2,[cu]:bA}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[cq]:f},{[cs]:[ax,an],[cr]:[{[cs]:bI,[cr]:[{[cs]:cb,[cr]:[{[cs]:[W,ab],error:"S3 Accelerate cannot be used in this region",[cq]:f},{[cs]:[Y,X,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,X,az,ar,aC,aD],[cr]:[{endpoint:aE,[cq]:n2}],[cq]:o},{[cs]:[Y,X,az,ar,aC,aG],endpoint:aE,[cq]:n2},{[cs]:[aH,X,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,X,az,ar,aC,aD],[cr]:[{endpoint:aI,[cq]:n2}],[cq]:o},{[cs]:[aH,X,az,ar,aC,aG],endpoint:aI,[cq]:n2},{[cs]:[Y,aJ,W,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,aJ,W,ar,aC,aD],[cr]:[{endpoint:aK,[cq]:n2}],[cq]:o},{[cs]:[Y,aJ,W,ar,aC,aG],endpoint:aK,[cq]:n2},{[cs]:[Y,aJ,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,aJ,az,ar,aC,aD],[cr]:[{endpoint:aL,[cq]:n2}],[cq]:o},{[cs]:[Y,aJ,az,ar,aC,aG],endpoint:aL,[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,ai,aA],endpoint:{[cx]:C,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,aM,aA],endpoint:{[cx]:q,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,ai,aC,aD],[cr]:[{[cs]:cc,endpoint:aN,[cq]:n2},{endpoint:aN,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,az,Z,ah,aM,aC,aD],[cr]:[{[cs]:cc,endpoint:aO,[cq]:n2},aP],[cq]:o},{[cs]:[aH,aJ,az,Z,ah,ai,aC,aG],endpoint:aN,[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,aM,aC,aG],endpoint:aO,[cq]:n2},{[cs]:[aH,aJ,W,ar,aA],endpoint:{[cx]:D,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,W,ar,aC,aD],[cr]:[{[cs]:cc,endpoint:aQ,[cq]:n2},{endpoint:aQ,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,W,ar,aC,aG],endpoint:aQ,[cq]:n2},{[cs]:[aH,aJ,az,ar,aA],endpoint:{[cx]:E,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,ar,aC,aD],[cr]:[{[cs]:cc,endpoint:{[cx]:E,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:aR,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,az,ar,aC,aG],endpoint:aR,[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[Z,ah,{[ct]:h,[cu]:[{[ct]:i,[cu]:[aj,"scheme"]},"http"]},{[ct]:p2,[cu]:[ad,c]},ax,aJ,aH,az],[cr]:[{[cs]:bI,[cr]:[{[cs]:cb,[cr]:[aP],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[ax,{[ct]:F,[cu]:bB,[cw]:G}],[cr]:[{[cs]:[{[ct]:i,[cu]:[aT,"resourceId[0]"],[cw]:H},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[aU,""]}]}],[cr]:[{[cs]:[{[ct]:h,[cu]:[aV,J]}],[cr]:[{[cs]:cd,[cr]:[{[cs]:ce,[cr]:[aX,aY,{[cs]:cg,[cr]:[aZ,{[cs]:ch3,[cr]:[ba,{[cs]:cj,[cr]:[{[cs]:bI,[cr]:[{[cs]:ck,[cr]:[{[cs]:cl,[cr]:[{[cs]:[{[ct]:h,[cu]:[bc,""]}],error:"Invalid ARN: Missing account id",[cq]:f},{[cs]:cm,[cr]:[{[cs]:cn,[cr]:[{[cs]:bE,endpoint:{[cx]:M,[cy]:bd,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bd,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bd,[cE]:am},[cq]:n2}],[cq]:o},be],[cq]:o},bf],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},bi],[cq]:o},{error:"Invalid ARN: bucket ARN is missing a region",[cq]:f}],[cq]:o},bj],[cq]:o},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[cq]:f}],[cq]:o},{[cs]:cd,[cr]:[{[cs]:ce,[cr]:[{[cs]:cg,[cr]:[{[cs]:cd,[cr]:[{[cs]:cg,[cr]:[aZ,{[cs]:ch3,[cr]:[ba,{[cs]:cj,[cr]:[{[cs]:bI,[cr]:[{[cs]:[{[ct]:h,[cu]:[bb,"{partitionResult#name}"]}],[cr]:[{[cs]:cl,[cr]:[{[cs]:[{[ct]:h,[cu]:[aV,B]}],[cr]:[{[cs]:cm,[cr]:[{[cs]:cn,[cr]:[{[cs]:bD,error:"Access Points do not support S3 Accelerate",[cq]:f},{[cs]:[X,Y],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[X,aH],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,Y],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,Z,ah],endpoint:{[cx]:M,[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,aH],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2}],[cq]:o},be],[cq]:o},bf],[cq]:o},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[cq]:f}],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},bi],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:y,[cu]:[aW,c]}],[cr]:[{[cs]:bC,error:"S3 MRAP does not support dual-stack",[cq]:f},{[cs]:bJ,error:"S3 MRAP does not support FIPS",[cq]:f},{[cs]:bD,error:"S3 MRAP does not support S3 Accelerate",[cq]:f},{[cs]:[{[ct]:e2,[cu]:[{[cv]:"DisableMultiRegionAccessPoints"},c]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[cq]:f},{[cs]:[{[ct]:g,[cu]:bz,[cw]:N}],[cr]:[{[cs]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[{[cv]:N},j]},{[ct]:i,[cu]:[aT,"partition"]}]}],[cr]:[{endpoint:{[cx]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[cy]:{[cA]:[{[cB]:c,name:z,[cC]:B,[cF]:ca}]},[cE]:am},[cq]:n2}],[cq]:o},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[cq]:f}],[cq]:o}],[cq]:o},{error:"Invalid Access Point Name",[cq]:f}],[cq]:o},bj],[cq]:o},{[cs]:[{[ct]:h,[cu]:[aV,A]}],[cr]:[{[cs]:bC,error:"S3 Outposts does not support Dual-stack",[cq]:f},{[cs]:bJ,error:"S3 Outposts does not support FIPS",[cq]:f},{[cs]:bD,error:"S3 Outposts does not support S3 Accelerate",[cq]:f},{[cs]:[{[ct]:d3,[cu]:[{[ct]:i,[cu]:[aT,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[cq]:f},{[cs]:[{[ct]:i,[cu]:cf,[cw]:x}],[cr]:[{[cs]:bY,[cr]:[ba,{[cs]:cj,[cr]:[{[cs]:bI,[cr]:[{[cs]:ck,[cr]:[{[cs]:cl,[cr]:[{[cs]:cm,[cr]:[{[cs]:[{[ct]:i,[cu]:ci,[cw]:O}],[cr]:[{[cs]:[{[ct]:i,[cu]:[aT,"resourceId[3]"],[cw]:L}],[cr]:[{[cs]:[{[ct]:h,[cu]:[{[cv]:O},K]}],[cr]:[{[cs]:bE,endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[cy]:bl,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bl,[cE]:am},[cq]:n2}],[cq]:o},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[cq]:f}],[cq]:o},{error:"Invalid ARN: expected an access point name",[cq]:f}],[cq]:o},{error:"Invalid ARN: Expected a 4-component resource",[cq]:f}],[cq]:o},bf],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[cq]:f}],[cq]:o},{error:"Invalid ARN: The Outpost Id was not set",[cq]:f}],[cq]:o},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[cq]:f}],[cq]:o},{error:"Invalid ARN: No ARN type specified",[cq]:f}],[cq]:o},{[cs]:[{[ct]:k,[cu]:[ad,0,4,!1],[cw]:P},{[ct]:h,[cu]:[{[cv]:P},"arn:"]},{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[bm]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[cq]:f},{[cs]:[{[ct]:e2,[cu]:[ay,c]},bm],error:"Path-style addressing cannot be used with ARN buckets",[cq]:f},{[cs]:bG,[cr]:[{[cs]:bI,[cr]:[{[cs]:[az],[cr]:[{[cs]:[Y,ar,X,aA],endpoint:{[cx]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,ar,X,aC,aD],[cr]:[{endpoint:bn,[cq]:n2}],[cq]:o},{[cs]:[Y,ar,X,aC,aG],endpoint:bn,[cq]:n2},{[cs]:[aH,ar,X,aA],endpoint:{[cx]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,ar,X,aC,aD],[cr]:[{endpoint:bo,[cq]:n2}],[cq]:o},{[cs]:[aH,ar,X,aC,aG],endpoint:bo,[cq]:n2},{[cs]:[Y,ar,aJ,aA],endpoint:{[cx]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,ar,aJ,aC,aD],[cr]:[{endpoint:bp,[cq]:n2}],[cq]:o},{[cs]:[Y,ar,aJ,aC,aG],endpoint:bp,[cq]:n2},{[cs]:[aH,Z,ah,aJ,aA],endpoint:{[cx]:Q,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,Z,ah,aJ,aC,aD],[cr]:[{[cs]:cc,endpoint:bq,[cq]:n2},{endpoint:bq,[cq]:n2}],[cq]:o},{[cs]:[aH,Z,ah,aJ,aC,aG],endpoint:bq,[cq]:n2},{[cs]:[aH,ar,aJ,aA],endpoint:{[cx]:R,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,ar,aJ,aC,aD],[cr]:[{[cs]:cc,endpoint:{[cx]:R,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:br,[cq]:n2}],[cq]:o},{[cs]:[aH,ar,aJ,aC,aG],endpoint:br,[cq]:n2}],[cq]:o},{error:"Path-style addressing cannot be used with S3 Accelerate",[cq]:f}],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:d3,[cu]:[bs]},{[ct]:e2,[cu]:[bs,c]}],[cr]:[{[cs]:bI,[cr]:[{[cs]:co,[cr]:[aX,aY,{[cs]:bE,endpoint:{[cx]:t2,[cy]:bt,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:bt,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[cy]:bt,[cE]:am},[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[at],[cr]:[{[cs]:bI,[cr]:[{[cs]:co,[cr]:[{[cs]:[X,Y,ar,aA],endpoint:{[cx]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[X,Y,ar,aC,aD],[cr]:[{endpoint:bu,[cq]:n2}],[cq]:o},{[cs]:[X,Y,ar,aC,aG],endpoint:bu,[cq]:n2},{[cs]:[X,aH,ar,aA],endpoint:{[cx]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[X,aH,ar,aC,aD],[cr]:[{endpoint:bv,[cq]:n2}],[cq]:o},{[cs]:[X,aH,ar,aC,aG],endpoint:bv,[cq]:n2},{[cs]:[aJ,Y,ar,aA],endpoint:{[cx]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,Y,ar,aC,aD],[cr]:[{endpoint:bw,[cq]:n2}],[cq]:o},{[cs]:[aJ,Y,ar,aC,aG],endpoint:bw,[cq]:n2},{[cs]:[aJ,aH,Z,ah,aA],endpoint:{[cx]:t2,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,Z,ah,aC,aD],[cr]:[{[cs]:cc,endpoint:bx,[cq]:n2},{endpoint:bx,[cq]:n2}],[cq]:o},{[cs]:[aJ,aH,Z,ah,aC,aG],endpoint:bx,[cq]:n2},{[cs]:[aJ,aH,ar,aA],endpoint:{[cx]:S,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,ar,aC,aD],[cr]:[{[cs]:cc,endpoint:{[cx]:S,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:by,[cq]:n2}],[cq]:o},{[cs]:[aJ,aH,ar,aC,aG],endpoint:by,[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o}],[cq]:o},{error:"A region must be set when sending requests to S3.",[cq]:f}]};cache=new EndpointCache({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]});defaultEndpointResolver=(endpointParams,context2={})=>cache.get(endpointParams,(()=>resolveEndpoint(ruleSet,{endpointParams,logger:context2.logger})));customEndpointFunctions.aws=awsEndpointFunctions;defaultS3HttpAuthSchemeParametersProvider=async(config,context2,input)=>{var _a8,_b4,_c3;if(!input)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");const defaultParameters=await(async(config,context2)=>({operation:getSmithyContext2(context2).operation,region:await normalizeProvider(config.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()}))(config,context2),instructionsFn=null==(_c3=null==(_b4=null==(_a8=getSmithyContext2(context2))?void 0:_a8.commandInstance)?void 0:_b4.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)};defaultS3HttpAuthSchemeProvider=(defaultEndpointResolver2=defaultEndpointResolver,createHttpAuthOptionFunctions={"aws.auth#sigv4":createAwsAuthSigv4HttpAuthOption,"aws.auth#sigv4a":createAwsAuthSigv4aHttpAuthOption},authParameters=>{var _a8;const authSchemes=null==(_a8=defaultEndpointResolver2(authParameters).properties)?void 0:_a8.authSchemes;if(!authSchemes)return(authParameters=>{const options=[];switch(authParameters.operation){default:options.push(createAwsAuthSigv4HttpAuthOption(authParameters));options.push(createAwsAuthSigv4aHttpAuthOption(authParameters))}return options})(authParameters);const options=[];for(const scheme of authSchemes){const{name:resolvedName,properties={},...rest}=scheme,name=resolvedName.toLowerCase();resolvedName!==name&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${resolvedName}\` to \`${name}\``);let schemeId;if("sigv4a"===name){schemeId="aws.auth#sigv4a";if(authSchemes.find((s2=>{const name2=s2.name.toLowerCase();return"sigv4a"!==name2&&name2.startsWith("sigv4")})))continue}else{if(!name.startsWith("sigv4"))throw new Error(`Unknown HttpAuthScheme found in \`@smithy.rules#endpointRuleSet\`: \`${name}\``);schemeId="aws.auth#sigv4"}const createOption=createHttpAuthOptionFunctions[schemeId];if(!createOption)throw new Error(`Could not find HttpAuthOption create function for \`${schemeId}\``);const option=createOption(authParameters);option.schemeId=schemeId;option.signingProperties={...option.signingProperties||{},...rest,...properties};options.push(option)}return options});resolveHttpAuthSchemeConfig=config=>{var _a8;const config_0=resolveAwsSdkSigV4Config(config),config_1=resolveAwsSdkSigV4AConfig(config_0);return Object.assign(config_1,{authSchemePreference:normalizeProvider(null!=(_a8=config.authSchemePreference)?_a8:[])})};resolveClientEndpointParameters=options=>{var _a8,_b4,_c3,_d2,_e2,_f;return Object.assign(options,{useFipsEndpoint:null!=(_a8=options.useFipsEndpoint)&&_a8,useDualstackEndpoint:null!=(_b4=options.useDualstackEndpoint)&&_b4,forcePathStyle:null!=(_c3=options.forcePathStyle)&&_c3,useAccelerateEndpoint:null!=(_d2=options.useAccelerateEndpoint)&&_d2,useGlobalEndpoint:null!=(_e2=options.useGlobalEndpoint)&&_e2,disableMultiregionAccessPoints:null!=(_f=options.disableMultiregionAccessPoints)&&_f,defaultSigningName:"s3"})};commonParams={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};S3ServiceException=class _S3ServiceException extends ServiceException{constructor(options){super(options);Object.setPrototypeOf(this,_S3ServiceException.prototype)}};NoSuchUpload=class _NoSuchUpload extends S3ServiceException{constructor(opts){super({name:"NoSuchUpload",$fault:"client",...opts});__publicField(this,"name","NoSuchUpload");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchUpload.prototype)}};ObjectNotInActiveTierError=class _ObjectNotInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectNotInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectNotInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectNotInActiveTierError.prototype)}};BucketAlreadyExists=class _BucketAlreadyExists extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyExists",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyExists");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyExists.prototype)}};BucketAlreadyOwnedByYou=class _BucketAlreadyOwnedByYou extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyOwnedByYou");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyOwnedByYou.prototype)}};NoSuchBucket=class _NoSuchBucket extends S3ServiceException{constructor(opts){super({name:"NoSuchBucket",$fault:"client",...opts});__publicField(this,"name","NoSuchBucket");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchBucket.prototype)}};(AnalyticsFilter||(AnalyticsFilter={})).visit=(value,visitor)=>void 0!==value.Prefix?visitor.Prefix(value.Prefix):void 0!==value.Tag?visitor.Tag(value.Tag):void 0!==value.And?visitor.And(value.And):visitor._(value.$unknown[0],value.$unknown[1]);(MetricsFilter||(MetricsFilter={})).visit=(value,visitor)=>void 0!==value.Prefix?visitor.Prefix(value.Prefix):void 0!==value.Tag?visitor.Tag(value.Tag):void 0!==value.AccessPointArn?visitor.AccessPointArn(value.AccessPointArn):void 0!==value.And?visitor.And(value.And):visitor._(value.$unknown[0],value.$unknown[1]);InvalidObjectState=class _InvalidObjectState extends S3ServiceException{constructor(opts){super({name:"InvalidObjectState",$fault:"client",...opts});__publicField(this,"name","InvalidObjectState");__publicField(this,"$fault","client");__publicField(this,"StorageClass");__publicField(this,"AccessTier");Object.setPrototypeOf(this,_InvalidObjectState.prototype);this.StorageClass=opts.StorageClass;this.AccessTier=opts.AccessTier}};NoSuchKey=class _NoSuchKey extends S3ServiceException{constructor(opts){super({name:"NoSuchKey",$fault:"client",...opts});__publicField(this,"name","NoSuchKey");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchKey.prototype)}};NotFound=class _NotFound extends S3ServiceException{constructor(opts){super({name:"NotFound",$fault:"client",...opts});__publicField(this,"name","NotFound");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NotFound.prototype)}};CompleteMultipartUploadOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});CompleteMultipartUploadRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});CopyObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});CopyObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING},...obj.CopySourceSSECustomerKey&&{CopySourceSSECustomerKey:SENSITIVE_STRING}});CreateMultipartUploadOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});CreateMultipartUploadRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});SessionCredentialsFilterSensitiveLog=obj=>({...obj,...obj.SecretAccessKey&&{SecretAccessKey:SENSITIVE_STRING},...obj.SessionToken&&{SessionToken:SENSITIVE_STRING}});CreateSessionOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING},...obj.Credentials&&{Credentials:SessionCredentialsFilterSensitiveLog(obj.Credentials)}});CreateSessionRequestFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});ServerSideEncryptionByDefaultFilterSensitiveLog=obj=>({...obj,...obj.KMSMasterKeyID&&{KMSMasterKeyID:SENSITIVE_STRING}});ServerSideEncryptionRuleFilterSensitiveLog=obj=>({...obj,...obj.ApplyServerSideEncryptionByDefault&&{ApplyServerSideEncryptionByDefault:ServerSideEncryptionByDefaultFilterSensitiveLog(obj.ApplyServerSideEncryptionByDefault)}});ServerSideEncryptionConfigurationFilterSensitiveLog=obj=>({...obj,...obj.Rules&&{Rules:obj.Rules.map((item=>ServerSideEncryptionRuleFilterSensitiveLog(item)))}});GetBucketEncryptionOutputFilterSensitiveLog=obj=>({...obj,...obj.ServerSideEncryptionConfiguration&&{ServerSideEncryptionConfiguration:ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)}});SSEKMSFilterSensitiveLog=obj=>({...obj,...obj.KeyId&&{KeyId:SENSITIVE_STRING}});InventoryEncryptionFilterSensitiveLog=obj=>({...obj,...obj.SSEKMS&&{SSEKMS:SSEKMSFilterSensitiveLog(obj.SSEKMS)}});InventoryS3BucketDestinationFilterSensitiveLog=obj=>({...obj,...obj.Encryption&&{Encryption:InventoryEncryptionFilterSensitiveLog(obj.Encryption)}});InventoryDestinationFilterSensitiveLog=obj=>({...obj,...obj.S3BucketDestination&&{S3BucketDestination:InventoryS3BucketDestinationFilterSensitiveLog(obj.S3BucketDestination)}});InventoryConfigurationFilterSensitiveLog=obj=>({...obj,...obj.Destination&&{Destination:InventoryDestinationFilterSensitiveLog(obj.Destination)}});GetBucketInventoryConfigurationOutputFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfiguration&&{InventoryConfiguration:InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)}});GetObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});GetObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});GetObjectAttributesRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});GetObjectTorrentOutputFilterSensitiveLog=obj=>({...obj});HeadObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});HeadObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});ListBucketInventoryConfigurationsOutputFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfigurationList&&{InventoryConfigurationList:obj.InventoryConfigurationList.map((item=>InventoryConfigurationFilterSensitiveLog(item)))}});ListPartsRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});XmlText=class{constructor(value){__publicField(this,"value");this.value=value}toString(){return function escapeElement(value){return value.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(//g,">").replace(/\r/g," ").replace(/\n/g," ").replace(/\u0085/g,"…").replace(/\u2028/,"
")}(""+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}="${value=""+attribute,value.replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}"`)}var value;return xmlText+(hasChildren?`>${this.children.map((c3=>c3.toString())).join("")}`:"/>")}};EncryptionTypeMismatch=class _EncryptionTypeMismatch extends S3ServiceException{constructor(opts){super({name:"EncryptionTypeMismatch",$fault:"client",...opts});__publicField(this,"name","EncryptionTypeMismatch");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_EncryptionTypeMismatch.prototype)}};InvalidRequest=class _InvalidRequest extends S3ServiceException{constructor(opts){super({name:"InvalidRequest",$fault:"client",...opts});__publicField(this,"name","InvalidRequest");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidRequest.prototype)}};InvalidWriteOffset=class _InvalidWriteOffset extends S3ServiceException{constructor(opts){super({name:"InvalidWriteOffset",$fault:"client",...opts});__publicField(this,"name","InvalidWriteOffset");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidWriteOffset.prototype)}};TooManyParts=class _TooManyParts extends S3ServiceException{constructor(opts){super({name:"TooManyParts",$fault:"client",...opts});__publicField(this,"name","TooManyParts");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_TooManyParts.prototype)}};ObjectAlreadyInActiveTierError=class _ObjectAlreadyInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectAlreadyInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectAlreadyInActiveTierError.prototype)}};(SelectObjectContentEventStream||(SelectObjectContentEventStream={})).visit=(value,visitor)=>void 0!==value.Records?visitor.Records(value.Records):void 0!==value.Stats?visitor.Stats(value.Stats):void 0!==value.Progress?visitor.Progress(value.Progress):void 0!==value.Cont?visitor.Cont(value.Cont):void 0!==value.End?visitor.End(value.End):visitor._(value.$unknown[0],value.$unknown[1]);PutBucketEncryptionRequestFilterSensitiveLog=obj=>({...obj,...obj.ServerSideEncryptionConfiguration&&{ServerSideEncryptionConfiguration:ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)}});PutBucketInventoryConfigurationRequestFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfiguration&&{InventoryConfiguration:InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)}});PutObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});PutObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});EncryptionFilterSensitiveLog=obj=>({...obj,...obj.KMSKeyId&&{KMSKeyId:SENSITIVE_STRING}});S3LocationFilterSensitiveLog=obj=>({...obj,...obj.Encryption&&{Encryption:EncryptionFilterSensitiveLog(obj.Encryption)}});OutputLocationFilterSensitiveLog=obj=>({...obj,...obj.S3&&{S3:S3LocationFilterSensitiveLog(obj.S3)}});RestoreRequestFilterSensitiveLog=obj=>({...obj,...obj.OutputLocation&&{OutputLocation:OutputLocationFilterSensitiveLog(obj.OutputLocation)}});RestoreObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.RestoreRequest&&{RestoreRequest:RestoreRequestFilterSensitiveLog(obj.RestoreRequest)}});SelectObjectContentOutputFilterSensitiveLog=obj=>({...obj,...obj.Payload&&{Payload:"STREAMING_CONTENT"}});SelectObjectContentRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});UploadPartOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});UploadPartRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});UploadPartCopyOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});UploadPartCopyRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.CopySourceSSECustomerKey&&{CopySourceSSECustomerKey:SENSITIVE_STRING}});WriteGetObjectResponseRequestFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});se_AbortMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaimit]:[()=>isSerializableHeaderValue(input[_IMIT]),()=>dateToUtcString(input[_IMIT]).toString()]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"AbortMultipartUpload"],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_CompleteMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_xact]:input[_CT],[_xamos]:[()=>isSerializableHeaderValue(input[_MOS]),()=>input[_MOS].toString()],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_im]:input[_IM],[_inm]:input[_INM],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_uI]:[,expectNonNull(input[_UI],"UploadId")]});let body,contents;if(void 0!==input.MultipartUpload){contents=se_CompletedMultipartUpload(input.MultipartUpload,context2);contents=contents.n("CompleteMultipartUpload");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_CopyObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_xaa]:input[_ACL],[_cc]:input[_CC],[_xaca]:input[_CA],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_ct]:input[_CTo],[_xacs__]:input[_CS],[_xacsim]:input[_CSIM],[_xacsims]:[()=>isSerializableHeaderValue(input[_CSIMS]),()=>dateToUtcString(input[_CSIMS]).toString()],[_xacsinm]:input[_CSINM],[_xacsius]:[()=>isSerializableHeaderValue(input[_CSIUS]),()=>dateToUtcString(input[_CSIUS]).toString()],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xamd]:input[_MD],[_xatd]:input[_TD],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xacssseca]:input[_CSSSECA],[_xacssseck]:input[_CSSSECK],[_xacssseckm]:input[_CSSSECKMD],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO],[_xasebo]:input[_ESBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"CopyObject"]});b3.m("PUT").h(headers).q(query3).b(void 0);return b3.build()};se_CreateBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xabole]:[()=>isSerializableHeaderValue(input[_OLEFB]),()=>input[_OLEFB].toString()],[_xaoo]:input[_OO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);let body,contents;if(void 0!==input.CreateBucketConfiguration){contents=se_CreateBucketConfiguration(input.CreateBucketConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).b(body);return b3.build()};se_CreateBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});let body,contents;if(void 0!==input.MetadataTableConfiguration){contents=se_MetadataTableConfiguration(input.MetadataTableConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_CreateMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_xaa]:input[_ACL],[_cc]:input[_CC],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_ct]:input[_CTo],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO],[_xaca]:input[_CA],[_xact]:input[_CT]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_u]:[,""]});b3.m("POST").h(headers).q(query3).b(void 0);return b3.build()};se_CreateSessionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xacsm]:input[_SM],[_xasse]:input[_SSE],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_s]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.m("DELETE").h(headers).b(void 0);return b3.build()};se_DeleteBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a6]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h({}).q(query3).b(void 0);return b3.build()};se_DeleteBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketLifecycleCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xam]:input[_MFA],[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_xaebo]:input[_EBO],[_im]:input[_IM],[_xaimlmt]:[()=>isSerializableHeaderValue(input[_IMLMT]),()=>dateToUtcString(input[_IMLMT]).toString()],[_xaims]:[()=>isSerializableHeaderValue(input[_IMS]),()=>input[_IMS].toString()]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"DeleteObject"],[_vI]:[,input[_VI]]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteObjectsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xam]:input[_MFA],[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_xaebo]:input[_EBO],[_xasca]:input[_CA]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_d]:[,""]});let body,contents;if(void 0!==input.Delete){contents=se_Delete(input.Delete,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_DeleteObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeletePublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAccelerateConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ac]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_acl]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a6]:[,""],[_xi]:[,"GetBucketAnalyticsConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_xi]:[,"GetBucketIntelligentTieringConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_GetBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_xi]:[,"GetBucketInventoryConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLifecycleConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLocationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_lo]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLoggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_log]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_xi]:[,"GetBucketMetricsConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketNotificationConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_n]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketPolicyStatusCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pS]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketRequestPaymentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_rP]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketVersioningCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_v]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_im]:input[_IM],[_ims]:[()=>isSerializableHeaderValue(input[_IMSf]),()=>dateToUtcString(input[_IMSf]).toString()],[_inm]:input[_INM],[_ius]:[()=>isSerializableHeaderValue(input[_IUS]),()=>dateToUtcString(input[_IUS]).toString()],[_ra]:input[_R],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xacm]:input[_CM]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"GetObject"],[_rcc]:[,input[_RCC]],[_rcd]:[,input[_RCD]],[_rce]:[,input[_RCE]],[_rcl]:[,input[_RCL]],[_rct]:[,input[_RCT]],[_re]:[()=>void 0!==input.ResponseExpires,()=>dateToUtcString(input[_RE]).toString()],[_vI]:[,input[_VI]],[_pN]:[()=>void 0!==input.PartNumber,()=>input[_PN].toString()]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_acl]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectAttributesCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xamp]:[()=>isSerializableHeaderValue(input[_MP]),()=>input[_MP].toString()],[_xapnm]:input[_PNM],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaoa]:[()=>isSerializableHeaderValue(input[_OA]),()=>(input[_OA]||[]).map(quoteHeader).join(", ")]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_at]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectLegalHoldCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_lh]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectLockConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ol]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectRetentionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_ret]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectTorrentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_to]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetPublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_HeadBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.m("HEAD").h(headers).b(void 0);return b3.build()};se_HeadObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_im]:input[_IM],[_ims]:[()=>isSerializableHeaderValue(input[_IMSf]),()=>dateToUtcString(input[_IMSf]).toString()],[_inm]:input[_INM],[_ius]:[()=>isSerializableHeaderValue(input[_IUS]),()=>dateToUtcString(input[_IUS]).toString()],[_ra]:input[_R],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xacm]:input[_CM]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_rcc]:[,input[_RCC]],[_rcd]:[,input[_RCD]],[_rce]:[,input[_RCE]],[_rcl]:[,input[_RCL]],[_rct]:[,input[_RCT]],[_re]:[()=>void 0!==input.ResponseExpires,()=>dateToUtcString(input[_RE]).toString()],[_vI]:[,input[_VI]],[_pN]:[()=>void 0!==input.PartNumber,()=>input[_PN].toString()]});b3.m("HEAD").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketAnalyticsConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a6]:[,""],[_xi]:[,"ListBucketAnalyticsConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketIntelligentTieringConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_xi]:[,"ListBucketIntelligentTieringConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListBucketInventoryConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_xi]:[,"ListBucketInventoryConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketMetricsConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_xi]:[,"ListBucketMetricsConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");const query3=map2({[_xi]:[,"ListBuckets"],[_mb]:[()=>void 0!==input.MaxBuckets,()=>input[_MB].toString()],[_ct_]:[,input[_CTon]],[_pr]:[,input[_P]],[_br]:[,input[_BR]]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListDirectoryBucketsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");const query3=map2({[_xi]:[,"ListDirectoryBuckets"],[_ct_]:[,input[_CTon]],[_mdb]:[()=>void 0!==input.MaxDirectoryBuckets,()=>input[_MDB].toString()]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListMultipartUploadsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_u]:[,""],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_km]:[,input[_KM]],[_mu]:[()=>void 0!==input.MaxUploads,()=>input[_MU].toString()],[_pr]:[,input[_P]],[_uim]:[,input[_UIM]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_de]:[,input[_D]],[_et]:[,input[_ET]],[_ma]:[,input[_M]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectsV2Command=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_lt]:[,"2"],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]],[_ct_]:[,input[_CTon]],[_fo]:[()=>void 0!==input.FetchOwner,()=>input[_FO].toString()],[_sa]:[,input[_SA]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectVersionsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ver]:[,""],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_km]:[,input[_KM]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]],[_vim]:[,input[_VIM]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListPartsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"ListParts"],[_mp]:[()=>void 0!==input.MaxParts,()=>input[_MP].toString()],[_pnm]:[,input[_PNM]],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_PutBucketAccelerateConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO],[_xasca]:input[_CA]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ac]:[,""]});let body,contents;if(void 0!==input.AccelerateConfiguration){contents=se_AccelerateConfiguration(input.AccelerateConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_acl]:[,""]});let body,contents;if(void 0!==input.AccessControlPolicy){contents=se_AccessControlPolicy(input.AccessControlPolicy,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a6]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.AnalyticsConfiguration){contents=se_AnalyticsConfiguration(input.AnalyticsConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});let body,contents;if(void 0!==input.CORSConfiguration){contents=se_CORSConfiguration(input.CORSConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});let body,contents;if(void 0!==input.ServerSideEncryptionConfiguration){contents=se_ServerSideEncryptionConfiguration(input.ServerSideEncryptionConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.IntelligentTieringConfiguration){contents=se_IntelligentTieringConfiguration(input.IntelligentTieringConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h({"content-type":"application/xml"}).q(query3).b(body);return b3.build()};se_PutBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.InventoryConfiguration){contents=se_InventoryConfiguration(input.InventoryConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketLifecycleConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xasca]:input[_CA],[_xaebo]:input[_EBO],[_xatdmos]:input[_TDMOS]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});let body,contents;if(void 0!==input.LifecycleConfiguration){contents=se_BucketLifecycleConfiguration(input.LifecycleConfiguration,context2);contents=contents.n("LifecycleConfiguration");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketLoggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_log]:[,""]});let body,contents;if(void 0!==input.BucketLoggingStatus){contents=se_BucketLoggingStatus(input.BucketLoggingStatus,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.MetricsConfiguration){contents=se_MetricsConfiguration(input.MetricsConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketNotificationConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO],[_xasdv]:[()=>isSerializableHeaderValue(input[_SDV]),()=>input[_SDV].toString()]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_n]:[,""]});let body,contents;if(void 0!==input.NotificationConfiguration){contents=se_NotificationConfiguration(input.NotificationConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});let body,contents;if(void 0!==input.OwnershipControls){contents=se_OwnershipControls(input.OwnershipControls,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"text/plain",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacrsba]:[()=>isSerializableHeaderValue(input[_CRSBA]),()=>input[_CRSBA].toString()],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});let body,contents;if(void 0!==input.Policy){contents=input.Policy;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xabolt]:input[_To],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});let body,contents;if(void 0!==input.ReplicationConfiguration){contents=se_ReplicationConfiguration(input.ReplicationConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketRequestPaymentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_rP]:[,""]});let body,contents;if(void 0!==input.RequestPaymentConfiguration){contents=se_RequestPaymentConfiguration(input.RequestPaymentConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});let body,contents;if(void 0!==input.Tagging){contents=se_Tagging(input.Tagging,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketVersioningCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xam]:input[_MFA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_v]:[,""]});let body,contents;if(void 0!==input.VersioningConfiguration){contents=se_VersioningConfiguration(input.VersioningConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});let body,contents;if(void 0!==input.WebsiteConfiguration){contents=se_WebsiteConfiguration(input.WebsiteConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_ct]:input[_CTo]||"application/octet-stream",[_xaa]:input[_ACL],[_cc]:input[_CC],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_im]:input[_IM],[_inm]:input[_INM],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xawob]:[()=>isSerializableHeaderValue(input[_WOB]),()=>input[_WOB].toString()],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"PutObject"]});let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_acl]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.AccessControlPolicy){contents=se_AccessControlPolicy(input.AccessControlPolicy,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectLegalHoldCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_lh]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.LegalHold){contents=se_ObjectLockLegalHold(input.LegalHold,context2);contents=contents.n("LegalHold");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectLockConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xabolt]:input[_To],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ol]:[,""]});let body,contents;if(void 0!==input.ObjectLockConfiguration){contents=se_ObjectLockConfiguration(input.ObjectLockConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectRetentionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_ret]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.Retention){contents=se_ObjectLockRetention(input.Retention,context2);contents=contents.n("Retention");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.Tagging){contents=se_Tagging(input.Tagging,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutPublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});let body,contents;if(void 0!==input.PublicAccessBlockConfiguration){contents=se_PublicAccessBlockConfiguration(input.PublicAccessBlockConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_RestoreObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_res]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.RestoreRequest){contents=se_RestoreRequest(input.RestoreRequest,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_SelectObjectContentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_se]:[,""],[_st]:[,"2"]});let body;body=_ve;const bn2=new XmlNode(_SOCR);bn2.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");bn2.cc(input,_Ex);bn2.cc(input,_ETx);null!=input[_IS]&&bn2.c(se_InputSerialization(input[_IS],context2).n(_IS));null!=input[_OS]&&bn2.c(se_OutputSerialization(input[_OS],context2).n(_OS));null!=input[_RPe]&&bn2.c(se_RequestProgress(input[_RPe],context2).n(_RPe));null!=input[_SR]&&bn2.c(se_ScanRange(input[_SR],context2).n(_SR));body+=bn2.toString();b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_UploadPartCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/octet-stream",[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"UploadPart"],[_pN]:[null!=expectNonNull(input.PartNumber,"PartNumber"),()=>input[_PN].toString()],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_UploadPartCopyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xacs__]:input[_CS],[_xacsim]:input[_CSIM],[_xacsims]:[()=>isSerializableHeaderValue(input[_CSIMS]),()=>dateToUtcString(input[_CSIMS]).toString()],[_xacsinm]:input[_CSINM],[_xacsius]:[()=>isSerializableHeaderValue(input[_CSIUS]),()=>dateToUtcString(input[_CSIUS]).toString()],[_xacsr]:input[_CSR],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xacssseca]:input[_CSSSECA],[_xacssseck]:input[_CSSSECK],[_xacssseckm]:input[_CSSSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xasebo]:input[_ESBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"UploadPartCopy"],[_pN]:[null!=expectNonNull(input.PartNumber,"PartNumber"),()=>input[_PN].toString()],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("PUT").h(headers).q(query3).b(void 0);return b3.build()};se_WriteGetObjectResponseCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"x-amz-content-sha256":"UNSIGNED-PAYLOAD",...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),"content-type":"application/octet-stream",[_xarr]:input[_RR],[_xart]:input[_RT],[_xafs]:[()=>isSerializableHeaderValue(input[_SCt]),()=>input[_SCt].toString()],[_xafec]:input[_EC],[_xafem]:input[_EM],[_xafhar]:input[_AR],[_xafhcc]:input[_CC],[_xafhcd]:input[_CD],[_xafhce]:input[_CE],[_xafhcl]:input[_CL],[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_xafhcr]:input[_CR],[_xafhct]:input[_CTo],[_xafhxacc]:input[_CCRC],[_xafhxacc_]:input[_CCRCC],[_xafhxacc__]:input[_CCRCNVME],[_xafhxacs]:input[_CSHA],[_xafhxacs_]:input[_CSHAh],[_xafhxadm]:[()=>isSerializableHeaderValue(input[_DM]),()=>input[_DM].toString()],[_xafhe]:input[_ETa],[_xafhe_]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xafhxae]:input[_Exp],[_xafhlm]:[()=>isSerializableHeaderValue(input[_LM]),()=>dateToUtcString(input[_LM]).toString()],[_xafhxamm]:[()=>isSerializableHeaderValue(input[_MM]),()=>input[_MM].toString()],[_xafhxaolm]:input[_OLM],[_xafhxaollh]:input[_OLLHS],[_xafhxaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xafhxampc]:[()=>isSerializableHeaderValue(input[_PC]),()=>input[_PC].toString()],[_xafhxars]:input[_RS],[_xafhxarc]:input[_RC],[_xafhxar]:input[_Re],[_xafhxasse]:input[_SSE],[_xafhxasseca]:input[_SSECA],[_xafhxasseakki]:input[_SSEKMSKI],[_xafhxasseckm]:input[_SSECKMD],[_xafhxasc]:input[_SC],[_xafhxatc]:[()=>isSerializableHeaderValue(input[_TC]),()=>input[_TC].toString()],[_xafhxavi]:input[_VI],[_xafhxassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()]});b3.bp("/WriteGetObjectResponse");let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}let{hostname:resolvedHostname}=await context2.endpoint();if(!0!==context2.disableHostPrefix){resolvedHostname="{RequestRoute}."+resolvedHostname;if(void 0===input.RequestRoute)throw new Error("Empty value provided for input host prefix: RequestRoute.");resolvedHostname=resolvedHostname.replace("{RequestRoute}",input.RequestRoute);if(!function isValidHostname(hostname){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(hostname)}(resolvedHostname))throw new Error("ValidationError: prefixed hostname must be hostname compatible.")}b3.hn(resolvedHostname);b3.m("POST").h(headers).b(body);return b3.build()};de_AbortMultipartUploadCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_CompleteMultipartUploadCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_SSE]:[,output.headers[_xasse]],[_VI]:[,output.headers[_xavi]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_CCRC]&&(contents[_CCRC]=expectString(data[_CCRC]));null!=data[_CCRCC]&&(contents[_CCRCC]=expectString(data[_CCRCC]));null!=data[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(data[_CCRCNVME]));null!=data[_CSHA]&&(contents[_CSHA]=expectString(data[_CSHA]));null!=data[_CSHAh]&&(contents[_CSHAh]=expectString(data[_CSHAh]));null!=data[_CT]&&(contents[_CT]=expectString(data[_CT]));null!=data[_ETa]&&(contents[_ETa]=expectString(data[_ETa]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_L]&&(contents[_L]=expectString(data[_L]));return contents};de_CopyObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_CSVI]:[,output.headers[_xacsvi]],[_VI]:[,output.headers[_xavi]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectObject(await parseXmlBody(output.body,context2));contents.CopyObjectResult=de_CopyObjectResult(data,context2);return contents};de_CreateBucketCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_L]:[,output.headers[_lo]]});await collectBody(output.body,context2);return contents};de_CreateBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_CreateMultipartUploadCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_AD]:[()=>void 0!==output.headers[_xaad],()=>expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))],[_ARI]:[,output.headers[_xaari]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]],[_CA]:[,output.headers[_xaca]],[_CT]:[,output.headers[_xact]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_UI]&&(contents[_UI]=expectString(data[_UI]));return contents};de_CreateSessionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_SSE]:[,output.headers[_xasse]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_C]&&(contents[_C]=de_SessionCredentials(data[_C],context2));return contents};de_DeleteBucketCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketCorsCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketEncryptionCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketInventoryConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketLifecycleCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketMetricsConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketOwnershipControlsCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketPolicyCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketReplicationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketTaggingCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketWebsiteCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteObjectCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_VI]:[,output.headers[_xavi]],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_DeleteObjectsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Deleted?contents[_De]=[]:null!=data[_De]&&(contents[_De]=de_DeletedObjects(getArrayIfSingleItem(data[_De]),context2));""===data.Error?contents[_Err]=[]:null!=data[_Er]&&(contents[_Err]=de_Errors(getArrayIfSingleItem(data[_Er]),context2));return contents};de_DeleteObjectTaggingCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]});await collectBody(output.body,context2);return contents};de_DeletePublicAccessBlockCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_GetBucketAccelerateConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_S]&&(contents[_S]=expectString(data[_S]));return contents};de_GetBucketAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AccessControlList?contents[_Gr]=[]:null!=data[_ACLc]&&null!=data[_ACLc][_G]&&(contents[_Gr]=de_Grants(getArrayIfSingleItem(data[_ACLc][_G]),context2));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));return contents};de_GetBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.AnalyticsConfiguration=de_AnalyticsConfiguration(data,context2);return contents};de_GetBucketCorsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CORSRule?contents[_CORSRu]=[]:null!=data[_CORSR]&&(contents[_CORSRu]=de_CORSRules(getArrayIfSingleItem(data[_CORSR]),context2));return contents};de_GetBucketEncryptionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ServerSideEncryptionConfiguration=de_ServerSideEncryptionConfiguration(data,context2);return contents};de_GetBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.IntelligentTieringConfiguration=de_IntelligentTieringConfiguration(data,context2);return contents};de_GetBucketInventoryConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.InventoryConfiguration=de_InventoryConfiguration(data,context2);return contents};de_GetBucketLifecycleConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_TDMOS]:[,output.headers[_xatdmos]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Rule?contents[_Rul]=[]:null!=data[_Ru]&&(contents[_Rul]=de_LifecycleRules(getArrayIfSingleItem(data[_Ru]),context2));return contents};de_GetBucketLocationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_LC]&&(contents[_LC]=expectString(data[_LC]));return contents};de_GetBucketLoggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_LE]&&(contents[_LE]=de_LoggingEnabled(data[_LE],context2));return contents};de_GetBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.GetBucketMetadataTableConfigurationResult=de_GetBucketMetadataTableConfigurationResult(data,context2);return contents};de_GetBucketMetricsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.MetricsConfiguration=de_MetricsConfiguration(data,context2);return contents};de_GetBucketNotificationConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_EBC]&&(contents[_EBC]=de_EventBridgeConfiguration(data[_EBC],context2));""===data.CloudFunctionConfiguration?contents[_LFC]=[]:null!=data[_CFC]&&(contents[_LFC]=de_LambdaFunctionConfigurationList(getArrayIfSingleItem(data[_CFC]),context2));""===data.QueueConfiguration?contents[_QCu]=[]:null!=data[_QC]&&(contents[_QCu]=de_QueueConfigurationList(getArrayIfSingleItem(data[_QC]),context2));""===data.TopicConfiguration?contents[_TCop]=[]:null!=data[_TCo]&&(contents[_TCop]=de_TopicConfigurationList(getArrayIfSingleItem(data[_TCo]),context2));return contents};de_GetBucketOwnershipControlsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.OwnershipControls=de_OwnershipControls(data,context2);return contents};de_GetBucketPolicyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=await collectBodyString2(output.body,context2);contents.Policy=expectString(data);return contents};de_GetBucketPolicyStatusCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.PolicyStatus=de_PolicyStatus(data,context2);return contents};de_GetBucketReplicationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ReplicationConfiguration=de_ReplicationConfiguration(data,context2);return contents};de_GetBucketRequestPaymentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_Pa]&&(contents[_Pa]=expectString(data[_Pa]));return contents};de_GetBucketTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.TagSet?contents[_TS]=[]:null!=data[_TS]&&null!=data[_TS][_Ta]&&(contents[_TS]=de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]),context2));return contents};de_GetBucketVersioningCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_MDf]&&(contents[_MFAD]=expectString(data[_MDf]));null!=data[_S]&&(contents[_S]=expectString(data[_S]));return contents};de_GetBucketWebsiteCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_ED]&&(contents[_ED]=de_ErrorDocument(data[_ED],context2));null!=data[_ID]&&(contents[_ID]=de_IndexDocument(data[_ID],context2));null!=data[_RART]&&(contents[_RART]=de_RedirectAllRequestsTo(data[_RART],context2));""===data.RoutingRules?contents[_RRo]=[]:null!=data[_RRo]&&null!=data[_RRo][_RRou]&&(contents[_RRo]=de_RoutingRules(getArrayIfSingleItem(data[_RRo][_RRou]),context2));return contents};de_GetObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_AR]:[,output.headers[_ar]],[_Exp]:[,output.headers[_xae]],[_Re]:[,output.headers[_xar]],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_CLo]:[()=>void 0!==output.headers[_cl_],()=>strictParseLong(output.headers[_cl_])],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_MM]:[()=>void 0!==output.headers[_xamm],()=>strictParseInt32(output.headers[_xamm])],[_VI]:[,output.headers[_xavi]],[_CC]:[,output.headers[_cc]],[_CD]:[,output.headers[_cd]],[_CE]:[,output.headers[_ce]],[_CL]:[,output.headers[_cl]],[_CR]:[,output.headers[_cr]],[_CTo]:[,output.headers[_ct]],[_E]:[()=>void 0!==output.headers[_e],()=>expectNonNull(parseRfc7231DateTime(output.headers[_e]))],[_ES]:[,output.headers[_ex]],[_WRL]:[,output.headers[_xawrl]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_SC]:[,output.headers[_xasc]],[_RC]:[,output.headers[_xarc]],[_RS]:[,output.headers[_xars]],[_PC]:[()=>void 0!==output.headers[_xampc],()=>strictParseInt32(output.headers[_xampc])],[_TC]:[()=>void 0!==output.headers[_xatc],()=>strictParseInt32(output.headers[_xatc])],[_OLM]:[,output.headers[_xaolm]],[_OLRUD]:[()=>void 0!==output.headers[_xaolrud],()=>expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))],[_OLLHS]:[,output.headers[_xaollh]],Metadata:[,Object.keys(output.headers).filter((header=>header.startsWith("x-amz-meta-"))).reduce(((acc,header)=>{acc[header.substring(11)]=output.headers[header];return acc}),{})]}),data=output.body;context2.sdkStreamMixin(data);contents.Body=data;return contents};de_GetObjectAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AccessControlList?contents[_Gr]=[]:null!=data[_ACLc]&&null!=data[_ACLc][_G]&&(contents[_Gr]=de_Grants(getArrayIfSingleItem(data[_ACLc][_G]),context2));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));return contents};de_GetObjectAttributesCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_VI]:[,output.headers[_xavi]],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_Ch]&&(contents[_Ch]=de_Checksum(data[_Ch],context2));null!=data[_ETa]&&(contents[_ETa]=expectString(data[_ETa]));null!=data[_OP]&&(contents[_OP]=de_GetObjectAttributesParts(data[_OP],context2));null!=data[_OSb]&&(contents[_OSb]=strictParseLong(data[_OSb]));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));return contents};de_GetObjectLegalHoldCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.LegalHold=de_ObjectLockLegalHold(data,context2);return contents};de_GetObjectLockConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ObjectLockConfiguration=de_ObjectLockConfiguration(data,context2);return contents};de_GetObjectRetentionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.Retention=de_ObjectLockRetention(data,context2);return contents};de_GetObjectTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.TagSet?contents[_TS]=[]:null!=data[_TS]&&null!=data[_TS][_Ta]&&(contents[_TS]=de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]),context2));return contents};de_GetObjectTorrentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=output.body;context2.sdkStreamMixin(data);contents.Body=data;return contents};de_GetPublicAccessBlockCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.PublicAccessBlockConfiguration=de_PublicAccessBlockConfiguration(data,context2);return contents};de_HeadBucketCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_BLT]:[,output.headers[_xablt]],[_BLN]:[,output.headers[_xabln]],[_BR]:[,output.headers[_xabr]],[_APA]:[()=>void 0!==output.headers[_xaapa],()=>parseBoolean(output.headers[_xaapa])]});await collectBody(output.body,context2);return contents};de_HeadObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_AR]:[,output.headers[_ar]],[_Exp]:[,output.headers[_xae]],[_Re]:[,output.headers[_xar]],[_AS]:[,output.headers[_xaas]],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_CLo]:[()=>void 0!==output.headers[_cl_],()=>strictParseLong(output.headers[_cl_])],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_ETa]:[,output.headers[_eta]],[_MM]:[()=>void 0!==output.headers[_xamm],()=>strictParseInt32(output.headers[_xamm])],[_VI]:[,output.headers[_xavi]],[_CC]:[,output.headers[_cc]],[_CD]:[,output.headers[_cd]],[_CE]:[,output.headers[_ce]],[_CL]:[,output.headers[_cl]],[_CTo]:[,output.headers[_ct]],[_CR]:[,output.headers[_cr]],[_E]:[()=>void 0!==output.headers[_e],()=>expectNonNull(parseRfc7231DateTime(output.headers[_e]))],[_ES]:[,output.headers[_ex]],[_WRL]:[,output.headers[_xawrl]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_SC]:[,output.headers[_xasc]],[_RC]:[,output.headers[_xarc]],[_RS]:[,output.headers[_xars]],[_PC]:[()=>void 0!==output.headers[_xampc],()=>strictParseInt32(output.headers[_xampc])],[_OLM]:[,output.headers[_xaolm]],[_OLRUD]:[()=>void 0!==output.headers[_xaolrud],()=>expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))],[_OLLHS]:[,output.headers[_xaollh]],Metadata:[,Object.keys(output.headers).filter((header=>header.startsWith("x-amz-meta-"))).reduce(((acc,header)=>{acc[header.substring(11)]=output.headers[header];return acc}),{})]});await collectBody(output.body,context2);return contents};de_ListBucketAnalyticsConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AnalyticsConfiguration?contents[_ACLn]=[]:null!=data[_AC]&&(contents[_ACLn]=de_AnalyticsConfigurationList(getArrayIfSingleItem(data[_AC]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketIntelligentTieringConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));""===data.IntelligentTieringConfiguration?contents[_ITCL]=[]:null!=data[_ITC]&&(contents[_ITCL]=de_IntelligentTieringConfigurationList(getArrayIfSingleItem(data[_ITC]),context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketInventoryConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));""===data.InventoryConfiguration?contents[_ICL]=[]:null!=data[_IC]&&(contents[_ICL]=de_InventoryConfigurationList(getArrayIfSingleItem(data[_IC]),context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketMetricsConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));""===data.MetricsConfiguration?contents[_MCL]=[]:null!=data[_MC]&&(contents[_MCL]=de_MetricsConfigurationList(getArrayIfSingleItem(data[_MC]),context2));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Buckets?contents[_Bu]=[]:null!=data[_Bu]&&null!=data[_Bu][_B]&&(contents[_Bu]=de_Buckets(getArrayIfSingleItem(data[_Bu][_B]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));null!=data[_P]&&(contents[_P]=expectString(data[_P]));return contents};de_ListDirectoryBucketsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Buckets?contents[_Bu]=[]:null!=data[_Bu]&&null!=data[_Bu][_B]&&(contents[_Bu]=de_Buckets(getArrayIfSingleItem(data[_Bu][_B]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));return contents};de_ListMultipartUploadsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KM]&&(contents[_KM]=expectString(data[_KM]));null!=data[_MU]&&(contents[_MU]=strictParseInt32(data[_MU]));null!=data[_NKM]&&(contents[_NKM]=expectString(data[_NKM]));null!=data[_NUIM]&&(contents[_NUIM]=expectString(data[_NUIM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_UIM]&&(contents[_UIM]=expectString(data[_UIM]));""===data.Upload?contents[_Up]=[]:null!=data[_U]&&(contents[_Up]=de_MultipartUploadList(getArrayIfSingleItem(data[_U]),context2));return contents};de_ListObjectsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.Contents?contents[_Co]=[]:null!=data[_Co]&&(contents[_Co]=de_ObjectList(getArrayIfSingleItem(data[_Co]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_M]&&(contents[_M]=expectString(data[_M]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NM]&&(contents[_NM]=expectString(data[_NM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));return contents};de_ListObjectsV2Command=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.Contents?contents[_Co]=[]:null!=data[_Co]&&(contents[_Co]=de_ObjectList(getArrayIfSingleItem(data[_Co]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KC]&&(contents[_KC]=strictParseInt32(data[_KC]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_SA]&&(contents[_SA]=expectString(data[_SA]));return contents};de_ListObjectVersionsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.DeleteMarker?contents[_DMe]=[]:null!=data[_DM]&&(contents[_DMe]=de_DeleteMarkers(getArrayIfSingleItem(data[_DM]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KM]&&(contents[_KM]=expectString(data[_KM]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NKM]&&(contents[_NKM]=expectString(data[_NKM]));null!=data[_NVIM]&&(contents[_NVIM]=expectString(data[_NVIM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_VIM]&&(contents[_VIM]=expectString(data[_VIM]));""===data.Version?contents[_Ve]=[]:null!=data[_V]&&(contents[_Ve]=de_ObjectVersionList(getArrayIfSingleItem(data[_V]),context2));return contents};de_ListPartsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_AD]:[()=>void 0!==output.headers[_xaad],()=>expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))],[_ARI]:[,output.headers[_xaari]],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_CA]&&(contents[_CA]=expectString(data[_CA]));null!=data[_CT]&&(contents[_CT]=expectString(data[_CT]));null!=data[_In]&&(contents[_In]=de_Initiator(data[_In],context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_MP]&&(contents[_MP]=strictParseInt32(data[_MP]));null!=data[_NPNM]&&(contents[_NPNM]=expectString(data[_NPNM]));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));null!=data[_PNM]&&(contents[_PNM]=expectString(data[_PNM]));""===data.Part?contents[_Part]=[]:null!=data[_Par]&&(contents[_Part]=de_Parts(getArrayIfSingleItem(data[_Par]),context2));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));null!=data[_UI]&&(contents[_UI]=expectString(data[_UI]));return contents};de_PutBucketAccelerateConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketCorsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketEncryptionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketInventoryConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketLifecycleConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_TDMOS]:[,output.headers[_xatdmos]]});await collectBody(output.body,context2);return contents};de_PutBucketLoggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketMetricsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketNotificationConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketOwnershipControlsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketPolicyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketReplicationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketRequestPaymentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketVersioningCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketWebsiteCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_SSE]:[,output.headers[_xasse]],[_VI]:[,output.headers[_xavi]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_Si]:[()=>void 0!==output.headers[_xaos],()=>strictParseLong(output.headers[_xaos])],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectLegalHoldCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectLockConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectRetentionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]});await collectBody(output.body,context2);return contents};de_PutPublicAccessBlockCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_RestoreObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]],[_ROP]:[,output.headers[_xarop]]});await collectBody(output.body,context2);return contents};de_SelectObjectContentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=output.body;contents.Payload=de_SelectObjectContentEventStream(data,context2);return contents};de_UploadPartCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_SSE]:[,output.headers[_xasse]],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_UploadPartCopyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_CSVI]:[,output.headers[_xacsvi]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectObject(await parseXmlBody(output.body,context2));contents.CopyPartResult=de_CopyPartResult(data,context2);return contents};de_WriteGetObjectResponseCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_CommandError=async(output,context2)=>{const parsedOutput={...output,body:await parseXmlErrorBody(output.body,context2)},errorCode=loadRestXmlErrorCode(output,parsedOutput.body);switch(errorCode){case"NoSuchUpload":case"com.amazonaws.s3#NoSuchUpload":throw await de_NoSuchUploadRes(parsedOutput,context2);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await de_ObjectNotInActiveTierErrorRes(parsedOutput,context2);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await de_BucketAlreadyExistsRes(parsedOutput,context2);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await de_BucketAlreadyOwnedByYouRes(parsedOutput,context2);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await de_NoSuchBucketRes(parsedOutput,context2);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await de_InvalidObjectStateRes(parsedOutput,context2);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await de_NoSuchKeyRes(parsedOutput,context2);case"NotFound":case"com.amazonaws.s3#NotFound":throw await de_NotFoundRes(parsedOutput,context2);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await de_EncryptionTypeMismatchRes(parsedOutput,context2);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await de_InvalidRequestRes(parsedOutput,context2);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await de_InvalidWriteOffsetRes(parsedOutput,context2);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await de_TooManyPartsRes(parsedOutput,context2);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await de_ObjectAlreadyInActiveTierErrorRes(parsedOutput,context2);default:const parsedBody=parsedOutput.body;return throwDefaultError2({output,parsedBody,errorCode})}};throwDefaultError2=withBaseException(S3ServiceException);de_BucketAlreadyExistsRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new BucketAlreadyExists({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_BucketAlreadyOwnedByYouRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new BucketAlreadyOwnedByYou({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_EncryptionTypeMismatchRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new EncryptionTypeMismatch({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_InvalidObjectStateRes=async(parsedOutput,context2)=>{const contents=map2({}),data=parsedOutput.body;null!=data[_AT]&&(contents[_AT]=expectString(data[_AT]));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));const exception=new InvalidObjectState({$metadata:deserializeMetadata2(parsedOutput),...contents});return decorateServiceException(exception,parsedOutput.body)};de_InvalidRequestRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new InvalidRequest({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_InvalidWriteOffsetRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new InvalidWriteOffset({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchBucketRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchBucket({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchKeyRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchKey({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchUploadRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchUpload({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NotFoundRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NotFound({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_ObjectAlreadyInActiveTierErrorRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new ObjectAlreadyInActiveTierError({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_ObjectNotInActiveTierErrorRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new ObjectNotInActiveTierError({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_TooManyPartsRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new TooManyParts({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_SelectObjectContentEventStream=(output,context2)=>context2.eventStreamMarshaller.deserialize(output,(async event2=>null!=event2.Records?{Records:await de_RecordsEvent_event(event2.Records,context2)}:null!=event2.Stats?{Stats:await de_StatsEvent_event(event2.Stats,context2)}:null!=event2.Progress?{Progress:await de_ProgressEvent_event(event2.Progress,context2)}:null!=event2.Cont?{Cont:await de_ContinuationEvent_event(event2.Cont,context2)}:null!=event2.End?{End:await de_EndEvent_event(event2.End,context2)}:{$unknown:output}));de_ContinuationEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);Object.assign(contents,de_ContinuationEvent(data,context2));return contents};de_EndEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);Object.assign(contents,de_EndEvent(data,context2));return contents};de_ProgressEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);contents.Details=de_Progress(data,context2);return contents};de_RecordsEvent_event=async(output,context2)=>{const contents={};contents.Payload=output.body;return contents};de_StatsEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);contents.Details=de_Stats(data,context2);return contents};se_AbortIncompleteMultipartUpload=(input,context2)=>{const bn2=new XmlNode(_AIMU);null!=input[_DAI]&&bn2.c(XmlNode.of(_DAI,String(input[_DAI])).n(_DAI));return bn2};se_AccelerateConfiguration=(input,context2)=>{const bn2=new XmlNode(_ACc);null!=input[_S]&&bn2.c(XmlNode.of(_BAS,input[_S]).n(_S));return bn2};se_AccessControlPolicy=(input,context2)=>{const bn2=new XmlNode(_ACP);bn2.lc(input,"Grants","AccessControlList",(()=>se_Grants(input[_Gr],context2)));null!=input[_O]&&bn2.c(se_Owner(input[_O],context2).n(_O));return bn2};se_AccessControlTranslation=(input,context2)=>{const bn2=new XmlNode(_ACT);null!=input[_O]&&bn2.c(XmlNode.of(_OOw,input[_O]).n(_O));return bn2};se_AllowedHeaders=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AH,entry).n(_me)));se_AllowedMethods=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AM,entry).n(_me)));se_AllowedOrigins=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AO,entry).n(_me)));se_AnalyticsAndOperator=(input,context2)=>{const bn2=new XmlNode(_AAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_AnalyticsConfiguration=(input,context2)=>{const bn2=new XmlNode(_AC);null!=input[_I]&&bn2.c(XmlNode.of(_AI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_AnalyticsFilter(input[_F],context2).n(_F));null!=input[_SCA]&&bn2.c(se_StorageClassAnalysis(input[_SCA],context2).n(_SCA));return bn2};se_AnalyticsExportDestination=(input,context2)=>{const bn2=new XmlNode(_AED);null!=input[_SBD]&&bn2.c(se_AnalyticsS3BucketDestination(input[_SBD],context2).n(_SBD));return bn2};se_AnalyticsFilter=(input,context2)=>{const bn2=new XmlNode(_AF);AnalyticsFilter.visit(input,{Prefix:value=>{null!=input[_P]&&bn2.c(XmlNode.of(_P,value).n(_P))},Tag:value=>{null!=input[_Ta]&&bn2.c(se_Tag(value,context2).n(_Ta))},And:value=>{null!=input[_A]&&bn2.c(se_AnalyticsAndOperator(value,context2).n(_A))},_:(name,value)=>{if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("Unable to serialize unknown union members in XML.");bn2.c(new XmlNode(name).c(value))}});return bn2};se_AnalyticsS3BucketDestination=(input,context2)=>{const bn2=new XmlNode(_ASBD);null!=input[_Fo]&&bn2.c(XmlNode.of(_ASEFF,input[_Fo]).n(_Fo));null!=input[_BAI]&&bn2.c(XmlNode.of(_AIc,input[_BAI]).n(_BAI));null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));bn2.cc(input,_P);return bn2};se_BucketInfo=(input,context2)=>{const bn2=new XmlNode(_BI);bn2.cc(input,_DR);null!=input[_Ty]&&bn2.c(XmlNode.of(_BT,input[_Ty]).n(_Ty));return bn2};se_BucketLifecycleConfiguration=(input,context2)=>{const bn2=new XmlNode(_BLC);bn2.l(input,"Rules","Rule",(()=>se_LifecycleRules(input[_Rul],context2)));return bn2};se_BucketLoggingStatus=(input,context2)=>{const bn2=new XmlNode(_BLS);null!=input[_LE]&&bn2.c(se_LoggingEnabled(input[_LE],context2).n(_LE));return bn2};se_CompletedMultipartUpload=(input,context2)=>{const bn2=new XmlNode(_CMU);bn2.l(input,"Parts","Part",(()=>se_CompletedPartList(input[_Part],context2)));return bn2};se_CompletedPart=(input,context2)=>{const bn2=new XmlNode(_CPo);bn2.cc(input,_ETa);bn2.cc(input,_CCRC);bn2.cc(input,_CCRCC);bn2.cc(input,_CCRCNVME);bn2.cc(input,_CSHA);bn2.cc(input,_CSHAh);null!=input[_PN]&&bn2.c(XmlNode.of(_PN,String(input[_PN])).n(_PN));return bn2};se_CompletedPartList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_CompletedPart(entry).n(_me)));se_Condition=(input,context2)=>{const bn2=new XmlNode(_Con);bn2.cc(input,_HECRE);bn2.cc(input,_KPE);return bn2};se_CORSConfiguration=(input,context2)=>{const bn2=new XmlNode(_CORSC);bn2.l(input,"CORSRules","CORSRule",(()=>se_CORSRules(input[_CORSRu],context2)));return bn2};se_CORSRule=(input,context2)=>{const bn2=new XmlNode(_CORSR);bn2.cc(input,_ID_);bn2.l(input,"AllowedHeaders","AllowedHeader",(()=>se_AllowedHeaders(input[_AHl])));bn2.l(input,"AllowedMethods","AllowedMethod",(()=>se_AllowedMethods(input[_AMl])));bn2.l(input,"AllowedOrigins","AllowedOrigin",(()=>se_AllowedOrigins(input[_AOl])));bn2.l(input,"ExposeHeaders","ExposeHeader",(()=>se_ExposeHeaders(input[_EH],context2)));null!=input[_MAS]&&bn2.c(XmlNode.of(_MAS,String(input[_MAS])).n(_MAS));return bn2};se_CORSRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_CORSRule(entry,context2).n(_me)));se_CreateBucketConfiguration=(input,context2)=>{const bn2=new XmlNode(_CBC);null!=input[_LC]&&bn2.c(XmlNode.of(_BLCu,input[_LC]).n(_LC));null!=input[_L]&&bn2.c(se_LocationInfo(input[_L],context2).n(_L));null!=input[_B]&&bn2.c(se_BucketInfo(input[_B]).n(_B));return bn2};se_CSVInput=(input,context2)=>{const bn2=new XmlNode(_CSVIn);bn2.cc(input,_FHI);bn2.cc(input,_Com);bn2.cc(input,_QEC);bn2.cc(input,_RD);bn2.cc(input,_FD);bn2.cc(input,_QCuo);null!=input[_AQRD]&&bn2.c(XmlNode.of(_AQRD,String(input[_AQRD])).n(_AQRD));return bn2};se_CSVOutput=(input,context2)=>{const bn2=new XmlNode(_CSVO);bn2.cc(input,_QF);bn2.cc(input,_QEC);bn2.cc(input,_RD);bn2.cc(input,_FD);bn2.cc(input,_QCuo);return bn2};se_DefaultRetention=(input,context2)=>{const bn2=new XmlNode(_DRe);null!=input[_Mo]&&bn2.c(XmlNode.of(_OLRM,input[_Mo]).n(_Mo));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_Y]&&bn2.c(XmlNode.of(_Y,String(input[_Y])).n(_Y));return bn2};se_Delete=(input,context2)=>{const bn2=new XmlNode(_Del);bn2.l(input,"Objects","Object",(()=>se_ObjectIdentifierList(input[_Ob],context2)));null!=input[_Q]&&bn2.c(XmlNode.of(_Q,String(input[_Q])).n(_Q));return bn2};se_DeleteMarkerReplication=(input,context2)=>{const bn2=new XmlNode(_DMR);null!=input[_S]&&bn2.c(XmlNode.of(_DMRS,input[_S]).n(_S));return bn2};se_Destination=(input,context2)=>{const bn2=new XmlNode(_Des);null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));null!=input[_Ac]&&bn2.c(XmlNode.of(_AIc,input[_Ac]).n(_Ac));bn2.cc(input,_SC);null!=input[_ACT]&&bn2.c(se_AccessControlTranslation(input[_ACT]).n(_ACT));null!=input[_ECn]&&bn2.c(se_EncryptionConfiguration(input[_ECn],context2).n(_ECn));null!=input[_RTe]&&bn2.c(se_ReplicationTime(input[_RTe],context2).n(_RTe));null!=input[_Me]&&bn2.c(se_Metrics(input[_Me],context2).n(_Me));return bn2};se_Encryption=(input,context2)=>{const bn2=new XmlNode(_En);null!=input[_ETn]&&bn2.c(XmlNode.of(_SSE,input[_ETn]).n(_ETn));null!=input[_KMSKI]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KMSKI]).n(_KMSKI));bn2.cc(input,_KMSC);return bn2};se_EncryptionConfiguration=(input,context2)=>{const bn2=new XmlNode(_ECn);bn2.cc(input,_RKKID);return bn2};se_ErrorDocument=(input,context2)=>{const bn2=new XmlNode(_ED);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));return bn2};se_EventBridgeConfiguration=(input,context2)=>new XmlNode(_EBC);se_EventList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_Ev,entry).n(_me)));se_ExistingObjectReplication=(input,context2)=>{const bn2=new XmlNode(_EOR);null!=input[_S]&&bn2.c(XmlNode.of(_EORS,input[_S]).n(_S));return bn2};se_ExposeHeaders=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_EHx,entry).n(_me)));se_FilterRule=(input,context2)=>{const bn2=new XmlNode(_FR);null!=input[_N]&&bn2.c(XmlNode.of(_FRN,input[_N]).n(_N));null!=input[_Va]&&bn2.c(XmlNode.of(_FRV,input[_Va]).n(_Va));return bn2};se_FilterRuleList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_FilterRule(entry).n(_me)));se_GlacierJobParameters=(input,context2)=>{const bn2=new XmlNode(_GJP);bn2.cc(input,_Ti);return bn2};se_Grant=(input,context2)=>{const bn2=new XmlNode(_G);if(null!=input[_Gra]){const n3=se_Grantee(input[_Gra],context2).n(_Gra);n3.a("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");bn2.c(n3)}bn2.cc(input,_Pe);return bn2};se_Grantee=(input,context2)=>{const bn2=new XmlNode(_Gra);bn2.cc(input,_DN);bn2.cc(input,_EA);bn2.cc(input,_ID_);bn2.cc(input,_URI);bn2.a("xsi:type",input[_Ty]);return bn2};se_Grants=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Grant(entry,context2).n(_G)));se_IndexDocument=(input,context2)=>{const bn2=new XmlNode(_ID);bn2.cc(input,_Su);return bn2};se_InputSerialization=(input,context2)=>{const bn2=new XmlNode(_IS);null!=input[_CSV]&&bn2.c(se_CSVInput(input[_CSV]).n(_CSV));bn2.cc(input,_CTom);null!=input[_JSON]&&bn2.c(se_JSONInput(input[_JSON],context2).n(_JSON));null!=input[_Parq]&&bn2.c(se_ParquetInput(input[_Parq],context2).n(_Parq));return bn2};se_IntelligentTieringAndOperator=(input,context2)=>{const bn2=new XmlNode(_ITAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_IntelligentTieringConfiguration=(input,context2)=>{const bn2=new XmlNode(_ITC);null!=input[_I]&&bn2.c(XmlNode.of(_ITI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_IntelligentTieringFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_ITS,input[_S]).n(_S));bn2.l(input,"Tierings","Tiering",(()=>se_TieringList(input[_Tie],context2)));return bn2};se_IntelligentTieringFilter=(input,context2)=>{const bn2=new XmlNode(_ITF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_A]&&bn2.c(se_IntelligentTieringAndOperator(input[_A],context2).n(_A));return bn2};se_InventoryConfiguration=(input,context2)=>{const bn2=new XmlNode(_IC);null!=input[_Des]&&bn2.c(se_InventoryDestination(input[_Des],context2).n(_Des));null!=input[_IE]&&bn2.c(XmlNode.of(_IE,String(input[_IE])).n(_IE));null!=input[_F]&&bn2.c(se_InventoryFilter(input[_F],context2).n(_F));null!=input[_I]&&bn2.c(XmlNode.of(_II,input[_I]).n(_I));null!=input[_IOV]&&bn2.c(XmlNode.of(_IIOV,input[_IOV]).n(_IOV));bn2.lc(input,"OptionalFields","OptionalFields",(()=>se_InventoryOptionalFields(input[_OF],context2)));null!=input[_Sc]&&bn2.c(se_InventorySchedule(input[_Sc],context2).n(_Sc));return bn2};se_InventoryDestination=(input,context2)=>{const bn2=new XmlNode(_IDn);null!=input[_SBD]&&bn2.c(se_InventoryS3BucketDestination(input[_SBD],context2).n(_SBD));return bn2};se_InventoryEncryption=(input,context2)=>{const bn2=new XmlNode(_IEn);null!=input[_SSES]&&bn2.c(se_SSES3(input[_SSES],context2).n(_SS));null!=input[_SSEKMS]&&bn2.c(se_SSEKMS(input[_SSEKMS],context2).n(_SK));return bn2};se_InventoryFilter=(input,context2)=>{const bn2=new XmlNode(_IF);bn2.cc(input,_P);return bn2};se_InventoryOptionalFields=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_IOF,entry).n(_Fi)));se_InventoryS3BucketDestination=(input,context2)=>{const bn2=new XmlNode(_ISBD);bn2.cc(input,_AIc);null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));null!=input[_Fo]&&bn2.c(XmlNode.of(_IFn,input[_Fo]).n(_Fo));bn2.cc(input,_P);null!=input[_En]&&bn2.c(se_InventoryEncryption(input[_En],context2).n(_En));return bn2};se_InventorySchedule=(input,context2)=>{const bn2=new XmlNode(_ISn);null!=input[_Fr]&&bn2.c(XmlNode.of(_IFnv,input[_Fr]).n(_Fr));return bn2};se_JSONInput=(input,context2)=>{const bn2=new XmlNode(_JSONI);null!=input[_Ty]&&bn2.c(XmlNode.of(_JSONT,input[_Ty]).n(_Ty));return bn2};se_JSONOutput=(input,context2)=>{const bn2=new XmlNode(_JSONO);bn2.cc(input,_RD);return bn2};se_LambdaFunctionConfiguration=(input,context2)=>{const bn2=new XmlNode(_LFCa);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_LFA]&&bn2.c(XmlNode.of(_LFA,input[_LFA]).n(_CF));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_LambdaFunctionConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_LambdaFunctionConfiguration(entry,context2).n(_me)));se_LifecycleExpiration=(input,context2)=>{const bn2=new XmlNode(_LEi);null!=input[_Dat]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_Dat]).toString()).n(_Dat));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_EODM]&&bn2.c(XmlNode.of(_EODM,String(input[_EODM])).n(_EODM));return bn2};se_LifecycleRule=(input,context2)=>{const bn2=new XmlNode(_LR);null!=input[_Exp]&&bn2.c(se_LifecycleExpiration(input[_Exp]).n(_Exp));bn2.cc(input,_ID_);bn2.cc(input,_P);null!=input[_F]&&bn2.c(se_LifecycleRuleFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_ESx,input[_S]).n(_S));bn2.l(input,"Transitions","Transition",(()=>se_TransitionList(input[_Tr],context2)));bn2.l(input,"NoncurrentVersionTransitions","NoncurrentVersionTransition",(()=>se_NoncurrentVersionTransitionList(input[_NVT],context2)));null!=input[_NVE]&&bn2.c(se_NoncurrentVersionExpiration(input[_NVE],context2).n(_NVE));null!=input[_AIMU]&&bn2.c(se_AbortIncompleteMultipartUpload(input[_AIMU]).n(_AIMU));return bn2};se_LifecycleRuleAndOperator=(input,context2)=>{const bn2=new XmlNode(_LRAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));null!=input[_OSGT]&&bn2.c(XmlNode.of(_OSGTB,String(input[_OSGT])).n(_OSGT));null!=input[_OSLT]&&bn2.c(XmlNode.of(_OSLTB,String(input[_OSLT])).n(_OSLT));return bn2};se_LifecycleRuleFilter=(input,context2)=>{const bn2=new XmlNode(_LRF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_OSGT]&&bn2.c(XmlNode.of(_OSGTB,String(input[_OSGT])).n(_OSGT));null!=input[_OSLT]&&bn2.c(XmlNode.of(_OSLTB,String(input[_OSLT])).n(_OSLT));null!=input[_A]&&bn2.c(se_LifecycleRuleAndOperator(input[_A],context2).n(_A));return bn2};se_LifecycleRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_LifecycleRule(entry,context2).n(_me)));se_LocationInfo=(input,context2)=>{const bn2=new XmlNode(_LI);null!=input[_Ty]&&bn2.c(XmlNode.of(_LT,input[_Ty]).n(_Ty));null!=input[_N]&&bn2.c(XmlNode.of(_LNAS,input[_N]).n(_N));return bn2};se_LoggingEnabled=(input,context2)=>{const bn2=new XmlNode(_LE);bn2.cc(input,_TB);bn2.lc(input,"TargetGrants","TargetGrants",(()=>se_TargetGrants(input[_TG],context2)));bn2.cc(input,_TP);null!=input[_TOKF]&&bn2.c(se_TargetObjectKeyFormat(input[_TOKF],context2).n(_TOKF));return bn2};se_MetadataEntry=(input,context2)=>{const bn2=new XmlNode(_ME);null!=input[_N]&&bn2.c(XmlNode.of(_MKe,input[_N]).n(_N));null!=input[_Va]&&bn2.c(XmlNode.of(_MV,input[_Va]).n(_Va));return bn2};se_MetadataTableConfiguration=(input,context2)=>{const bn2=new XmlNode(_MTC);null!=input[_STD]&&bn2.c(se_S3TablesDestination(input[_STD],context2).n(_STD));return bn2};se_Metrics=(input,context2)=>{const bn2=new XmlNode(_Me);null!=input[_S]&&bn2.c(XmlNode.of(_MS,input[_S]).n(_S));null!=input[_ETv]&&bn2.c(se_ReplicationTimeValue(input[_ETv],context2).n(_ETv));return bn2};se_MetricsAndOperator=(input,context2)=>{const bn2=new XmlNode(_MAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));bn2.cc(input,_APAc);return bn2};se_MetricsConfiguration=(input,context2)=>{const bn2=new XmlNode(_MC);null!=input[_I]&&bn2.c(XmlNode.of(_MI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_MetricsFilter(input[_F],context2).n(_F));return bn2};se_MetricsFilter=(input,context2)=>{const bn2=new XmlNode(_MF);MetricsFilter.visit(input,{Prefix:value=>{null!=input[_P]&&bn2.c(XmlNode.of(_P,value).n(_P))},Tag:value=>{null!=input[_Ta]&&bn2.c(se_Tag(value,context2).n(_Ta))},AccessPointArn:value=>{null!=input[_APAc]&&bn2.c(XmlNode.of(_APAc,value).n(_APAc))},And:value=>{null!=input[_A]&&bn2.c(se_MetricsAndOperator(value,context2).n(_A))},_:(name,value)=>{if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("Unable to serialize unknown union members in XML.");bn2.c(new XmlNode(name).c(value))}});return bn2};se_NoncurrentVersionExpiration=(input,context2)=>{const bn2=new XmlNode(_NVE);null!=input[_ND]&&bn2.c(XmlNode.of(_Da,String(input[_ND])).n(_ND));null!=input[_NNV]&&bn2.c(XmlNode.of(_VC,String(input[_NNV])).n(_NNV));return bn2};se_NoncurrentVersionTransition=(input,context2)=>{const bn2=new XmlNode(_NVTo);null!=input[_ND]&&bn2.c(XmlNode.of(_Da,String(input[_ND])).n(_ND));null!=input[_SC]&&bn2.c(XmlNode.of(_TSC,input[_SC]).n(_SC));null!=input[_NNV]&&bn2.c(XmlNode.of(_VC,String(input[_NNV])).n(_NNV));return bn2};se_NoncurrentVersionTransitionList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_NoncurrentVersionTransition(entry).n(_me)));se_NotificationConfiguration=(input,context2)=>{const bn2=new XmlNode(_NC);bn2.l(input,"TopicConfigurations","TopicConfiguration",(()=>se_TopicConfigurationList(input[_TCop],context2)));bn2.l(input,"QueueConfigurations","QueueConfiguration",(()=>se_QueueConfigurationList(input[_QCu],context2)));bn2.l(input,"LambdaFunctionConfigurations","CloudFunctionConfiguration",(()=>se_LambdaFunctionConfigurationList(input[_LFC],context2)));null!=input[_EBC]&&bn2.c(se_EventBridgeConfiguration(input[_EBC]).n(_EBC));return bn2};se_NotificationConfigurationFilter=(input,context2)=>{const bn2=new XmlNode(_NCF);null!=input[_K]&&bn2.c(se_S3KeyFilter(input[_K],context2).n(_SKe));return bn2};se_ObjectIdentifier=(input,context2)=>{const bn2=new XmlNode(_OI);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));null!=input[_VI]&&bn2.c(XmlNode.of(_OVI,input[_VI]).n(_VI));bn2.cc(input,_ETa);null!=input[_LMT]&&bn2.c(XmlNode.of(_LMT,dateToUtcString(input[_LMT]).toString()).n(_LMT));null!=input[_Si]&&bn2.c(XmlNode.of(_Si,String(input[_Si])).n(_Si));return bn2};se_ObjectIdentifierList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ObjectIdentifier(entry).n(_me)));se_ObjectLockConfiguration=(input,context2)=>{const bn2=new XmlNode(_OLC);bn2.cc(input,_OLE);null!=input[_Ru]&&bn2.c(se_ObjectLockRule(input[_Ru],context2).n(_Ru));return bn2};se_ObjectLockLegalHold=(input,context2)=>{const bn2=new XmlNode(_OLLH);null!=input[_S]&&bn2.c(XmlNode.of(_OLLHS,input[_S]).n(_S));return bn2};se_ObjectLockRetention=(input,context2)=>{const bn2=new XmlNode(_OLR);null!=input[_Mo]&&bn2.c(XmlNode.of(_OLRM,input[_Mo]).n(_Mo));null!=input[_RUD]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_RUD]).toString()).n(_RUD));return bn2};se_ObjectLockRule=(input,context2)=>{const bn2=new XmlNode(_OLRb);null!=input[_DRe]&&bn2.c(se_DefaultRetention(input[_DRe]).n(_DRe));return bn2};se_OutputLocation=(input,context2)=>{const bn2=new XmlNode(_OL);null!=input[_S_]&&bn2.c(se_S3Location(input[_S_],context2).n(_S_));return bn2};se_OutputSerialization=(input,context2)=>{const bn2=new XmlNode(_OS);null!=input[_CSV]&&bn2.c(se_CSVOutput(input[_CSV]).n(_CSV));null!=input[_JSON]&&bn2.c(se_JSONOutput(input[_JSON]).n(_JSON));return bn2};se_Owner=(input,context2)=>{const bn2=new XmlNode(_O);bn2.cc(input,_DN);bn2.cc(input,_ID_);return bn2};se_OwnershipControls=(input,context2)=>{const bn2=new XmlNode(_OC);bn2.l(input,"Rules","Rule",(()=>se_OwnershipControlsRules(input[_Rul],context2)));return bn2};se_OwnershipControlsRule=(input,context2)=>{const bn2=new XmlNode(_OCR);bn2.cc(input,_OO);return bn2};se_OwnershipControlsRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_OwnershipControlsRule(entry).n(_me)));se_ParquetInput=(input,context2)=>new XmlNode(_PI);se_PartitionedPrefix=(input,context2)=>{const bn2=new XmlNode(_PP);bn2.cc(input,_PDS);return bn2};se_PublicAccessBlockConfiguration=(input,context2)=>{const bn2=new XmlNode(_PABC);null!=input[_BPA]&&bn2.c(XmlNode.of(_Se,String(input[_BPA])).n(_BPA));null!=input[_IPA]&&bn2.c(XmlNode.of(_Se,String(input[_IPA])).n(_IPA));null!=input[_BPP]&&bn2.c(XmlNode.of(_Se,String(input[_BPP])).n(_BPP));null!=input[_RPB]&&bn2.c(XmlNode.of(_Se,String(input[_RPB])).n(_RPB));return bn2};se_QueueConfiguration=(input,context2)=>{const bn2=new XmlNode(_QC);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_QA]&&bn2.c(XmlNode.of(_QA,input[_QA]).n(_Qu));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_QueueConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_QueueConfiguration(entry,context2).n(_me)));se_Redirect=(input,context2)=>{const bn2=new XmlNode(_Red);bn2.cc(input,_HN);bn2.cc(input,_HRC);bn2.cc(input,_Pr);bn2.cc(input,_RKPW);bn2.cc(input,_RKW);return bn2};se_RedirectAllRequestsTo=(input,context2)=>{const bn2=new XmlNode(_RART);bn2.cc(input,_HN);bn2.cc(input,_Pr);return bn2};se_ReplicaModifications=(input,context2)=>{const bn2=new XmlNode(_RM);null!=input[_S]&&bn2.c(XmlNode.of(_RMS,input[_S]).n(_S));return bn2};se_ReplicationConfiguration=(input,context2)=>{const bn2=new XmlNode(_RCe);bn2.cc(input,_Ro);bn2.l(input,"Rules","Rule",(()=>se_ReplicationRules(input[_Rul],context2)));return bn2};se_ReplicationRule=(input,context2)=>{const bn2=new XmlNode(_RRe);bn2.cc(input,_ID_);null!=input[_Pri]&&bn2.c(XmlNode.of(_Pri,String(input[_Pri])).n(_Pri));bn2.cc(input,_P);null!=input[_F]&&bn2.c(se_ReplicationRuleFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_RRS,input[_S]).n(_S));null!=input[_SSC]&&bn2.c(se_SourceSelectionCriteria(input[_SSC],context2).n(_SSC));null!=input[_EOR]&&bn2.c(se_ExistingObjectReplication(input[_EOR]).n(_EOR));null!=input[_Des]&&bn2.c(se_Destination(input[_Des],context2).n(_Des));null!=input[_DMR]&&bn2.c(se_DeleteMarkerReplication(input[_DMR]).n(_DMR));return bn2};se_ReplicationRuleAndOperator=(input,context2)=>{const bn2=new XmlNode(_RRAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_ReplicationRuleFilter=(input,context2)=>{const bn2=new XmlNode(_RRF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_A]&&bn2.c(se_ReplicationRuleAndOperator(input[_A],context2).n(_A));return bn2};se_ReplicationRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ReplicationRule(entry,context2).n(_me)));se_ReplicationTime=(input,context2)=>{const bn2=new XmlNode(_RTe);null!=input[_S]&&bn2.c(XmlNode.of(_RTS,input[_S]).n(_S));null!=input[_Tim]&&bn2.c(se_ReplicationTimeValue(input[_Tim],context2).n(_Tim));return bn2};se_ReplicationTimeValue=(input,context2)=>{const bn2=new XmlNode(_RTV);null!=input[_Mi]&&bn2.c(XmlNode.of(_Mi,String(input[_Mi])).n(_Mi));return bn2};se_RequestPaymentConfiguration=(input,context2)=>{const bn2=new XmlNode(_RPC);bn2.cc(input,_Pa);return bn2};se_RequestProgress=(input,context2)=>{const bn2=new XmlNode(_RPe);null!=input[_Ena]&&bn2.c(XmlNode.of(_ERP,String(input[_Ena])).n(_Ena));return bn2};se_RestoreRequest=(input,context2)=>{const bn2=new XmlNode(_RRes);null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_GJP]&&bn2.c(se_GlacierJobParameters(input[_GJP]).n(_GJP));null!=input[_Ty]&&bn2.c(XmlNode.of(_RRT,input[_Ty]).n(_Ty));bn2.cc(input,_Ti);bn2.cc(input,_Desc);null!=input[_SP]&&bn2.c(se_SelectParameters(input[_SP],context2).n(_SP));null!=input[_OL]&&bn2.c(se_OutputLocation(input[_OL],context2).n(_OL));return bn2};se_RoutingRule=(input,context2)=>{const bn2=new XmlNode(_RRou);null!=input[_Con]&&bn2.c(se_Condition(input[_Con]).n(_Con));null!=input[_Red]&&bn2.c(se_Redirect(input[_Red]).n(_Red));return bn2};se_RoutingRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_RoutingRule(entry).n(_RRou)));se_S3KeyFilter=(input,context2)=>{const bn2=new XmlNode(_SKF);bn2.l(input,"FilterRules","FilterRule",(()=>se_FilterRuleList(input[_FRi])));return bn2};se_S3Location=(input,context2)=>{const bn2=new XmlNode(_SL);bn2.cc(input,_BN);null!=input[_P]&&bn2.c(XmlNode.of(_LP,input[_P]).n(_P));null!=input[_En]&&bn2.c(se_Encryption(input[_En]).n(_En));null!=input[_CACL]&&bn2.c(XmlNode.of(_OCACL,input[_CACL]).n(_CACL));bn2.lc(input,"AccessControlList","AccessControlList",(()=>se_Grants(input[_ACLc],context2)));null!=input[_T]&&bn2.c(se_Tagging(input[_T],context2).n(_T));bn2.lc(input,"UserMetadata","UserMetadata",(()=>se_UserMetadata(input[_UM],context2)));bn2.cc(input,_SC);return bn2};se_S3TablesDestination=(input,context2)=>{const bn2=new XmlNode(_STD);null!=input[_TBA]&&bn2.c(XmlNode.of(_STBA,input[_TBA]).n(_TBA));null!=input[_TN]&&bn2.c(XmlNode.of(_STN,input[_TN]).n(_TN));return bn2};se_ScanRange=(input,context2)=>{const bn2=new XmlNode(_SR);null!=input[_St]&&bn2.c(XmlNode.of(_St,String(input[_St])).n(_St));null!=input[_End]&&bn2.c(XmlNode.of(_End,String(input[_End])).n(_End));return bn2};se_SelectParameters=(input,context2)=>{const bn2=new XmlNode(_SP);null!=input[_IS]&&bn2.c(se_InputSerialization(input[_IS],context2).n(_IS));bn2.cc(input,_ETx);bn2.cc(input,_Ex);null!=input[_OS]&&bn2.c(se_OutputSerialization(input[_OS],context2).n(_OS));return bn2};se_ServerSideEncryptionByDefault=(input,context2)=>{const bn2=new XmlNode(_SSEBD);null!=input[_SSEA]&&bn2.c(XmlNode.of(_SSE,input[_SSEA]).n(_SSEA));null!=input[_KMSMKID]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KMSMKID]).n(_KMSMKID));return bn2};se_ServerSideEncryptionConfiguration=(input,context2)=>{const bn2=new XmlNode(_SSEC);bn2.l(input,"Rules","Rule",(()=>se_ServerSideEncryptionRules(input[_Rul],context2)));return bn2};se_ServerSideEncryptionRule=(input,context2)=>{const bn2=new XmlNode(_SSER);null!=input[_ASSEBD]&&bn2.c(se_ServerSideEncryptionByDefault(input[_ASSEBD]).n(_ASSEBD));null!=input[_BKE]&&bn2.c(XmlNode.of(_BKE,String(input[_BKE])).n(_BKE));return bn2};se_ServerSideEncryptionRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ServerSideEncryptionRule(entry).n(_me)));se_SimplePrefix=(input,context2)=>new XmlNode(_SPi);se_SourceSelectionCriteria=(input,context2)=>{const bn2=new XmlNode(_SSC);null!=input[_SKEO]&&bn2.c(se_SseKmsEncryptedObjects(input[_SKEO],context2).n(_SKEO));null!=input[_RM]&&bn2.c(se_ReplicaModifications(input[_RM]).n(_RM));return bn2};se_SSEKMS=(input,context2)=>{const bn2=new XmlNode(_SK);null!=input[_KI]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KI]).n(_KI));return bn2};se_SseKmsEncryptedObjects=(input,context2)=>{const bn2=new XmlNode(_SKEO);null!=input[_S]&&bn2.c(XmlNode.of(_SKEOS,input[_S]).n(_S));return bn2};se_SSES3=(input,context2)=>new XmlNode(_SS);se_StorageClassAnalysis=(input,context2)=>{const bn2=new XmlNode(_SCA);null!=input[_DE]&&bn2.c(se_StorageClassAnalysisDataExport(input[_DE],context2).n(_DE));return bn2};se_StorageClassAnalysisDataExport=(input,context2)=>{const bn2=new XmlNode(_SCADE);null!=input[_OSV]&&bn2.c(XmlNode.of(_SCASV,input[_OSV]).n(_OSV));null!=input[_Des]&&bn2.c(se_AnalyticsExportDestination(input[_Des],context2).n(_Des));return bn2};se_Tag=(input,context2)=>{const bn2=new XmlNode(_Ta);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));bn2.cc(input,_Va);return bn2};se_Tagging=(input,context2)=>{const bn2=new XmlNode(_T);bn2.lc(input,"TagSet","TagSet",(()=>se_TagSet(input[_TS],context2)));return bn2};se_TagSet=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Tag(entry,context2).n(_Ta)));se_TargetGrant=(input,context2)=>{const bn2=new XmlNode(_TGa);if(null!=input[_Gra]){const n3=se_Grantee(input[_Gra],context2).n(_Gra);n3.a("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");bn2.c(n3)}null!=input[_Pe]&&bn2.c(XmlNode.of(_BLP,input[_Pe]).n(_Pe));return bn2};se_TargetGrants=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_TargetGrant(entry,context2).n(_G)));se_TargetObjectKeyFormat=(input,context2)=>{const bn2=new XmlNode(_TOKF);null!=input[_SPi]&&bn2.c(se_SimplePrefix(input[_SPi]).n(_SPi));null!=input[_PP]&&bn2.c(se_PartitionedPrefix(input[_PP]).n(_PP));return bn2};se_Tiering=(input,context2)=>{const bn2=new XmlNode(_Tier);null!=input[_Da]&&bn2.c(XmlNode.of(_ITD,String(input[_Da])).n(_Da));null!=input[_AT]&&bn2.c(XmlNode.of(_ITAT,input[_AT]).n(_AT));return bn2};se_TieringList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Tiering(entry).n(_me)));se_TopicConfiguration=(input,context2)=>{const bn2=new XmlNode(_TCo);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_TA]&&bn2.c(XmlNode.of(_TA,input[_TA]).n(_Top));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_TopicConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_TopicConfiguration(entry,context2).n(_me)));se_Transition=(input,context2)=>{const bn2=new XmlNode(_Tra);null!=input[_Dat]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_Dat]).toString()).n(_Dat));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_SC]&&bn2.c(XmlNode.of(_TSC,input[_SC]).n(_SC));return bn2};se_TransitionList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Transition(entry).n(_me)));se_UserMetadata=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_MetadataEntry(entry).n(_ME)));se_VersioningConfiguration=(input,context2)=>{const bn2=new XmlNode(_VCe);null!=input[_MFAD]&&bn2.c(XmlNode.of(_MFAD,input[_MFAD]).n(_MDf));null!=input[_S]&&bn2.c(XmlNode.of(_BVS,input[_S]).n(_S));return bn2};se_WebsiteConfiguration=(input,context2)=>{const bn2=new XmlNode(_WC);null!=input[_ED]&&bn2.c(se_ErrorDocument(input[_ED]).n(_ED));null!=input[_ID]&&bn2.c(se_IndexDocument(input[_ID]).n(_ID));null!=input[_RART]&&bn2.c(se_RedirectAllRequestsTo(input[_RART]).n(_RART));bn2.lc(input,"RoutingRules","RoutingRules",(()=>se_RoutingRules(input[_RRo])));return bn2};de_AbortIncompleteMultipartUpload=(output,context2)=>{const contents={};null!=output[_DAI]&&(contents[_DAI]=strictParseInt32(output[_DAI]));return contents};de_AccessControlTranslation=(output,context2)=>{const contents={};null!=output[_O]&&(contents[_O]=expectString(output[_O]));return contents};de_AllowedHeaders=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AllowedMethods=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AllowedOrigins=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AnalyticsAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_AnalyticsConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));""===output.Filter||null!=output[_F]&&(contents[_F]=de_AnalyticsFilter(expectUnion(output[_F]),context2));null!=output[_SCA]&&(contents[_SCA]=de_StorageClassAnalysis(output[_SCA],context2));return contents};de_AnalyticsConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_AnalyticsConfiguration(entry,context2)));de_AnalyticsExportDestination=(output,context2)=>{const contents={};null!=output[_SBD]&&(contents[_SBD]=de_AnalyticsS3BucketDestination(output[_SBD],context2));return contents};de_AnalyticsFilter=(output,context2)=>null!=output[_P]?{Prefix:expectString(output[_P])}:null!=output[_Ta]?{Tag:de_Tag(output[_Ta],context2)}:null!=output[_A]?{And:de_AnalyticsAndOperator(output[_A],context2)}:{$unknown:Object.entries(output)[0]};de_AnalyticsS3BucketDestination=(output,context2)=>{const contents={};null!=output[_Fo]&&(contents[_Fo]=expectString(output[_Fo]));null!=output[_BAI]&&(contents[_BAI]=expectString(output[_BAI]));null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_Bucket=(output,context2)=>{const contents={};null!=output[_N]&&(contents[_N]=expectString(output[_N]));null!=output[_CDr]&&(contents[_CDr]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_CDr])));null!=output[_BR]&&(contents[_BR]=expectString(output[_BR]));return contents};de_Buckets=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Bucket(entry)));de_Checksum=(output,context2)=>{const contents={};null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));return contents};de_ChecksumAlgorithmList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_CommonPrefix=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_CommonPrefixList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_CommonPrefix(entry)));de_Condition=(output,context2)=>{const contents={};null!=output[_HECRE]&&(contents[_HECRE]=expectString(output[_HECRE]));null!=output[_KPE]&&(contents[_KPE]=expectString(output[_KPE]));return contents};de_ContinuationEvent=(output,context2)=>({});de_CopyObjectResult=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_CopyPartResult=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_CORSRule=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));""===output.AllowedHeader?contents[_AHl]=[]:null!=output[_AH]&&(contents[_AHl]=de_AllowedHeaders(getArrayIfSingleItem(output[_AH])));""===output.AllowedMethod?contents[_AMl]=[]:null!=output[_AM]&&(contents[_AMl]=de_AllowedMethods(getArrayIfSingleItem(output[_AM])));""===output.AllowedOrigin?contents[_AOl]=[]:null!=output[_AO]&&(contents[_AOl]=de_AllowedOrigins(getArrayIfSingleItem(output[_AO])));""===output.ExposeHeader?contents[_EH]=[]:null!=output[_EHx]&&(contents[_EH]=de_ExposeHeaders(getArrayIfSingleItem(output[_EHx]),context2));null!=output[_MAS]&&(contents[_MAS]=strictParseInt32(output[_MAS]));return contents};de_CORSRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_CORSRule(entry,context2)));de_DefaultRetention=(output,context2)=>{const contents={};null!=output[_Mo]&&(contents[_Mo]=expectString(output[_Mo]));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_Y]&&(contents[_Y]=strictParseInt32(output[_Y]));return contents};de_DeletedObject=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_DM]&&(contents[_DM]=parseBoolean(output[_DM]));null!=output[_DMVI]&&(contents[_DMVI]=expectString(output[_DMVI]));return contents};de_DeletedObjects=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_DeletedObject(entry)));de_DeleteMarkerEntry=(output,context2)=>{const contents={};null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_IL]&&(contents[_IL]=parseBoolean(output[_IL]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));return contents};de_DeleteMarkerReplication=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_DeleteMarkers=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_DeleteMarkerEntry(entry,context2)));de_Destination=(output,context2)=>{const contents={};null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_Ac]&&(contents[_Ac]=expectString(output[_Ac]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_ACT]&&(contents[_ACT]=de_AccessControlTranslation(output[_ACT]));null!=output[_ECn]&&(contents[_ECn]=de_EncryptionConfiguration(output[_ECn],context2));null!=output[_RTe]&&(contents[_RTe]=de_ReplicationTime(output[_RTe],context2));null!=output[_Me]&&(contents[_Me]=de_Metrics(output[_Me],context2));return contents};de_EncryptionConfiguration=(output,context2)=>{const contents={};null!=output[_RKKID]&&(contents[_RKKID]=expectString(output[_RKKID]));return contents};de_EndEvent=(output,context2)=>({});de__Error=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_Cod]&&(contents[_Cod]=expectString(output[_Cod]));null!=output[_Mes]&&(contents[_Mes]=expectString(output[_Mes]));return contents};de_ErrorDetails=(output,context2)=>{const contents={};null!=output[_EC]&&(contents[_EC]=expectString(output[_EC]));null!=output[_EM]&&(contents[_EM]=expectString(output[_EM]));return contents};de_ErrorDocument=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));return contents};de_Errors=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de__Error(entry)));de_EventBridgeConfiguration=(output,context2)=>({});de_EventList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_ExistingObjectReplication=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ExposeHeaders=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_FilterRule=(output,context2)=>{const contents={};null!=output[_N]&&(contents[_N]=expectString(output[_N]));null!=output[_Va]&&(contents[_Va]=expectString(output[_Va]));return contents};de_FilterRuleList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_FilterRule(entry)));de_GetBucketMetadataTableConfigurationResult=(output,context2)=>{const contents={};null!=output[_MTCR]&&(contents[_MTCR]=de_MetadataTableConfigurationResult(output[_MTCR],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_Er]&&(contents[_Er]=de_ErrorDetails(output[_Er]));return contents};de_GetObjectAttributesParts=(output,context2)=>{const contents={};null!=output[_PC]&&(contents[_TPC]=strictParseInt32(output[_PC]));null!=output[_PNM]&&(contents[_PNM]=expectString(output[_PNM]));null!=output[_NPNM]&&(contents[_NPNM]=expectString(output[_NPNM]));null!=output[_MP]&&(contents[_MP]=strictParseInt32(output[_MP]));null!=output[_IT]&&(contents[_IT]=parseBoolean(output[_IT]));""===output.Part?contents[_Part]=[]:null!=output[_Par]&&(contents[_Part]=de_PartsList(getArrayIfSingleItem(output[_Par]),context2));return contents};de_Grant=(output,context2)=>{const contents={};null!=output[_Gra]&&(contents[_Gra]=de_Grantee(output[_Gra],context2));null!=output[_Pe]&&(contents[_Pe]=expectString(output[_Pe]));return contents};de_Grantee=(output,context2)=>{const contents={};null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));null!=output[_EA]&&(contents[_EA]=expectString(output[_EA]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_URI]&&(contents[_URI]=expectString(output[_URI]));null!=output[_x]&&(contents[_Ty]=expectString(output[_x]));return contents};de_Grants=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Grant(entry,context2)));de_IndexDocument=(output,context2)=>{const contents={};null!=output[_Su]&&(contents[_Su]=expectString(output[_Su]));return contents};de_Initiator=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));return contents};de_IntelligentTieringAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_IntelligentTieringConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_F]&&(contents[_F]=de_IntelligentTieringFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));""===output.Tiering?contents[_Tie]=[]:null!=output[_Tier]&&(contents[_Tie]=de_TieringList(getArrayIfSingleItem(output[_Tier]),context2));return contents};de_IntelligentTieringConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_IntelligentTieringConfiguration(entry,context2)));de_IntelligentTieringFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_A]&&(contents[_A]=de_IntelligentTieringAndOperator(output[_A],context2));return contents};de_InventoryConfiguration=(output,context2)=>{const contents={};null!=output[_Des]&&(contents[_Des]=de_InventoryDestination(output[_Des],context2));null!=output[_IE]&&(contents[_IE]=parseBoolean(output[_IE]));null!=output[_F]&&(contents[_F]=de_InventoryFilter(output[_F],context2));null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_IOV]&&(contents[_IOV]=expectString(output[_IOV]));""===output.OptionalFields?contents[_OF]=[]:null!=output[_OF]&&null!=output[_OF][_Fi]&&(contents[_OF]=de_InventoryOptionalFields(getArrayIfSingleItem(output[_OF][_Fi]),context2));null!=output[_Sc]&&(contents[_Sc]=de_InventorySchedule(output[_Sc],context2));return contents};de_InventoryConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_InventoryConfiguration(entry,context2)));de_InventoryDestination=(output,context2)=>{const contents={};null!=output[_SBD]&&(contents[_SBD]=de_InventoryS3BucketDestination(output[_SBD],context2));return contents};de_InventoryEncryption=(output,context2)=>{const contents={};null!=output[_SS]&&(contents[_SSES]=de_SSES3(output[_SS],context2));null!=output[_SK]&&(contents[_SSEKMS]=de_SSEKMS(output[_SK],context2));return contents};de_InventoryFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_InventoryOptionalFields=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_InventoryS3BucketDestination=(output,context2)=>{const contents={};null!=output[_AIc]&&(contents[_AIc]=expectString(output[_AIc]));null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_Fo]&&(contents[_Fo]=expectString(output[_Fo]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_En]&&(contents[_En]=de_InventoryEncryption(output[_En],context2));return contents};de_InventorySchedule=(output,context2)=>{const contents={};null!=output[_Fr]&&(contents[_Fr]=expectString(output[_Fr]));return contents};de_LambdaFunctionConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_CF]&&(contents[_LFA]=expectString(output[_CF]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_LambdaFunctionConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_LambdaFunctionConfiguration(entry,context2)));de_LifecycleExpiration=(output,context2)=>{const contents={};null!=output[_Dat]&&(contents[_Dat]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat])));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_EODM]&&(contents[_EODM]=parseBoolean(output[_EODM]));return contents};de_LifecycleRule=(output,context2)=>{const contents={};null!=output[_Exp]&&(contents[_Exp]=de_LifecycleExpiration(output[_Exp]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_F]&&(contents[_F]=de_LifecycleRuleFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));""===output.Transition?contents[_Tr]=[]:null!=output[_Tra]&&(contents[_Tr]=de_TransitionList(getArrayIfSingleItem(output[_Tra]),context2));""===output.NoncurrentVersionTransition?contents[_NVT]=[]:null!=output[_NVTo]&&(contents[_NVT]=de_NoncurrentVersionTransitionList(getArrayIfSingleItem(output[_NVTo]),context2));null!=output[_NVE]&&(contents[_NVE]=de_NoncurrentVersionExpiration(output[_NVE],context2));null!=output[_AIMU]&&(contents[_AIMU]=de_AbortIncompleteMultipartUpload(output[_AIMU]));return contents};de_LifecycleRuleAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));null!=output[_OSGT]&&(contents[_OSGT]=strictParseLong(output[_OSGT]));null!=output[_OSLT]&&(contents[_OSLT]=strictParseLong(output[_OSLT]));return contents};de_LifecycleRuleFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_OSGT]&&(contents[_OSGT]=strictParseLong(output[_OSGT]));null!=output[_OSLT]&&(contents[_OSLT]=strictParseLong(output[_OSLT]));null!=output[_A]&&(contents[_A]=de_LifecycleRuleAndOperator(output[_A],context2));return contents};de_LifecycleRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_LifecycleRule(entry,context2)));de_LoggingEnabled=(output,context2)=>{const contents={};null!=output[_TB]&&(contents[_TB]=expectString(output[_TB]));""===output.TargetGrants?contents[_TG]=[]:null!=output[_TG]&&null!=output[_TG][_G]&&(contents[_TG]=de_TargetGrants(getArrayIfSingleItem(output[_TG][_G]),context2));null!=output[_TP]&&(contents[_TP]=expectString(output[_TP]));null!=output[_TOKF]&&(contents[_TOKF]=de_TargetObjectKeyFormat(output[_TOKF],context2));return contents};de_MetadataTableConfigurationResult=(output,context2)=>{const contents={};null!=output[_STDR]&&(contents[_STDR]=de_S3TablesDestinationResult(output[_STDR],context2));return contents};de_Metrics=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_ETv]&&(contents[_ETv]=de_ReplicationTimeValue(output[_ETv],context2));return contents};de_MetricsAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));null!=output[_APAc]&&(contents[_APAc]=expectString(output[_APAc]));return contents};de_MetricsConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));""===output.Filter||null!=output[_F]&&(contents[_F]=de_MetricsFilter(expectUnion(output[_F]),context2));return contents};de_MetricsConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_MetricsConfiguration(entry,context2)));de_MetricsFilter=(output,context2)=>null!=output[_P]?{Prefix:expectString(output[_P])}:null!=output[_Ta]?{Tag:de_Tag(output[_Ta],context2)}:null!=output[_APAc]?{AccessPointArn:expectString(output[_APAc])}:null!=output[_A]?{And:de_MetricsAndOperator(output[_A],context2)}:{$unknown:Object.entries(output)[0]};de_MultipartUpload=(output,context2)=>{const contents={};null!=output[_UI]&&(contents[_UI]=expectString(output[_UI]));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_Ini]&&(contents[_Ini]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Ini])));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_In]&&(contents[_In]=de_Initiator(output[_In],context2));null!=output[_CA]&&(contents[_CA]=expectString(output[_CA]));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));return contents};de_MultipartUploadList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_MultipartUpload(entry,context2)));de_NoncurrentVersionExpiration=(output,context2)=>{const contents={};null!=output[_ND]&&(contents[_ND]=strictParseInt32(output[_ND]));null!=output[_NNV]&&(contents[_NNV]=strictParseInt32(output[_NNV]));return contents};de_NoncurrentVersionTransition=(output,context2)=>{const contents={};null!=output[_ND]&&(contents[_ND]=strictParseInt32(output[_ND]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_NNV]&&(contents[_NNV]=strictParseInt32(output[_NNV]));return contents};de_NoncurrentVersionTransitionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_NoncurrentVersionTransition(entry)));de_NotificationConfigurationFilter=(output,context2)=>{const contents={};null!=output[_SKe]&&(contents[_K]=de_S3KeyFilter(output[_SKe],context2));return contents};de__Object=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));""===output.ChecksumAlgorithm?contents[_CA]=[]:null!=output[_CA]&&(contents[_CA]=de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_RSe]&&(contents[_RSe]=de_RestoreStatus(output[_RSe],context2));return contents};de_ObjectList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de__Object(entry,context2)));de_ObjectLockConfiguration=(output,context2)=>{const contents={};null!=output[_OLE]&&(contents[_OLE]=expectString(output[_OLE]));null!=output[_Ru]&&(contents[_Ru]=de_ObjectLockRule(output[_Ru],context2));return contents};de_ObjectLockLegalHold=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ObjectLockRetention=(output,context2)=>{const contents={};null!=output[_Mo]&&(contents[_Mo]=expectString(output[_Mo]));null!=output[_RUD]&&(contents[_RUD]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_RUD])));return contents};de_ObjectLockRule=(output,context2)=>{const contents={};null!=output[_DRe]&&(contents[_DRe]=de_DefaultRetention(output[_DRe]));return contents};de_ObjectPart=(output,context2)=>{const contents={};null!=output[_PN]&&(contents[_PN]=strictParseInt32(output[_PN]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_ObjectVersion=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));""===output.ChecksumAlgorithm?contents[_CA]=[]:null!=output[_CA]&&(contents[_CA]=de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_IL]&&(contents[_IL]=parseBoolean(output[_IL]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_RSe]&&(contents[_RSe]=de_RestoreStatus(output[_RSe],context2));return contents};de_ObjectVersionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ObjectVersion(entry,context2)));de_Owner=(output,context2)=>{const contents={};null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));return contents};de_OwnershipControls=(output,context2)=>{const contents={};""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_OwnershipControlsRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_OwnershipControlsRule=(output,context2)=>{const contents={};null!=output[_OO]&&(contents[_OO]=expectString(output[_OO]));return contents};de_OwnershipControlsRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_OwnershipControlsRule(entry)));de_Part=(output,context2)=>{const contents={};null!=output[_PN]&&(contents[_PN]=strictParseInt32(output[_PN]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_PartitionedPrefix=(output,context2)=>{const contents={};null!=output[_PDS]&&(contents[_PDS]=expectString(output[_PDS]));return contents};de_Parts=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Part(entry)));de_PartsList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ObjectPart(entry)));de_PolicyStatus=(output,context2)=>{const contents={};null!=output[_IP]&&(contents[_IP]=parseBoolean(output[_IP]));return contents};de_Progress=(output,context2)=>{const contents={};null!=output[_BS]&&(contents[_BS]=strictParseLong(output[_BS]));null!=output[_BP]&&(contents[_BP]=strictParseLong(output[_BP]));null!=output[_BRy]&&(contents[_BRy]=strictParseLong(output[_BRy]));return contents};de_PublicAccessBlockConfiguration=(output,context2)=>{const contents={};null!=output[_BPA]&&(contents[_BPA]=parseBoolean(output[_BPA]));null!=output[_IPA]&&(contents[_IPA]=parseBoolean(output[_IPA]));null!=output[_BPP]&&(contents[_BPP]=parseBoolean(output[_BPP]));null!=output[_RPB]&&(contents[_RPB]=parseBoolean(output[_RPB]));return contents};de_QueueConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_Qu]&&(contents[_QA]=expectString(output[_Qu]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_QueueConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_QueueConfiguration(entry,context2)));de_Redirect=(output,context2)=>{const contents={};null!=output[_HN]&&(contents[_HN]=expectString(output[_HN]));null!=output[_HRC]&&(contents[_HRC]=expectString(output[_HRC]));null!=output[_Pr]&&(contents[_Pr]=expectString(output[_Pr]));null!=output[_RKPW]&&(contents[_RKPW]=expectString(output[_RKPW]));null!=output[_RKW]&&(contents[_RKW]=expectString(output[_RKW]));return contents};de_RedirectAllRequestsTo=(output,context2)=>{const contents={};null!=output[_HN]&&(contents[_HN]=expectString(output[_HN]));null!=output[_Pr]&&(contents[_Pr]=expectString(output[_Pr]));return contents};de_ReplicaModifications=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ReplicationConfiguration=(output,context2)=>{const contents={};null!=output[_Ro]&&(contents[_Ro]=expectString(output[_Ro]));""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_ReplicationRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_ReplicationRule=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_Pri]&&(contents[_Pri]=strictParseInt32(output[_Pri]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_F]&&(contents[_F]=de_ReplicationRuleFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_SSC]&&(contents[_SSC]=de_SourceSelectionCriteria(output[_SSC],context2));null!=output[_EOR]&&(contents[_EOR]=de_ExistingObjectReplication(output[_EOR]));null!=output[_Des]&&(contents[_Des]=de_Destination(output[_Des],context2));null!=output[_DMR]&&(contents[_DMR]=de_DeleteMarkerReplication(output[_DMR]));return contents};de_ReplicationRuleAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_ReplicationRuleFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_A]&&(contents[_A]=de_ReplicationRuleAndOperator(output[_A],context2));return contents};de_ReplicationRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ReplicationRule(entry,context2)));de_ReplicationTime=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_Tim]&&(contents[_Tim]=de_ReplicationTimeValue(output[_Tim],context2));return contents};de_ReplicationTimeValue=(output,context2)=>{const contents={};null!=output[_Mi]&&(contents[_Mi]=strictParseInt32(output[_Mi]));return contents};de_RestoreStatus=(output,context2)=>{const contents={};null!=output[_IRIP]&&(contents[_IRIP]=parseBoolean(output[_IRIP]));null!=output[_RED]&&(contents[_RED]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_RED])));return contents};de_RoutingRule=(output,context2)=>{const contents={};null!=output[_Con]&&(contents[_Con]=de_Condition(output[_Con]));null!=output[_Red]&&(contents[_Red]=de_Redirect(output[_Red]));return contents};de_RoutingRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_RoutingRule(entry)));de_S3KeyFilter=(output,context2)=>{const contents={};""===output.FilterRule?contents[_FRi]=[]:null!=output[_FR]&&(contents[_FRi]=de_FilterRuleList(getArrayIfSingleItem(output[_FR])));return contents};de_S3TablesDestinationResult=(output,context2)=>{const contents={};null!=output[_TBA]&&(contents[_TBA]=expectString(output[_TBA]));null!=output[_TN]&&(contents[_TN]=expectString(output[_TN]));null!=output[_TAa]&&(contents[_TAa]=expectString(output[_TAa]));null!=output[_TNa]&&(contents[_TNa]=expectString(output[_TNa]));return contents};de_ServerSideEncryptionByDefault=(output,context2)=>{const contents={};null!=output[_SSEA]&&(contents[_SSEA]=expectString(output[_SSEA]));null!=output[_KMSMKID]&&(contents[_KMSMKID]=expectString(output[_KMSMKID]));return contents};de_ServerSideEncryptionConfiguration=(output,context2)=>{const contents={};""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_ServerSideEncryptionRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_ServerSideEncryptionRule=(output,context2)=>{const contents={};null!=output[_ASSEBD]&&(contents[_ASSEBD]=de_ServerSideEncryptionByDefault(output[_ASSEBD]));null!=output[_BKE]&&(contents[_BKE]=parseBoolean(output[_BKE]));return contents};de_ServerSideEncryptionRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ServerSideEncryptionRule(entry)));de_SessionCredentials=(output,context2)=>{const contents={};null!=output[_AKI]&&(contents[_AKI]=expectString(output[_AKI]));null!=output[_SAK]&&(contents[_SAK]=expectString(output[_SAK]));null!=output[_ST]&&(contents[_ST]=expectString(output[_ST]));null!=output[_Exp]&&(contents[_Exp]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Exp])));return contents};de_SourceSelectionCriteria=(output,context2)=>{const contents={};null!=output[_SKEO]&&(contents[_SKEO]=de_SseKmsEncryptedObjects(output[_SKEO],context2));null!=output[_RM]&&(contents[_RM]=de_ReplicaModifications(output[_RM]));return contents};de_SSEKMS=(output,context2)=>{const contents={};null!=output[_KI]&&(contents[_KI]=expectString(output[_KI]));return contents};de_SseKmsEncryptedObjects=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_SSES3=(output,context2)=>({});de_Stats=(output,context2)=>{const contents={};null!=output[_BS]&&(contents[_BS]=strictParseLong(output[_BS]));null!=output[_BP]&&(contents[_BP]=strictParseLong(output[_BP]));null!=output[_BRy]&&(contents[_BRy]=strictParseLong(output[_BRy]));return contents};de_StorageClassAnalysis=(output,context2)=>{const contents={};null!=output[_DE]&&(contents[_DE]=de_StorageClassAnalysisDataExport(output[_DE],context2));return contents};de_StorageClassAnalysisDataExport=(output,context2)=>{const contents={};null!=output[_OSV]&&(contents[_OSV]=expectString(output[_OSV]));null!=output[_Des]&&(contents[_Des]=de_AnalyticsExportDestination(output[_Des],context2));return contents};de_Tag=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_Va]&&(contents[_Va]=expectString(output[_Va]));return contents};de_TagSet=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Tag(entry,context2)));de_TargetGrant=(output,context2)=>{const contents={};null!=output[_Gra]&&(contents[_Gra]=de_Grantee(output[_Gra],context2));null!=output[_Pe]&&(contents[_Pe]=expectString(output[_Pe]));return contents};de_TargetGrants=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_TargetGrant(entry,context2)));de_TargetObjectKeyFormat=(output,context2)=>{const contents={};null!=output[_SPi]&&(contents[_SPi]=(output[_SPi],{}));null!=output[_PP]&&(contents[_PP]=de_PartitionedPrefix(output[_PP]));return contents};de_Tiering=(output,context2)=>{const contents={};null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_AT]&&(contents[_AT]=expectString(output[_AT]));return contents};de_TieringList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Tiering(entry)));de_TopicConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_Top]&&(contents[_TA]=expectString(output[_Top]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_TopicConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_TopicConfiguration(entry,context2)));de_Transition=(output,context2)=>{const contents={};null!=output[_Dat]&&(contents[_Dat]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat])));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));return contents};de_TransitionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Transition(entry)));deserializeMetadata2=output=>{var _a8,_b4;return{httpStatusCode:output.statusCode,requestId:null!=(_b4=null!=(_a8=output.headers["x-amzn-requestid"])?_a8:output.headers["x-amzn-request-id"])?_b4:output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]}};collectBodyString2=(streamBody,context2)=>collectBody(streamBody,context2).then((body=>context2.utf8Encoder(body)));_A="And";_AAO="AnalyticsAndOperator";_AC="AnalyticsConfiguration";_ACL="ACL";_ACLc="AccessControlList";_ACLn="AnalyticsConfigurationList";_ACP="AccessControlPolicy";_ACT="AccessControlTranslation";_ACc="AccelerateConfiguration";_AD="AbortDate";_AED="AnalyticsExportDestination";_AF="AnalyticsFilter";_AH="AllowedHeader";_AHl="AllowedHeaders";_AI="AnalyticsId";_AIMU="AbortIncompleteMultipartUpload";_AIc="AccountId";_AKI="AccessKeyId";_AM="AllowedMethod";_AMl="AllowedMethods";_AO="AllowedOrigin";_AOl="AllowedOrigins";_APA="AccessPointAlias";_APAc="AccessPointArn";_AQRD="AllowQuotedRecordDelimiter";_AR="AcceptRanges";_ARI="AbortRuleId";_AS="ArchiveStatus";_ASBD="AnalyticsS3BucketDestination";_ASEFF="AnalyticsS3ExportFileFormat";_ASSEBD="ApplyServerSideEncryptionByDefault";_AT="AccessTier";_Ac="Account";_B="Bucket";_BAI="BucketAccountId";_BAS="BucketAccelerateStatus";_BGR="BypassGovernanceRetention";_BI="BucketInfo";_BKE="BucketKeyEnabled";_BLC="BucketLifecycleConfiguration";_BLCu="BucketLocationConstraint";_BLN="BucketLocationName";_BLP="BucketLogsPermission";_BLS="BucketLoggingStatus";_BLT="BucketLocationType";_BN="BucketName";_BP="BytesProcessed";_BPA="BlockPublicAcls";_BPP="BlockPublicPolicy";_BR="BucketRegion";_BRy="BytesReturned";_BS="BytesScanned";_BT="BucketType";_BVS="BucketVersioningStatus";_Bu="Buckets";_C="Credentials";_CA="ChecksumAlgorithm";_CACL="CannedACL";_CBC="CreateBucketConfiguration";_CC="CacheControl";_CCRC="ChecksumCRC32";_CCRCC="ChecksumCRC32C";_CCRCNVME="ChecksumCRC64NVME";_CD="ContentDisposition";_CDr="CreationDate";_CE="ContentEncoding";_CF="CloudFunction";_CFC="CloudFunctionConfiguration";_CL="ContentLanguage";_CLo="ContentLength";_CM="ChecksumMode";_CMD="ContentMD5";_CMU="CompletedMultipartUpload";_CORSC="CORSConfiguration";_CORSR="CORSRule";_CORSRu="CORSRules";_CP="CommonPrefixes";_CPo="CompletedPart";_CR="ContentRange";_CRSBA="ConfirmRemoveSelfBucketAccess";_CS="CopySource";_CSHA="ChecksumSHA1";_CSHAh="ChecksumSHA256";_CSIM="CopySourceIfMatch";_CSIMS="CopySourceIfModifiedSince";_CSINM="CopySourceIfNoneMatch";_CSIUS="CopySourceIfUnmodifiedSince";_CSR="CopySourceRange";_CSSSECA="CopySourceSSECustomerAlgorithm";_CSSSECK="CopySourceSSECustomerKey";_CSSSECKMD="CopySourceSSECustomerKeyMD5";_CSV="CSV";_CSVI="CopySourceVersionId";_CSVIn="CSVInput";_CSVO="CSVOutput";_CT="ChecksumType";_CTo="ContentType";_CTom="CompressionType";_CTon="ContinuationToken";_Ch="Checksum";_Co="Contents";_Cod="Code";_Com="Comments";_Con="Condition";_D="Delimiter";_DAI="DaysAfterInitiation";_DE="DataExport";_DM="DeleteMarker";_DMR="DeleteMarkerReplication";_DMRS="DeleteMarkerReplicationStatus";_DMVI="DeleteMarkerVersionId";_DMe="DeleteMarkers";_DN="DisplayName";_DR="DataRedundancy";_DRe="DefaultRetention";_Da="Days";_Dat="Date";_De="Deleted";_Del="Delete";_Des="Destination";_Desc="Description";_E="Expires";_EA="EmailAddress";_EBC="EventBridgeConfiguration";_EBO="ExpectedBucketOwner";_EC="ErrorCode";_ECn="EncryptionConfiguration";_ED="ErrorDocument";_EH="ExposeHeaders";_EHx="ExposeHeader";_EM="ErrorMessage";_EODM="ExpiredObjectDeleteMarker";_EOR="ExistingObjectReplication";_EORS="ExistingObjectReplicationStatus";_ERP="EnableRequestProgress";_ES="ExpiresString";_ESBO="ExpectedSourceBucketOwner";_ESx="ExpirationStatus";_ET="EncodingType";_ETa="ETag";_ETn="EncryptionType";_ETv="EventThreshold";_ETx="ExpressionType";_En="Encryption";_Ena="Enabled";_End="End";_Er="Error";_Err="Errors";_Ev="Event";_Eve="Events";_Ex="Expression";_Exp="Expiration";_F="Filter";_FD="FieldDelimiter";_FHI="FileHeaderInfo";_FO="FetchOwner";_FR="FilterRule";_FRN="FilterRuleName";_FRV="FilterRuleValue";_FRi="FilterRules";_Fi="Field";_Fo="Format";_Fr="Frequency";_G="Grant";_GFC="GrantFullControl";_GJP="GlacierJobParameters";_GR="GrantRead";_GRACP="GrantReadACP";_GW="GrantWrite";_GWACP="GrantWriteACP";_Gr="Grants";_Gra="Grantee";_HECRE="HttpErrorCodeReturnedEquals";_HN="HostName";_HRC="HttpRedirectCode";_I="Id";_IC="InventoryConfiguration";_ICL="InventoryConfigurationList";_ID="IndexDocument";_ID_="ID";_IDn="InventoryDestination";_IE="IsEnabled";_IEn="InventoryEncryption";_IF="InventoryFilter";_IFn="InventoryFormat";_IFnv="InventoryFrequency";_II="InventoryId";_IIOV="InventoryIncludedObjectVersions";_IL="IsLatest";_IM="IfMatch";_IMIT="IfMatchInitiatedTime";_IMLMT="IfMatchLastModifiedTime";_IMS="IfMatchSize";_IMSf="IfModifiedSince";_INM="IfNoneMatch";_IOF="InventoryOptionalField";_IOV="IncludedObjectVersions";_IP="IsPublic";_IPA="IgnorePublicAcls";_IRIP="IsRestoreInProgress";_IS="InputSerialization";_ISBD="InventoryS3BucketDestination";_ISn="InventorySchedule";_IT="IsTruncated";_ITAO="IntelligentTieringAndOperator";_ITAT="IntelligentTieringAccessTier";_ITC="IntelligentTieringConfiguration";_ITCL="IntelligentTieringConfigurationList";_ITD="IntelligentTieringDays";_ITF="IntelligentTieringFilter";_ITI="IntelligentTieringId";_ITS="IntelligentTieringStatus";_IUS="IfUnmodifiedSince";_In="Initiator";_Ini="Initiated";_JSON="JSON";_JSONI="JSONInput";_JSONO="JSONOutput";_JSONT="JSONType";_K="Key";_KC="KeyCount";_KI="KeyId";_KM="KeyMarker";_KMSC="KMSContext";_KMSKI="KMSKeyId";_KMSMKID="KMSMasterKeyID";_KPE="KeyPrefixEquals";_L="Location";_LC="LocationConstraint";_LE="LoggingEnabled";_LEi="LifecycleExpiration";_LFA="LambdaFunctionArn";_LFC="LambdaFunctionConfigurations";_LFCa="LambdaFunctionConfiguration";_LI="LocationInfo";_LM="LastModified";_LMT="LastModifiedTime";_LNAS="LocationNameAsString";_LP="LocationPrefix";_LR="LifecycleRule";_LRAO="LifecycleRuleAndOperator";_LRF="LifecycleRuleFilter";_LT="LocationType";_M="Marker";_MAO="MetricsAndOperator";_MAS="MaxAgeSeconds";_MB="MaxBuckets";_MC="MetricsConfiguration";_MCL="MetricsConfigurationList";_MD="MetadataDirective";_MDB="MaxDirectoryBuckets";_MDf="MfaDelete";_ME="MetadataEntry";_MF="MetricsFilter";_MFA="MFA";_MFAD="MFADelete";_MI="MetricsId";_MK="MaxKeys";_MKe="MetadataKey";_MM="MissingMeta";_MOS="MpuObjectSize";_MP="MaxParts";_MS="MetricsStatus";_MTC="MetadataTableConfiguration";_MTCR="MetadataTableConfigurationResult";_MU="MaxUploads";_MV="MetadataValue";_Me="Metrics";_Mes="Message";_Mi="Minutes";_Mo="Mode";_N="Name";_NC="NotificationConfiguration";_NCF="NotificationConfigurationFilter";_NCT="NextContinuationToken";_ND="NoncurrentDays";_NI="NotificationId";_NKM="NextKeyMarker";_NM="NextMarker";_NNV="NewerNoncurrentVersions";_NPNM="NextPartNumberMarker";_NUIM="NextUploadIdMarker";_NVE="NoncurrentVersionExpiration";_NVIM="NextVersionIdMarker";_NVT="NoncurrentVersionTransitions";_NVTo="NoncurrentVersionTransition";_O="Owner";_OA="ObjectAttributes";_OC="OwnershipControls";_OCACL="ObjectCannedACL";_OCR="OwnershipControlsRule";_OF="OptionalFields";_OI="ObjectIdentifier";_OK="ObjectKey";_OL="OutputLocation";_OLC="ObjectLockConfiguration";_OLE="ObjectLockEnabled";_OLEFB="ObjectLockEnabledForBucket";_OLLH="ObjectLockLegalHold";_OLLHS="ObjectLockLegalHoldStatus";_OLM="ObjectLockMode";_OLR="ObjectLockRetention";_OLRM="ObjectLockRetentionMode";_OLRUD="ObjectLockRetainUntilDate";_OLRb="ObjectLockRule";_OO="ObjectOwnership";_OOA="OptionalObjectAttributes";_OOw="OwnerOverride";_OP="ObjectParts";_OS="OutputSerialization";_OSGT="ObjectSizeGreaterThan";_OSGTB="ObjectSizeGreaterThanBytes";_OSLT="ObjectSizeLessThan";_OSLTB="ObjectSizeLessThanBytes";_OSV="OutputSchemaVersion";_OSb="ObjectSize";_OVI="ObjectVersionId";_Ob="Objects";_P="Prefix";_PABC="PublicAccessBlockConfiguration";_PC="PartsCount";_PDS="PartitionDateSource";_PI="ParquetInput";_PN="PartNumber";_PNM="PartNumberMarker";_PP="PartitionedPrefix";_Pa="Payer";_Par="Part";_Parq="Parquet";_Part="Parts";_Pe="Permission";_Pr="Protocol";_Pri="Priority";_Q="Quiet";_QA="QueueArn";_QC="QueueConfiguration";_QCu="QueueConfigurations";_QCuo="QuoteCharacter";_QEC="QuoteEscapeCharacter";_QF="QuoteFields";_Qu="Queue";_R="Range";_RART="RedirectAllRequestsTo";_RC="RequestCharged";_RCC="ResponseCacheControl";_RCD="ResponseContentDisposition";_RCE="ResponseContentEncoding";_RCL="ResponseContentLanguage";_RCT="ResponseContentType";_RCe="ReplicationConfiguration";_RD="RecordDelimiter";_RE="ResponseExpires";_RED="RestoreExpiryDate";_RKKID="ReplicaKmsKeyID";_RKPW="ReplaceKeyPrefixWith";_RKW="ReplaceKeyWith";_RM="ReplicaModifications";_RMS="ReplicaModificationsStatus";_ROP="RestoreOutputPath";_RP="RequestPayer";_RPB="RestrictPublicBuckets";_RPC="RequestPaymentConfiguration";_RPe="RequestProgress";_RR="RequestRoute";_RRAO="ReplicationRuleAndOperator";_RRF="ReplicationRuleFilter";_RRS="ReplicationRuleStatus";_RRT="RestoreRequestType";_RRe="ReplicationRule";_RRes="RestoreRequest";_RRo="RoutingRules";_RRou="RoutingRule";_RS="ReplicationStatus";_RSe="RestoreStatus";_RT="RequestToken";_RTS="ReplicationTimeStatus";_RTV="ReplicationTimeValue";_RTe="ReplicationTime";_RUD="RetainUntilDate";_Re="Restore";_Red="Redirect";_Ro="Role";_Ru="Rule";_Rul="Rules";_S="Status";_SA="StartAfter";_SAK="SecretAccessKey";_SBD="S3BucketDestination";_SC="StorageClass";_SCA="StorageClassAnalysis";_SCADE="StorageClassAnalysisDataExport";_SCASV="StorageClassAnalysisSchemaVersion";_SCt="StatusCode";_SDV="SkipDestinationValidation";_SK="SSE-KMS";_SKEO="SseKmsEncryptedObjects";_SKEOS="SseKmsEncryptedObjectsStatus";_SKF="S3KeyFilter";_SKe="S3Key";_SL="S3Location";_SM="SessionMode";_SOCR="SelectObjectContentRequest";_SP="SelectParameters";_SPi="SimplePrefix";_SR="ScanRange";_SS="SSE-S3";_SSC="SourceSelectionCriteria";_SSE="ServerSideEncryption";_SSEA="SSEAlgorithm";_SSEBD="ServerSideEncryptionByDefault";_SSEC="ServerSideEncryptionConfiguration";_SSECA="SSECustomerAlgorithm";_SSECK="SSECustomerKey";_SSECKMD="SSECustomerKeyMD5";_SSEKMS="SSEKMS";_SSEKMSEC="SSEKMSEncryptionContext";_SSEKMSKI="SSEKMSKeyId";_SSER="ServerSideEncryptionRule";_SSES="SSES3";_ST="SessionToken";_STBA="S3TablesBucketArn";_STD="S3TablesDestination";_STDR="S3TablesDestinationResult";_STN="S3TablesName";_S_="S3";_Sc="Schedule";_Se="Setting";_Si="Size";_St="Start";_Su="Suffix";_T="Tagging";_TA="TopicArn";_TAa="TableArn";_TB="TargetBucket";_TBA="TableBucketArn";_TC="TagCount";_TCo="TopicConfiguration";_TCop="TopicConfigurations";_TD="TaggingDirective";_TDMOS="TransitionDefaultMinimumObjectSize";_TG="TargetGrants";_TGa="TargetGrant";_TN="TableName";_TNa="TableNamespace";_TOKF="TargetObjectKeyFormat";_TP="TargetPrefix";_TPC="TotalPartsCount";_TS="TagSet";_TSC="TransitionStorageClass";_Ta="Tag";_Tag="Tags";_Ti="Tier";_Tie="Tierings";_Tier="Tiering";_Tim="Time";_To="Token";_Top="Topic";_Tr="Transitions";_Tra="Transition";_Ty="Type";_U="Upload";_UI="UploadId";_UIM="UploadIdMarker";_UM="UserMetadata";_URI="URI";_Up="Uploads";_V="Version";_VC="VersionCount";_VCe="VersioningConfiguration";_VI="VersionId";_VIM="VersionIdMarker";_Va="Value";_Ve="Versions";_WC="WebsiteConfiguration";_WOB="WriteOffsetBytes";_WRL="WebsiteRedirectLocation";_Y="Years";_a6="analytics";_ac="accelerate";_acl="acl";_ar="accept-ranges";_at="attributes";_br="bucket-region";_c2="cors";_cc="cache-control";_cd="content-disposition";_ce="content-encoding";_cl="content-language";_cl_="content-length";_cm="content-md5";_cr="content-range";_ct="content-type";_ct_="continuation-token";_d="delete";_de="delimiter";_e="expires";_en="encryption";_et="encoding-type";_eta="etag";_ex="expiresstring";_fo="fetch-owner";_i="id";_im="if-match";_ims="if-modified-since";_in="inventory";_inm="if-none-match";_it="intelligent-tiering";_ius="if-unmodified-since";_km="key-marker";_l="lifecycle";_lh="legal-hold";_lm="last-modified";_lo="location";_log="logging";_lt="list-type";_m="metrics";_mT="metadataTable";_ma="marker";_mb="max-buckets";_mdb="max-directory-buckets";_me="member";_mk="max-keys";_mp="max-parts";_mu="max-uploads";_n="notification";_oC="ownershipControls";_ol="object-lock";_p="policy";_pAB="publicAccessBlock";_pN="partNumber";_pS="policyStatus";_pnm="part-number-marker";_pr="prefix";_r="replication";_rP="requestPayment";_ra="range";_rcc="response-cache-control";_rcd="response-content-disposition";_rce="response-content-encoding";_rcl="response-content-language";_rct="response-content-type";_re="response-expires";_res="restore";_ret="retention";_s="session";_sa="start-after";_se="select";_st="select-type";_t="tagging";_to="torrent";_u="uploads";_uI="uploadId";_uim="upload-id-marker";_v="versioning";_vI="versionId";_ve='';_ver="versions";_vim="version-id-marker";_w="website";_x="xsi:type";_xaa="x-amz-acl";_xaad="x-amz-abort-date";_xaapa="x-amz-access-point-alias";_xaari="x-amz-abort-rule-id";_xaas="x-amz-archive-status";_xabgr="x-amz-bypass-governance-retention";_xabln="x-amz-bucket-location-name";_xablt="x-amz-bucket-location-type";_xabole="x-amz-bucket-object-lock-enabled";_xabolt="x-amz-bucket-object-lock-token";_xabr="x-amz-bucket-region";_xaca="x-amz-checksum-algorithm";_xacc="x-amz-checksum-crc32";_xacc_="x-amz-checksum-crc32c";_xacc__="x-amz-checksum-crc64nvme";_xacm="x-amz-checksum-mode";_xacrsba="x-amz-confirm-remove-self-bucket-access";_xacs="x-amz-checksum-sha1";_xacs_="x-amz-checksum-sha256";_xacs__="x-amz-copy-source";_xacsim="x-amz-copy-source-if-match";_xacsims="x-amz-copy-source-if-modified-since";_xacsinm="x-amz-copy-source-if-none-match";_xacsius="x-amz-copy-source-if-unmodified-since";_xacsm="x-amz-create-session-mode";_xacsr="x-amz-copy-source-range";_xacssseca="x-amz-copy-source-server-side-encryption-customer-algorithm";_xacssseck="x-amz-copy-source-server-side-encryption-customer-key";_xacssseckm="x-amz-copy-source-server-side-encryption-customer-key-md5";_xacsvi="x-amz-copy-source-version-id";_xact="x-amz-checksum-type";_xadm="x-amz-delete-marker";_xae="x-amz-expiration";_xaebo="x-amz-expected-bucket-owner";_xafec="x-amz-fwd-error-code";_xafem="x-amz-fwd-error-message";_xafhar="x-amz-fwd-header-accept-ranges";_xafhcc="x-amz-fwd-header-cache-control";_xafhcd="x-amz-fwd-header-content-disposition";_xafhce="x-amz-fwd-header-content-encoding";_xafhcl="x-amz-fwd-header-content-language";_xafhcr="x-amz-fwd-header-content-range";_xafhct="x-amz-fwd-header-content-type";_xafhe="x-amz-fwd-header-etag";_xafhe_="x-amz-fwd-header-expires";_xafhlm="x-amz-fwd-header-last-modified";_xafhxacc="x-amz-fwd-header-x-amz-checksum-crc32";_xafhxacc_="x-amz-fwd-header-x-amz-checksum-crc32c";_xafhxacc__="x-amz-fwd-header-x-amz-checksum-crc64nvme";_xafhxacs="x-amz-fwd-header-x-amz-checksum-sha1";_xafhxacs_="x-amz-fwd-header-x-amz-checksum-sha256";_xafhxadm="x-amz-fwd-header-x-amz-delete-marker";_xafhxae="x-amz-fwd-header-x-amz-expiration";_xafhxamm="x-amz-fwd-header-x-amz-missing-meta";_xafhxampc="x-amz-fwd-header-x-amz-mp-parts-count";_xafhxaollh="x-amz-fwd-header-x-amz-object-lock-legal-hold";_xafhxaolm="x-amz-fwd-header-x-amz-object-lock-mode";_xafhxaolrud="x-amz-fwd-header-x-amz-object-lock-retain-until-date";_xafhxar="x-amz-fwd-header-x-amz-restore";_xafhxarc="x-amz-fwd-header-x-amz-request-charged";_xafhxars="x-amz-fwd-header-x-amz-replication-status";_xafhxasc="x-amz-fwd-header-x-amz-storage-class";_xafhxasse="x-amz-fwd-header-x-amz-server-side-encryption";_xafhxasseakki="x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id";_xafhxassebke="x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled";_xafhxasseca="x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm";_xafhxasseckm="x-amz-fwd-header-x-amz-server-side-encryption-customer-key-md5";_xafhxatc="x-amz-fwd-header-x-amz-tagging-count";_xafhxavi="x-amz-fwd-header-x-amz-version-id";_xafs="x-amz-fwd-status";_xagfc="x-amz-grant-full-control";_xagr="x-amz-grant-read";_xagra="x-amz-grant-read-acp";_xagw="x-amz-grant-write";_xagwa="x-amz-grant-write-acp";_xaimit="x-amz-if-match-initiated-time";_xaimlmt="x-amz-if-match-last-modified-time";_xaims="x-amz-if-match-size";_xam="x-amz-mfa";_xamd="x-amz-metadata-directive";_xamm="x-amz-missing-meta";_xamos="x-amz-mp-object-size";_xamp="x-amz-max-parts";_xampc="x-amz-mp-parts-count";_xaoa="x-amz-object-attributes";_xaollh="x-amz-object-lock-legal-hold";_xaolm="x-amz-object-lock-mode";_xaolrud="x-amz-object-lock-retain-until-date";_xaoo="x-amz-object-ownership";_xaooa="x-amz-optional-object-attributes";_xaos="x-amz-object-size";_xapnm="x-amz-part-number-marker";_xar="x-amz-restore";_xarc="x-amz-request-charged";_xarop="x-amz-restore-output-path";_xarp="x-amz-request-payer";_xarr="x-amz-request-route";_xars="x-amz-replication-status";_xart="x-amz-request-token";_xasc="x-amz-storage-class";_xasca="x-amz-sdk-checksum-algorithm";_xasdv="x-amz-skip-destination-validation";_xasebo="x-amz-source-expected-bucket-owner";_xasse="x-amz-server-side-encryption";_xasseakki="x-amz-server-side-encryption-aws-kms-key-id";_xassebke="x-amz-server-side-encryption-bucket-key-enabled";_xassec="x-amz-server-side-encryption-context";_xasseca="x-amz-server-side-encryption-customer-algorithm";_xasseck="x-amz-server-side-encryption-customer-key";_xasseckm="x-amz-server-side-encryption-customer-key-md5";_xat="x-amz-tagging";_xatc="x-amz-tagging-count";_xatd="x-amz-tagging-directive";_xatdmos="x-amz-transition-default-minimum-object-size";_xavi="x-amz-version-id";_xawob="x-amz-write-offset-bytes";_xawrl="x-amz-website-redirect-location";_xi="x-id";CreateSessionCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(CreateSessionRequestFilterSensitiveLog,CreateSessionOutputFilterSensitiveLog).ser(se_CreateSessionCommand).de(de_CreateSessionCommand).build()){};fromUtf84=input=>(new TextEncoder).encode(input);SHA_1_HMAC_ALGO={name:"HMAC",hash:SHA_1_HASH={name:"SHA-1"}};EMPTY_DATA_SHA_1=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);fallbackWindow={};Sha1=function(){function Sha13(secret){this.toHash=new Uint8Array(0);if(void 0!==secret){this.key=new Promise((function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer2(secret),SHA_1_HMAC_ALGO,!1,["sign"]).then(resolve,reject)}));this.key.catch((function(){}))}}Sha13.prototype.update=function(data){var update2,typedArray;if(!isEmptyData2(data)){update2=convertToBuffer2(data);(typedArray=new Uint8Array(this.toHash.byteLength+update2.byteLength)).set(this.toHash,0);typedArray.set(update2,this.toHash.byteLength);this.toHash=typedArray}};Sha13.prototype.digest=function(){var _this=this;return this.key?this.key.then((function(key2){return locateWindow().crypto.subtle.sign(SHA_1_HMAC_ALGO,key2,_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(key2){return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO,key2,_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}();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(64===this.bufferLength){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%64>=56){for(i2=this.bufferLength;i2<64;i2++)bufferView.setUint8(i2,0);this.hashBuffer();this.bufferLength=0}for(i2=this.bufferLength;i2<56;i2++)bufferView.setUint8(i2,0);bufferView.setUint32(56,Math.floor(bitsHashed/4294967296),!0);bufferView.setUint32(60,bitsHashed);this.hashBuffer();this.finished=!0}out=new Uint8Array(32);for(i2=0;i2<8;i2++){out[4*i2]=this.state[i2]>>>24&255;out[4*i2+1]=this.state[i2]>>>16&255;out[4*i2+2]=this.state[i2]>>>8&255;out[4*i2+3]=this.state[i2]>>>0&255}return out};RawSha2562.prototype.hashBuffer=function(){var i2,u2,t1_1,t2_1,t1,t22,buffer=this.buffer,state2=this.state,state0=state2[0],state1=state2[1],state22=state2[2],state3=state2[3],state4=state2[4],state5=state2[5],state6=state2[6],state7=state2[7];for(i2=0;i2<64;i2++){if(i2<16)this.temp[i2]=(255&buffer[4*i2])<<24|(255&buffer[4*i2+1])<<16|(255&buffer[4*i2+2])<<8|255&buffer[4*i2+3];else{t1_1=((u2=this.temp[i2-2])>>>17|u2<<15)^(u2>>>19|u2<<13)^u2>>>10;t2_1=((u2=this.temp[i2-15])>>>7|u2<<25)^(u2>>>18|u2<<14)^u2>>>3;this.temp[i2]=(t1_1+this.temp[i2-7]|0)+(t2_1+this.temp[i2-16]|0)}t1=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i2]+this.temp[i2]|0)|0)|0;t22=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state22^state1&state22)|0;state7=state6;state6=state5;state5=state4;state4=state3+t1|0;state3=state22;state22=state1;state1=state0;state0=t1+t22|0}state2[0]+=state0;state2[1]+=state1;state2[2]+=state22;state2[3]+=state3;state2[4]+=state4;state2[5]+=state5;state2[6]+=state6;state2[7]+=state7};return RawSha2562}();Sha2562=function(){function Sha2564(secret){this.secret=secret;this.hash=new RawSha256;this.reset()}Sha2564.prototype.update=function(toHash){if(!isEmptyData(toHash)&&!this.error)try{this.hash.update(convertToBuffer(toHash))}catch(e3){this.error=e3}};Sha2564.prototype.digestSync=function(){if(this.error)throw this.error;if(this.outer){this.outer.finished||this.outer.update(this.hash.digest());return this.outer.digest()}return this.hash.digest()};Sha2564.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,this.digestSync()]}))}))};Sha2564.prototype.reset=function(){var inner,outer,i2;this.hash=new RawSha256;if(this.secret){this.outer=new RawSha256;inner=function bufferFromSecret(secret){var bufferHash,buffer,input=convertToBuffer(secret);if(input.byteLength>64){(bufferHash=new RawSha256).update(input);input=bufferHash.digest()}(buffer=new Uint8Array(64)).set(input);return buffer}(this.secret);(outer=new Uint8Array(64)).set(inner);for(i2=0;i2<64;i2++){inner[i2]^=54;outer[i2]^=92}this.hash.update(inner);this.outer.update(outer);for(i2=0;i2async config=>{var _a8,_b4,_c3,_d2,_e2,_f,_g,_h;const parsedUA="undefined"!=typeof window&&(null==(_a8=null==window?void 0:window.navigator)?void 0:_a8.userAgent)?import_bowser.default.parse(window.navigator.userAgent):void 0,sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${(null==(_b4=null==parsedUA?void 0:parsedUA.os)?void 0:_b4.name)||"other"}`,null==(_c3=null==parsedUA?void 0:parsedUA.os)?void 0:_c3.version],["lang/js"],["md/browser",`${null!=(_e2=null==(_d2=null==parsedUA?void 0:parsedUA.browser)?void 0:_d2.name)?_e2:"unknown"}_${null!=(_g=null==(_f=null==parsedUA?void 0:parsedUA.browser)?void 0:_f.version)?_g:"unknown"}`]];serviceId&§ions.push([`api/${serviceId}`,clientVersion]);const appId=await(null==(_h=null==config?void 0:config.userAgentAppId)?void 0:_h.call(config));appId&§ions.push([`app/${appId}`]);return sections};Int642=class _Int64{constructor(bytes){this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i2=7,remaining=Math.abs(Math.round(number));i2>-1&&remaining>0;i2--,remaining/=256)bytes[i2]=remaining;number<0&&negate2(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate2(bytes);return parseInt(toHex2(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};HeaderMarshaller=class{constructor(toUtf82,fromUtf85){this.toUtf8=toUtf82;this.fromUtf8=fromUtf85}format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=this.fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce(((carry,bytes)=>carry+bytes.byteLength),0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=this.fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN2.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}parse(headers){const out={};let position=0;for(;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}=function splitMessage({byteLength,byteOffset,buffer}){if(byteLength<16)throw new Error("Provided message too short to accommodate event stream message overhead");const view=new DataView(buffer,byteOffset,byteLength),messageLength=view.getUint32(0,!1);if(byteLength!==messageLength)throw new Error("Reported message length does not match received message length");const headerLength=view.getUint32(4,!1),expectedPreludeChecksum=view.getUint32(8,!1),expectedMessageChecksum=view.getUint32(byteLength-4,!1),checksummer=(new Crc32).update(new Uint8Array(buffer,byteOffset,8));if(expectedPreludeChecksum!==checksummer.digest())throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);checksummer.update(new Uint8Array(buffer,byteOffset+8,byteLength-12));if(expectedMessageChecksum!==checksummer.digest())throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);return{headers:new DataView(buffer,byteOffset+8+4,headerLength),body:new Uint8Array(buffer,byteOffset+8+4+headerLength,messageLength-headerLength-16)}}(message);return{headers:this.headerMarshaller.parse(headers),body}}formatHeaders(rawHeaders){return this.headerMarshaller.format(rawHeaders)}};MessageDecoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const bytes of this.options.inputStream){const decoded=this.options.decoder.decode(bytes);yield decoded}}};MessageEncoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const msg of this.options.messageStream){const encoded=this.options.encoder.encode(msg);yield encoded}this.options.includeEndFrame&&(yield new Uint8Array(0))}};SmithyMessageDecoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const message of this.options.messageStream){const deserialized=await this.options.deserializer(message);void 0!==deserialized&&(yield deserialized)}}};SmithyMessageEncoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const chunk of this.options.inputStream){const payloadBuf=this.options.serializer(chunk);yield payloadBuf}}};EventStreamMarshaller=class{constructor({utf8Encoder,utf8Decoder}){this.eventStreamCodec=new EventStreamCodec(utf8Encoder,utf8Decoder);this.utfEncoder=utf8Encoder}deserialize(body,deserializer){const inputStream=function getChunkedStream(source2){let currentMessageTotalLength=0,currentMessagePendingLength=0,currentMessage=null,messageLengthBuffer=null;const allocateMessage=size=>{if("number"!=typeof size)throw new Error("Attempted to allocate an event message where size was not a number: "+size);currentMessageTotalLength=size;currentMessagePendingLength=4;currentMessage=new Uint8Array(size);new DataView(currentMessage.buffer).setUint32(0,size,!1)};return{[Symbol.asyncIterator]:async function*(){const sourceIterator=source2[Symbol.asyncIterator]();for(;;){const{value,done}=await sourceIterator.next();if(done){if(!currentMessageTotalLength)return;if(currentMessageTotalLength!==currentMessagePendingLength)throw new Error("Truncated event message received.");yield currentMessage;return}const chunkLength=value.length;let currentOffset=0;for(;currentOffset({[Symbol.asyncIterator]:async function*(){const reader=readableStream.getReader();try{for(;;){const{done,value}=await reader.read();if(done)return;yield value}}finally{reader.releaseLock()}}});iterableToReadableStream=asyncIterable=>{const iterator=asyncIterable[Symbol.asyncIterator]();return new ReadableStream({async pull(controller){const{done,value}=await iterator.next();if(done)return controller.close();controller.enqueue(value)}})};EventStreamMarshaller2=class{constructor({utf8Encoder,utf8Decoder}){this.universalMarshaller=new EventStreamMarshaller({utf8Decoder,utf8Encoder})}deserialize(body,deserializer){const bodyIterable=isReadableStream2(body)?readableStreamtoIterable(body):body;return this.universalMarshaller.deserialize(bodyIterable,deserializer)}serialize(input,serializer){const serialziedIterable=this.universalMarshaller.serialize(input,serializer);return"function"==typeof ReadableStream?iterableToReadableStream(serialziedIterable):serialziedIterable}};isReadableStream2=body=>"function"==typeof ReadableStream&&body instanceof ReadableStream;eventStreamSerdeProvider2=options=>new EventStreamMarshaller2(options);blobHasher=async function blobHasher2(hashCtor,blob){const hash2=new hashCtor;await async function blobReader(blob,onChunk,chunkSize2=1048576){const size=blob.size;let totalBytesRead=0;for(;totalBytesRead{hash2.update(chunk)}));return hash2.digest()};invalidProvider=message=>()=>Promise.reject(message);INIT2=[1732584193,4023233417,2562383102,271733878];Md5=class{constructor(){this.reset()}update(sourceData){if(function isEmptyData3(data){return"string"==typeof data?0===data.length:0===data.byteLength}(sourceData))return;if(this.finished)throw new Error("Attempted to update an already finished hash.");const data=function convertToBuffer3(data){return"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}(sourceData);let position=0,{byteLength}=data;this.bytesHashed+=byteLength;for(;byteLength>0;){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(64===this.bufferLength){this.hashBuffer();this.bufferLength=0}}}async digest(){if(!this.finished){const{buffer,bufferLength:undecoratedLength,bytesHashed}=this,bitsHashed=8*bytesHashed;buffer.setUint8(this.bufferLength++,128);if(undecoratedLength%64>=56){for(let i2=this.bufferLength;i2<64;i2++)buffer.setUint8(i2,0);this.hashBuffer();this.bufferLength=0}for(let i2=this.bufferLength;i2<56;i2++)buffer.setUint8(i2,0);buffer.setUint32(56,bitsHashed>>>0,!0);buffer.setUint32(60,Math.floor(bitsHashed/4294967296),!0);this.hashBuffer();this.finished=!0}const out=new DataView(new ArrayBuffer(16));for(let i2=0;i2<4;i2++)out.setUint32(4*i2,this.state[i2],!0);return new Uint8Array(out.buffer,out.byteOffset,out.byteLength)}hashBuffer(){const{buffer,state:state2}=this;let a2=state2[0],b3=state2[1],c3=state2[2],d4=state2[3];a2=ff(a2,b3,c3,d4,buffer.getUint32(0,!0),7,3614090360);d4=ff(d4,a2,b3,c3,buffer.getUint32(4,!0),12,3905402710);c3=ff(c3,d4,a2,b3,buffer.getUint32(8,!0),17,606105819);b3=ff(b3,c3,d4,a2,buffer.getUint32(12,!0),22,3250441966);a2=ff(a2,b3,c3,d4,buffer.getUint32(16,!0),7,4118548399);d4=ff(d4,a2,b3,c3,buffer.getUint32(20,!0),12,1200080426);c3=ff(c3,d4,a2,b3,buffer.getUint32(24,!0),17,2821735955);b3=ff(b3,c3,d4,a2,buffer.getUint32(28,!0),22,4249261313);a2=ff(a2,b3,c3,d4,buffer.getUint32(32,!0),7,1770035416);d4=ff(d4,a2,b3,c3,buffer.getUint32(36,!0),12,2336552879);c3=ff(c3,d4,a2,b3,buffer.getUint32(40,!0),17,4294925233);b3=ff(b3,c3,d4,a2,buffer.getUint32(44,!0),22,2304563134);a2=ff(a2,b3,c3,d4,buffer.getUint32(48,!0),7,1804603682);d4=ff(d4,a2,b3,c3,buffer.getUint32(52,!0),12,4254626195);c3=ff(c3,d4,a2,b3,buffer.getUint32(56,!0),17,2792965006);b3=ff(b3,c3,d4,a2,buffer.getUint32(60,!0),22,1236535329);a2=gg(a2,b3,c3,d4,buffer.getUint32(4,!0),5,4129170786);d4=gg(d4,a2,b3,c3,buffer.getUint32(24,!0),9,3225465664);c3=gg(c3,d4,a2,b3,buffer.getUint32(44,!0),14,643717713);b3=gg(b3,c3,d4,a2,buffer.getUint32(0,!0),20,3921069994);a2=gg(a2,b3,c3,d4,buffer.getUint32(20,!0),5,3593408605);d4=gg(d4,a2,b3,c3,buffer.getUint32(40,!0),9,38016083);c3=gg(c3,d4,a2,b3,buffer.getUint32(60,!0),14,3634488961);b3=gg(b3,c3,d4,a2,buffer.getUint32(16,!0),20,3889429448);a2=gg(a2,b3,c3,d4,buffer.getUint32(36,!0),5,568446438);d4=gg(d4,a2,b3,c3,buffer.getUint32(56,!0),9,3275163606);c3=gg(c3,d4,a2,b3,buffer.getUint32(12,!0),14,4107603335);b3=gg(b3,c3,d4,a2,buffer.getUint32(32,!0),20,1163531501);a2=gg(a2,b3,c3,d4,buffer.getUint32(52,!0),5,2850285829);d4=gg(d4,a2,b3,c3,buffer.getUint32(8,!0),9,4243563512);c3=gg(c3,d4,a2,b3,buffer.getUint32(28,!0),14,1735328473);b3=gg(b3,c3,d4,a2,buffer.getUint32(48,!0),20,2368359562);a2=hh(a2,b3,c3,d4,buffer.getUint32(20,!0),4,4294588738);d4=hh(d4,a2,b3,c3,buffer.getUint32(32,!0),11,2272392833);c3=hh(c3,d4,a2,b3,buffer.getUint32(44,!0),16,1839030562);b3=hh(b3,c3,d4,a2,buffer.getUint32(56,!0),23,4259657740);a2=hh(a2,b3,c3,d4,buffer.getUint32(4,!0),4,2763975236);d4=hh(d4,a2,b3,c3,buffer.getUint32(16,!0),11,1272893353);c3=hh(c3,d4,a2,b3,buffer.getUint32(28,!0),16,4139469664);b3=hh(b3,c3,d4,a2,buffer.getUint32(40,!0),23,3200236656);a2=hh(a2,b3,c3,d4,buffer.getUint32(52,!0),4,681279174);d4=hh(d4,a2,b3,c3,buffer.getUint32(0,!0),11,3936430074);c3=hh(c3,d4,a2,b3,buffer.getUint32(12,!0),16,3572445317);b3=hh(b3,c3,d4,a2,buffer.getUint32(24,!0),23,76029189);a2=hh(a2,b3,c3,d4,buffer.getUint32(36,!0),4,3654602809);d4=hh(d4,a2,b3,c3,buffer.getUint32(48,!0),11,3873151461);c3=hh(c3,d4,a2,b3,buffer.getUint32(60,!0),16,530742520);b3=hh(b3,c3,d4,a2,buffer.getUint32(8,!0),23,3299628645);a2=ii(a2,b3,c3,d4,buffer.getUint32(0,!0),6,4096336452);d4=ii(d4,a2,b3,c3,buffer.getUint32(28,!0),10,1126891415);c3=ii(c3,d4,a2,b3,buffer.getUint32(56,!0),15,2878612391);b3=ii(b3,c3,d4,a2,buffer.getUint32(20,!0),21,4237533241);a2=ii(a2,b3,c3,d4,buffer.getUint32(48,!0),6,1700485571);d4=ii(d4,a2,b3,c3,buffer.getUint32(12,!0),10,2399980690);c3=ii(c3,d4,a2,b3,buffer.getUint32(40,!0),15,4293915773);b3=ii(b3,c3,d4,a2,buffer.getUint32(4,!0),21,2240044497);a2=ii(a2,b3,c3,d4,buffer.getUint32(32,!0),6,1873313359);d4=ii(d4,a2,b3,c3,buffer.getUint32(60,!0),10,4264355552);c3=ii(c3,d4,a2,b3,buffer.getUint32(24,!0),15,2734768916);b3=ii(b3,c3,d4,a2,buffer.getUint32(52,!0),21,1309151649);a2=ii(a2,b3,c3,d4,buffer.getUint32(16,!0),6,4149444226);d4=ii(d4,a2,b3,c3,buffer.getUint32(44,!0),10,3174756917);c3=ii(c3,d4,a2,b3,buffer.getUint32(8,!0),15,718787259);b3=ii(b3,c3,d4,a2,buffer.getUint32(36,!0),21,3951481745);state2[0]=a2+state2[0]&4294967295;state2[1]=b3+state2[1]&4294967295;state2[2]=c3+state2[2]&4294967295;state2[3]=d4+state2[3]&4294967295}reset(){this.state=Uint32Array.from(INIT2);this.buffer=new DataView(new ArrayBuffer(64));this.bufferLength=0;this.bytesHashed=0;this.finished=!1}};TEXT_ENCODER="function"==typeof TextEncoder?new TextEncoder:null;calculateBodyLength=body=>{if("string"==typeof body){if(TEXT_ENCODER)return TEXT_ENCODER.encode(body).byteLength;let len=body.length;for(let i2=len-1;i2>=0;i2--){const code=body.charCodeAt(i2);code>127&&code<=2047?len++:code>2047&&code<=65535&&(len+=2);code>=56320&&code<=57343&&i2--}return len}if("number"==typeof body.byteLength)return body.byteLength;if("number"==typeof body.size)return body.size;throw new Error(`Body Length computation failed for ${body}`)};getRuntimeConfig=config=>{var _a8,_b4,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k,_l2,_m2,_n2,_o,_p2,_q;return{apiVersion:"2006-03-01",base64Decoder:null!=(_a8=null==config?void 0:config.base64Decoder)?_a8:fromBase64,base64Encoder:null!=(_b4=null==config?void 0:config.base64Encoder)?_b4:toBase64,disableHostPrefix:null!=(_c3=null==config?void 0:config.disableHostPrefix)&&_c3,endpointProvider:null!=(_d2=null==config?void 0:config.endpointProvider)?_d2:defaultEndpointResolver,extensions:null!=(_e2=null==config?void 0:config.extensions)?_e2:[],getAwsChunkedEncodingStream:null!=(_f=null==config?void 0:config.getAwsChunkedEncodingStream)?_f:getAwsChunkedEncodingStream,httpAuthSchemeProvider:null!=(_g=null==config?void 0:config.httpAuthSchemeProvider)?_g:defaultS3HttpAuthSchemeProvider,httpAuthSchemes:null!=(_h=null==config?void 0:config.httpAuthSchemes)?_h:[{schemeId:"aws.auth#sigv4",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4"),signer:new AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4a"),signer:new AwsSdkSigV4ASigner}],logger:null!=(_i2=null==config?void 0:config.logger)?_i2:new NoOpLogger,sdkStreamMixin:null!=(_j=null==config?void 0:config.sdkStreamMixin)?_j:sdkStreamMixin,serviceId:null!=(_k=null==config?void 0:config.serviceId)?_k:"S3",signerConstructor:null!=(_l2=null==config?void 0:config.signerConstructor)?_l2:SignatureV4MultiRegion,signingEscapePath:null!=(_m2=null==config?void 0:config.signingEscapePath)&&_m2,urlParser:null!=(_n2=null==config?void 0:config.urlParser)?_n2:parseUrl,useArnRegion:null!=(_o=null==config?void 0:config.useArnRegion)&&_o,utf8Decoder:null!=(_p2=null==config?void 0:config.utf8Decoder)?_p2:fromUtf8,utf8Encoder:null!=(_q=null==config?void 0:config.utf8Encoder)?_q:toUtf8}};DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];import_bowser2=__toESM(require_es5());resolveDefaultsModeConfig=({defaultsMode}={})=>memoize((async()=>{const mode="function"==typeof defaultsMode?await defaultsMode():defaultsMode;switch(null==mode?void 0:mode.toLowerCase()){case"auto":return Promise.resolve(isMobileBrowser()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(null==mode?void 0:mode.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`)}}));isMobileBrowser=()=>{var _a8,_b4;const parsedUA="undefined"!=typeof window&&(null==(_a8=null==window?void 0:window.navigator)?void 0:_a8.userAgent)?import_bowser2.default.parse(window.navigator.userAgent):void 0,platform=null==(_b4=null==parsedUA?void 0:parsedUA.platform)?void 0:_b4.type;return"tablet"===platform||"mobile"===platform};getRuntimeConfig2=config=>{var _a8,_b4,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k,_l2,_m2,_n2,_o;const defaultsMode=resolveDefaultsModeConfig(config),defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode),clientSharedValues=getRuntimeConfig(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:null!=(_a8=null==config?void 0:config.bodyLengthChecker)?_a8:calculateBodyLength,credentialDefaultProvider:null!=(_b4=null==config?void 0:config.credentialDefaultProvider)?_b4:_=>()=>Promise.reject(new Error("Credential is missing")),defaultUserAgentProvider:null!=(_c3=null==config?void 0:config.defaultUserAgentProvider)?_c3:createDefaultUserAgentProvider({serviceId:clientSharedValues.serviceId,clientVersion:"3.808.0"}),eventStreamSerdeProvider:null!=(_d2=null==config?void 0:config.eventStreamSerdeProvider)?_d2:eventStreamSerdeProvider2,maxAttempts:null!=(_e2=null==config?void 0:config.maxAttempts)?_e2:3,md5:null!=(_f=null==config?void 0:config.md5)?_f:Md5,region:null!=(_g=null==config?void 0:config.region)?_g:invalidProvider("Region is missing"),requestHandler:FetchHttpHandler.create(null!=(_h=null==config?void 0:config.requestHandler)?_h:defaultConfigProvider),retryMode:null!=(_i2=null==config?void 0:config.retryMode)?_i2:async()=>(await defaultConfigProvider()).retryMode||DEFAULT_RETRY_MODE,sha1:null!=(_j=null==config?void 0:config.sha1)?_j:Sha12,sha256:null!=(_k=null==config?void 0:config.sha256)?_k:Sha2563,streamCollector:null!=(_l2=null==config?void 0:config.streamCollector)?_l2:streamCollector,streamHasher:null!=(_m2=null==config?void 0:config.streamHasher)?_m2:blobHasher,useDualstackEndpoint:null!=(_n2=null==config?void 0:config.useDualstackEndpoint)?_n2:()=>Promise.resolve(!1),useFipsEndpoint:null!=(_o=null==config?void 0:config.useFipsEndpoint)?_o:()=>Promise.resolve(!1)}};getAwsRegionExtensionConfiguration=runtimeConfig=>({setRegion(region){runtimeConfig.region=region},region:()=>runtimeConfig.region});resolveAwsRegionExtensionConfiguration=awsRegionExtensionConfiguration=>({region:awsRegionExtensionConfiguration.region()});getHttpAuthExtensionConfiguration=runtimeConfig=>{const _httpAuthSchemes=runtimeConfig.httpAuthSchemes;let _httpAuthSchemeProvider=runtimeConfig.httpAuthSchemeProvider,_credentials=runtimeConfig.credentials;return{setHttpAuthScheme(httpAuthScheme){const index6=_httpAuthSchemes.findIndex((scheme=>scheme.schemeId===httpAuthScheme.schemeId));-1===index6?_httpAuthSchemes.push(httpAuthScheme):_httpAuthSchemes.splice(index6,1,httpAuthScheme)},httpAuthSchemes:()=>_httpAuthSchemes,setHttpAuthSchemeProvider(httpAuthSchemeProvider){_httpAuthSchemeProvider=httpAuthSchemeProvider},httpAuthSchemeProvider:()=>_httpAuthSchemeProvider,setCredentials(credentials){_credentials=credentials},credentials:()=>_credentials}};resolveHttpAuthRuntimeConfig=config=>({httpAuthSchemes:config.httpAuthSchemes(),httpAuthSchemeProvider:config.httpAuthSchemeProvider(),credentials:config.credentials()});resolveRuntimeExtensions=(runtimeConfig,extensions)=>{const extensionConfiguration=Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig),getDefaultExtensionConfiguration(runtimeConfig),getHttpHandlerExtensionConfiguration(runtimeConfig),getHttpAuthExtensionConfiguration(runtimeConfig));extensions.forEach((extension=>extension.configure(extensionConfiguration)));return Object.assign(runtimeConfig,resolveAwsRegionExtensionConfiguration(extensionConfiguration),resolveDefaultRuntimeConfig2(extensionConfiguration),resolveHttpHandlerRuntimeConfig(extensionConfiguration),resolveHttpAuthRuntimeConfig(extensionConfiguration))};S3Client=class extends Client{constructor(...[configuration]){const _config_0=getRuntimeConfig2(configuration||{});super(_config_0);__publicField(this,"config");this.initConfig=_config_0;const _config_2=function resolveUserAgentConfig(input){var _a8;const normalizedAppIdProvider=normalizeProvider2(null!=(_a8=input.userAgentAppId)?_a8:void 0),{customUserAgent}=input;return Object.assign(input,{customUserAgent:"string"==typeof customUserAgent?[[customUserAgent]]:customUserAgent,userAgentAppId:async()=>{var _a9,_b4;const appId=await normalizedAppIdProvider();if(!function isValidUserAgentAppId(appId){return void 0===appId||"string"==typeof appId&&appId.length<=50}(appId)){const logger2="NoOpLogger"!==(null==(_b4=null==(_a9=input.logger)?void 0:_a9.constructor)?void 0:_b4.name)&&input.logger?input.logger:console;"string"!=typeof appId?null==logger2||logger2.warn("userAgentAppId must be a string or undefined."):appId.length>50&&(null==logger2||logger2.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."))}return appId}})}(resolveClientEndpointParameters(_config_0)),_config_3=resolveFlexibleChecksumsConfig(_config_2),_config_4=resolveRetryConfig(_config_3),_config_5=resolveRegionConfig(_config_4),_config_7=resolveEndpointConfig(_config_5),_config_8=resolveEventStreamSerdeConfig(_config_7),_config_9=resolveHttpAuthSchemeConfig(_config_8),_config_10=resolveS3Config(_config_9,{session:[()=>this,CreateSessionCommand]}),_config_11=resolveRuntimeExtensions(_config_10,(null==configuration?void 0:configuration.extensions)||[]);this.config=_config_11;this.middlewareStack.use(getUserAgentPlugin(this.config));this.middlewareStack.use(getRetryPlugin(this.config));this.middlewareStack.use(getContentLengthPlugin(this.config));this.middlewareStack.use(getHostHeaderPlugin(this.config));this.middlewareStack.use(getLoggerPlugin(this.config));this.middlewareStack.use(getRecursionDetectionPlugin(this.config));this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:defaultS3HttpAuthSchemeParametersProvider,identityProviderConfigProvider:async config=>new DefaultIdentityProviderConfig({"aws.auth#sigv4":config.credentials,"aws.auth#sigv4a":config.credentials})}));this.middlewareStack.use(getHttpSigningPlugin(this.config));this.middlewareStack.use(getValidateBucketNamePlugin(this.config));this.middlewareStack.use(getAddExpectContinuePlugin(this.config));this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config));this.middlewareStack.use(getS3ExpressPlugin(this.config));this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config))}destroy(){super.destroy()}};AbortMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").f(void 0,void 0).ser(se_AbortMultipartUploadCommand).de(de_AbortMultipartUploadCommand).build()){};ssecMiddlewareOptions={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0};getSsecPlugin=config=>({applyToStack:clientStack=>{clientStack.add(function ssecMiddleware(options){return next2=>async args=>{const input={...args.input},properties=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(const prop2 of properties){const value=input[prop2.target];if(value){let valueForHash;if("string"==typeof value)if(isValidBase64EncodedSSECustomerKey(value,options))valueForHash=options.base64Decoder(value);else{valueForHash=options.utf8Decoder(value);input[prop2.target]=options.base64Encoder(valueForHash)}else{valueForHash=ArrayBuffer.isView(value)?new Uint8Array(value.buffer,value.byteOffset,value.byteLength):new Uint8Array(value);input[prop2.target]=options.base64Encoder(valueForHash)}const hash2=new options.md5;hash2.update(valueForHash);input[prop2.hash]=options.base64Encoder(await hash2.digest())}}return next2({...args,input})}}(config),ssecMiddlewareOptions)}});CompleteMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").f(CompleteMultipartUploadRequestFilterSensitiveLog,CompleteMultipartUploadOutputFilterSensitiveLog).ser(se_CompleteMultipartUploadCommand).de(de_CompleteMultipartUploadCommand).build()){};CopyObjectCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"},CopySource:{type:"contextParams",name:"CopySource"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").f(CopyObjectRequestFilterSensitiveLog,CopyObjectOutputFilterSensitiveLog).ser(se_CopyObjectCommand).de(de_CopyObjectCommand).build()){};locationConstraintMiddlewareOptions={step:"initialize",tags:["LOCATION_CONSTRAINT","CREATE_BUCKET_CONFIGURATION"],name:"locationConstraintMiddleware",override:!0};getLocationConstraintPlugin=config=>({applyToStack:clientStack=>{clientStack.add(function locationConstraintMiddleware(options){return next2=>async args=>{const{CreateBucketConfiguration}=args.input,region=await options.region();(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.LocationConstraint)||(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.Location)||(args={...args,input:{...args.input,CreateBucketConfiguration:"us-east-1"===region?void 0:{LocationConstraint:region}}});return next2(args)}}(config),locationConstraintMiddlewareOptions)}});CreateBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},DisableAccessPoints:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getLocationConstraintPlugin(config)]})).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").f(void 0,void 0).ser(se_CreateBucketCommand).de(de_CreateBucketCommand).build()){};CreateBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_CreateBucketMetadataTableConfigurationCommand).de(de_CreateBucketMetadataTableConfigurationCommand).build()){};CreateMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").f(CreateMultipartUploadRequestFilterSensitiveLog,CreateMultipartUploadOutputFilterSensitiveLog).ser(se_CreateMultipartUploadCommand).de(de_CreateMultipartUploadCommand).build()){};DeleteBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketAnalyticsConfigurationCommand).de(de_DeleteBucketAnalyticsConfigurationCommand).build()){};DeleteBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").f(void 0,void 0).ser(se_DeleteBucketCommand).de(de_DeleteBucketCommand).build()){};DeleteBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").f(void 0,void 0).ser(se_DeleteBucketCorsCommand).de(de_DeleteBucketCorsCommand).build()){};DeleteBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").f(void 0,void 0).ser(se_DeleteBucketEncryptionCommand).de(de_DeleteBucketEncryptionCommand).build()){};DeleteBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketIntelligentTieringConfigurationCommand).de(de_DeleteBucketIntelligentTieringConfigurationCommand).build()){};DeleteBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketInventoryConfigurationCommand).de(de_DeleteBucketInventoryConfigurationCommand).build()){};DeleteBucketLifecycleCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").f(void 0,void 0).ser(se_DeleteBucketLifecycleCommand).de(de_DeleteBucketLifecycleCommand).build()){};DeleteBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketMetadataTableConfigurationCommand).de(de_DeleteBucketMetadataTableConfigurationCommand).build()){};DeleteBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketMetricsConfigurationCommand).de(de_DeleteBucketMetricsConfigurationCommand).build()){};DeleteBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_DeleteBucketOwnershipControlsCommand).de(de_DeleteBucketOwnershipControlsCommand).build()){};DeleteBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").f(void 0,void 0).ser(se_DeleteBucketPolicyCommand).de(de_DeleteBucketPolicyCommand).build()){};DeleteBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").f(void 0,void 0).ser(se_DeleteBucketReplicationCommand).de(de_DeleteBucketReplicationCommand).build()){};DeleteBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").f(void 0,void 0).ser(se_DeleteBucketTaggingCommand).de(de_DeleteBucketTaggingCommand).build()){};DeleteBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").f(void 0,void 0).ser(se_DeleteBucketWebsiteCommand).de(de_DeleteBucketWebsiteCommand).build()){};DeleteObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(se_DeleteObjectCommand).de(de_DeleteObjectCommand).build()){};DeleteObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObjects",{}).n("S3Client","DeleteObjectsCommand").f(void 0,void 0).ser(se_DeleteObjectsCommand).de(de_DeleteObjectsCommand).build()){};DeleteObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").f(void 0,void 0).ser(se_DeleteObjectTaggingCommand).de(de_DeleteObjectTaggingCommand).build()){};DeletePublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").f(void 0,void 0).ser(se_DeletePublicAccessBlockCommand).de(de_DeletePublicAccessBlockCommand).build()){};GetBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").f(void 0,void 0).ser(se_GetBucketAccelerateConfigurationCommand).de(de_GetBucketAccelerateConfigurationCommand).build()){};GetBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").f(void 0,void 0).ser(se_GetBucketAclCommand).de(de_GetBucketAclCommand).build()){};GetBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_GetBucketAnalyticsConfigurationCommand).de(de_GetBucketAnalyticsConfigurationCommand).build()){};GetBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").f(void 0,void 0).ser(se_GetBucketCorsCommand).de(de_GetBucketCorsCommand).build()){};GetBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").f(void 0,GetBucketEncryptionOutputFilterSensitiveLog).ser(se_GetBucketEncryptionCommand).de(de_GetBucketEncryptionCommand).build()){};GetBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_GetBucketIntelligentTieringConfigurationCommand).de(de_GetBucketIntelligentTieringConfigurationCommand).build()){};GetBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").f(void 0,GetBucketInventoryConfigurationOutputFilterSensitiveLog).ser(se_GetBucketInventoryConfigurationCommand).de(de_GetBucketInventoryConfigurationCommand).build()){};GetBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").f(void 0,void 0).ser(se_GetBucketLifecycleConfigurationCommand).de(de_GetBucketLifecycleConfigurationCommand).build()){};GetBucketLocationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").f(void 0,void 0).ser(se_GetBucketLocationCommand).de(de_GetBucketLocationCommand).build()){};GetBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").f(void 0,void 0).ser(se_GetBucketLoggingCommand).de(de_GetBucketLoggingCommand).build()){};GetBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_GetBucketMetadataTableConfigurationCommand).de(de_GetBucketMetadataTableConfigurationCommand).build()){};GetBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_GetBucketMetricsConfigurationCommand).de(de_GetBucketMetricsConfigurationCommand).build()){};GetBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").f(void 0,void 0).ser(se_GetBucketNotificationConfigurationCommand).de(de_GetBucketNotificationConfigurationCommand).build()){};GetBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_GetBucketOwnershipControlsCommand).de(de_GetBucketOwnershipControlsCommand).build()){};GetBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").f(void 0,void 0).ser(se_GetBucketPolicyCommand).de(de_GetBucketPolicyCommand).build()){};GetBucketPolicyStatusCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").f(void 0,void 0).ser(se_GetBucketPolicyStatusCommand).de(de_GetBucketPolicyStatusCommand).build()){};GetBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").f(void 0,void 0).ser(se_GetBucketReplicationCommand).de(de_GetBucketReplicationCommand).build()){};GetBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").f(void 0,void 0).ser(se_GetBucketRequestPaymentCommand).de(de_GetBucketRequestPaymentCommand).build()){};GetBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").f(void 0,void 0).ser(se_GetBucketTaggingCommand).de(de_GetBucketTaggingCommand).build()){};GetBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").f(void 0,void 0).ser(se_GetBucketVersioningCommand).de(de_GetBucketVersioningCommand).build()){};GetBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").f(void 0,void 0).ser(se_GetBucketWebsiteCommand).de(de_GetBucketWebsiteCommand).build()){};GetObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").f(void 0,void 0).ser(se_GetObjectAclCommand).de(de_GetObjectAclCommand).build()){};GetObjectAttributesCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").f(GetObjectAttributesRequestFilterSensitiveLog,void 0).ser(se_GetObjectAttributesCommand).de(de_GetObjectAttributesCommand).build()){};GetObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1"]}),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(GetObjectRequestFilterSensitiveLog,GetObjectOutputFilterSensitiveLog).ser(se_GetObjectCommand).de(de_GetObjectCommand).build()){};GetObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").f(void 0,void 0).ser(se_GetObjectLegalHoldCommand).de(de_GetObjectLegalHoldCommand).build()){};GetObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").f(void 0,void 0).ser(se_GetObjectLockConfigurationCommand).de(de_GetObjectLockConfigurationCommand).build()){};GetObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").f(void 0,void 0).ser(se_GetObjectRetentionCommand).de(de_GetObjectRetentionCommand).build()){};GetObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").f(void 0,void 0).ser(se_GetObjectTaggingCommand).de(de_GetObjectTaggingCommand).build()){};GetObjectTorrentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").f(void 0,GetObjectTorrentOutputFilterSensitiveLog).ser(se_GetObjectTorrentCommand).de(de_GetObjectTorrentCommand).build()){};GetPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").f(void 0,void 0).ser(se_GetPublicAccessBlockCommand).de(de_GetPublicAccessBlockCommand).build()){};HeadBucketCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").f(void 0,void 0).ser(se_HeadBucketCommand).de(de_HeadBucketCommand).build()){};HeadObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin()]})).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").f(HeadObjectRequestFilterSensitiveLog,HeadObjectOutputFilterSensitiveLog).ser(se_HeadObjectCommand).de(de_HeadObjectCommand).build()){};ListBucketAnalyticsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketAnalyticsConfigurationsCommand).de(de_ListBucketAnalyticsConfigurationsCommand).build()){};ListBucketIntelligentTieringConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketIntelligentTieringConfigurationsCommand).de(de_ListBucketIntelligentTieringConfigurationsCommand).build()){};ListBucketInventoryConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").f(void 0,ListBucketInventoryConfigurationsOutputFilterSensitiveLog).ser(se_ListBucketInventoryConfigurationsCommand).de(de_ListBucketInventoryConfigurationsCommand).build()){};ListBucketMetricsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketMetricsConfigurationsCommand).de(de_ListBucketMetricsConfigurationsCommand).build()){};ListBucketsCommand=class extends(Command.classBuilder().ep(commonParams).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").f(void 0,void 0).ser(se_ListBucketsCommand).de(de_ListBucketsCommand).build()){};ListDirectoryBucketsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").f(void 0,void 0).ser(se_ListDirectoryBucketsCommand).de(de_ListDirectoryBucketsCommand).build()){};ListMultipartUploadsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").f(void 0,void 0).ser(se_ListMultipartUploadsCommand).de(de_ListMultipartUploadsCommand).build()){};ListObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").f(void 0,void 0).ser(se_ListObjectsCommand).de(de_ListObjectsCommand).build()){};ListObjectsV2Command=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(se_ListObjectsV2Command).de(de_ListObjectsV2Command).build()){};ListObjectVersionsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").f(void 0,void 0).ser(se_ListObjectVersionsCommand).de(de_ListObjectVersionsCommand).build()){};ListPartsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").f(ListPartsRequestFilterSensitiveLog,void 0).ser(se_ListPartsCommand).de(de_ListPartsCommand).build()){};PutBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]})).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").f(void 0,void 0).ser(se_PutBucketAccelerateConfigurationCommand).de(de_PutBucketAccelerateConfigurationCommand).build()){};PutBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").f(void 0,void 0).ser(se_PutBucketAclCommand).de(de_PutBucketAclCommand).build()){};PutBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_PutBucketAnalyticsConfigurationCommand).de(de_PutBucketAnalyticsConfigurationCommand).build()){};PutBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").f(void 0,void 0).ser(se_PutBucketCorsCommand).de(de_PutBucketCorsCommand).build()){};PutBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").f(PutBucketEncryptionRequestFilterSensitiveLog,void 0).ser(se_PutBucketEncryptionCommand).de(de_PutBucketEncryptionCommand).build()){};PutBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_PutBucketIntelligentTieringConfigurationCommand).de(de_PutBucketIntelligentTieringConfigurationCommand).build()){};PutBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").f(PutBucketInventoryConfigurationRequestFilterSensitiveLog,void 0).ser(se_PutBucketInventoryConfigurationCommand).de(de_PutBucketInventoryConfigurationCommand).build()){};PutBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutBucketLifecycleConfiguration",{}).n("S3Client","PutBucketLifecycleConfigurationCommand").f(void 0,void 0).ser(se_PutBucketLifecycleConfigurationCommand).de(de_PutBucketLifecycleConfigurationCommand).build()){};PutBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").f(void 0,void 0).ser(se_PutBucketLoggingCommand).de(de_PutBucketLoggingCommand).build()){};PutBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_PutBucketMetricsConfigurationCommand).de(de_PutBucketMetricsConfigurationCommand).build()){};PutBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").f(void 0,void 0).ser(se_PutBucketNotificationConfigurationCommand).de(de_PutBucketNotificationConfigurationCommand).build()){};PutBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_PutBucketOwnershipControlsCommand).de(de_PutBucketOwnershipControlsCommand).build()){};PutBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").f(void 0,void 0).ser(se_PutBucketPolicyCommand).de(de_PutBucketPolicyCommand).build()){};PutBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").f(void 0,void 0).ser(se_PutBucketReplicationCommand).de(de_PutBucketReplicationCommand).build()){};PutBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").f(void 0,void 0).ser(se_PutBucketRequestPaymentCommand).de(de_PutBucketRequestPaymentCommand).build()){};PutBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").f(void 0,void 0).ser(se_PutBucketTaggingCommand).de(de_PutBucketTaggingCommand).build()){};PutBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").f(void 0,void 0).ser(se_PutBucketVersioningCommand).de(de_PutBucketVersioningCommand).build()){};PutBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").f(void 0,void 0).ser(se_PutBucketWebsiteCommand).de(de_PutBucketWebsiteCommand).build()){};PutObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectAcl",{}).n("S3Client","PutObjectAclCommand").f(void 0,void 0).ser(se_PutObjectAclCommand).de(de_PutObjectAclCommand).build()){};PutObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getCheckContentLengthHeaderPlugin(),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(PutObjectRequestFilterSensitiveLog,PutObjectOutputFilterSensitiveLog).ser(se_PutObjectCommand).de(de_PutObjectCommand).build()){};PutObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectLegalHold",{}).n("S3Client","PutObjectLegalHoldCommand").f(void 0,void 0).ser(se_PutObjectLegalHoldCommand).de(de_PutObjectLegalHoldCommand).build()){};PutObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectLockConfiguration",{}).n("S3Client","PutObjectLockConfigurationCommand").f(void 0,void 0).ser(se_PutObjectLockConfigurationCommand).de(de_PutObjectLockConfigurationCommand).build()){};PutObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectRetention",{}).n("S3Client","PutObjectRetentionCommand").f(void 0,void 0).ser(se_PutObjectRetentionCommand).de(de_PutObjectRetentionCommand).build()){};PutObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectTagging",{}).n("S3Client","PutObjectTaggingCommand").f(void 0,void 0).ser(se_PutObjectTaggingCommand).de(de_PutObjectTaggingCommand).build()){};PutPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").f(void 0,void 0).ser(se_PutPublicAccessBlockCommand).de(de_PutPublicAccessBlockCommand).build()){};RestoreObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","RestoreObject",{}).n("S3Client","RestoreObjectCommand").f(RestoreObjectRequestFilterSensitiveLog,void 0).ser(se_RestoreObjectCommand).de(de_RestoreObjectCommand).build()){};SelectObjectContentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").f(SelectObjectContentRequestFilterSensitiveLog,SelectObjectContentOutputFilterSensitiveLog).ser(se_SelectObjectContentCommand).de(de_SelectObjectContentCommand).build()){};UploadPartCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","UploadPart",{}).n("S3Client","UploadPartCommand").f(UploadPartRequestFilterSensitiveLog,UploadPartOutputFilterSensitiveLog).ser(se_UploadPartCommand).de(de_UploadPartCommand).build()){};UploadPartCopyCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").f(UploadPartCopyRequestFilterSensitiveLog,UploadPartCopyOutputFilterSensitiveLog).ser(se_UploadPartCopyCommand).de(de_UploadPartCopyCommand).build()){};WriteGetObjectResponseCommand=class extends(Command.classBuilder().ep({...commonParams,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").f(WriteGetObjectResponseRequestFilterSensitiveLog,void 0).ser(se_WriteGetObjectResponseCommand).de(de_WriteGetObjectResponseCommand).build()){};createAggregatedClient({AbortMultipartUploadCommand,CompleteMultipartUploadCommand,CopyObjectCommand,CreateBucketCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,CreateSessionCommand,DeleteBucketCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectCommand,PutObjectAclCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RestoreObjectCommand,SelectObjectContentCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand},S3=class extends S3Client{});applyMd5BodyChecksumMiddleware=options=>next2=>async args=>{const{request:request2}=args;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(!hasHeader3("content-md5",headers)){let digest;if(void 0===body||"string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hash2=new options.md5;hash2.update(body||"");digest=hash2.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};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 key2 of keys3)await db.delete(key2)})())}async eraseAllEphemerals(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-ephemeral`,`${PREFIX_TRENCH}-ephemeral.`);for(const key2 of keys3)await this._db.delete(key2)}async eraseAllPermanences(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-permanent`,`${PREFIX_TRENCH}-permanent.`);for(const key2 of keys3)await this._db.delete(key2)}conceal(obj){const key2=generateId("ephemeral");this.concealing.set(key2,obj);this._db.set(key2,obj).then((async e3=>{this.concealing.has(key2)?this.concealing.delete(key2):await this._db.delete(key2)}));return key2}async bury(key2){this.concealing.has(key2)&&this.concealing.delete(key2);await this._db.delete(key2)}async expose(key2){if(this.concealing.has(key2)){const value=this.concealing.get(key2);this.concealing.delete(key2);return value}const obj=await this._db.get(key2);await this._db.delete(key2);return obj}_evacuate(storeTask,key2){return async()=>{if(this._flushTask){await this._flushTask;this._flushTask=void 0}await storeTask;const item=await this._db.get(key2);await this._db.delete(key2);return item}}evacuatePromise(task){const key2=generateId("ephemeral"),storeTask=(async()=>{const data=await task;await this._db.set(key2,data)})();return this._evacuate(storeTask,key2)}evacuate(obj){if(obj instanceof Promise)return this.evacuatePromise(obj);const key2=generateId("ephemeral"),storeTask=this._db.set(key2,obj);return this._evacuate(storeTask,key2)}async _queue(type,key2,obj,index6){var _a8;if(void 0===index6){index6=null!=(_a8=indexes.get(key2))?_a8:0;indexes.set(key2,index6+1)}const storeKey=function createId(prefix,series2,idx2){return`${PREFIX_TRENCH}-${prefix}-${series2}-${idx2+1e7}`}(type,key2,index6);await this._db.set(storeKey,obj)}async _dequeue(type,key2){const range3=createRange(type,key2),keys3=(await this._db.keys(range3[0],range3[1])).filter((e3=>!inProgress.has(e3)));if(0!==keys3.length)return await this.expose(keys3[0])}async _dequeueWithCommit(type,key2){const range3=createRange(type,key2),keysAll=await this._db.keys(range3[0],range3[1]),keys3=keysAll.filter((e3=>!inProgress.has(e3)));if(0===keys3.length)return;const storeKey=keys3[0];inProgress.add(storeKey);const previousFailed=failed.get(storeKey)||0,value=await this._db.get(storeKey);return{key:storeKey,value,cancelCount:previousFailed,pendingItems:keysAll.length-1,commit:async()=>{await this._db.delete(storeKey);failed.delete(storeKey);inProgress.delete(storeKey)},cancel:()=>{failed.set(storeKey,(failed.get(storeKey)||0)+1);inProgress.delete(storeKey)}}}queue(key2,obj,index6){return this._queue("ephemeral",key2,obj,index6)}dequeue(key2){return this._dequeue("ephemeral",key2)}dequeueWithCommit(key2){return this._dequeueWithCommit("ephemeral",key2)}queuePermanent(key2,obj,index6){return this._queue("permanent",key2,obj,index6)}dequeuePermanent(key2){return this._dequeue("permanent",key2)}dequeuePermanentWithCommit(key2){return this._dequeueWithCommit("permanent",key2)}};RECORD_SPLIT="\n";UNIT_SPLIT="";te4=new TextEncoder;JournalSyncAbstract=class{constructor(id,key2,endpoint,bucket,prefix,store,env,useCustomRequestHandler,region="",customHeaders){this.id="";this.key="";this.bucket="";this.endpoint="";this.prefix="";this.region="auto";this.hash="";this.batchSize=100;this.customHeaders=[];this.requestedStop=!1;this.notifier=new Notifier;this._currentCheckPointInfo={...CheckPointInfoDefault};this.isPacking=!1;this.isDownloading=!1;this.id=id;this.key=key2;this.bucket=bucket;this.prefix=prefix;this.endpoint=endpoint;this.region=region;this.db=env.getDatabase();this.env=env;this.useCustomRequestHandler=useCustomRequestHandler;this.processReplication=async docs=>await env.$$parseReplicationResult(docs);this.store=store;this.hash=this.getHash(endpoint,bucket,region,prefix);this.trench=new Trench(store);const headers=Object.entries(parseHeaderValues(customHeaders));this.customHeaders=headers}getHash(endpoint,bucket,region,prefix){return btoa(encodeURI([endpoint,`${bucket}${prefix}`,region].join()))}applyNewConfig(id,key2,endpoint,bucket,prefix,store,env,useCustomRequestHandler,region="",customHeaders){this.id=id;this.key=key2;this.bucket=bucket;this.prefix=prefix;this.endpoint=endpoint;this.region=region;this.db=env.getDatabase();this.env=env;this.useCustomRequestHandler=useCustomRequestHandler;this.processReplication=async docs=>await env.$$parseReplicationResult(docs);this.store=store;this.hash=this.getHash(endpoint,bucket,region,prefix);const headers=Object.entries(parseHeaderValues(customHeaders));this.customHeaders=headers}updateInfo(info3){var _a8,_b4,_c3,_d2,_e2,_f,_g;const old=this.env.replicationStat.value;this.env.replicationStat.value={sent:null!=(_a8=info3.sent)?_a8:old.sent,arrived:null!=(_b4=info3.arrived)?_b4: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 key2 of items)key2 in old&&(Array.isArray(old[key2]),1)&&(old[key2]=new Set(old[key2]));this._currentCheckPointInfo={...CheckPointInfoDefault,...old};return this._currentCheckPointInfo}async resetAllCaches(){await this.trench.eraseAllPermanences()}async resetCheckpointInfo(){await this.updateCheckPointInfo((info3=>({...CheckPointInfoDefault})))}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 key2=this.getDocKey(doc);if(this._currentCheckPointInfo.knownIDs.has(key2)){knownKeyCount++;return!1}if(this._currentCheckPointInfo.sentIDs.has(key2)){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)`,-1);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 key2=this.getDocKey(doc);if(this._currentCheckPointInfo.knownIDs.has(key2)){knownKeyCount++;return!1}if(this._currentCheckPointInfo.sentIDs.has(key2)){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:key2,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} ${key2} ${0!=cancelCount?`TRY:${cancelCount}`:""} ${pendingItems} left`,LOG_LEVEL_VERBOSE);if(cancelCount>3){Logger(`${TASK_TITLE} Something went wrong on processing queue ${key2}.`,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 ${key2} as ${filename}`,LOG_LEVEL_INFO)}catch(ex){Logger(`${TASK_TITLE} Could not send journalPack to the bucket (${key2} as ${filename})`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`${TASK_TITLE} Uploading ${key2} 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=concatUInt8Array(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=concatUInt8Array(outBuf),orgLen=sendBuf.byteLength,bin=await wrappedDeflate(sendBuf,{consume:!0,level:8});Logger(`Packing Journal: Compressed ${orgLen} bytes to ${bin.byteLength} bytes (${0!=orgLen?Math.ceil(bin.byteLength/orgLen*100):"--"}%)`,LOG_LEVEL_VERBOSE);await this.trench.queuePermanent("upload_queue",bin);this.notifier.notify()}await this.updateCheckPointInfo((info3=>({...info3,lastLocalSeq:packLastSeq,sentIDs})));currentLastSeq=packLastSeq;if(!hasNext){isFinished=!0;break}}while(0==this.requestedStop&&!isFinished);Logger(0!=seqToProcess?`Packing Journal: Packaging ${seqToProcess}`:"Packing Journal: No journals to be packed!",logLevel,MSG_KEY);this.notifier.notify();return!0}finally{this.isPacking=!1;this.notifier.notify()}}))}async sendLocalJournal(showMessage=!1){this.updateInfo({syncStatus:"JOURNAL_SEND"});if((await Promise.all([this.packAndCompress(showMessage),this.uploadQueued(showMessage)])).every((e3=>e3))&&await this.uploadQueued(showMessage,!0)){this.updateInfo({syncStatus:"COMPLETED"});return!0}this.updateInfo({syncStatus:"ERRORED"});return!1}async _getRemoteJournals(){const StartAfter=[...(await this.getCheckpointInfo()).receivedFiles.keys()].sort(((a2,b3)=>b3.localeCompare(a2,void 0,{numeric:!0})))[0],files=(await this.listFiles(StartAfter)).filter((e3=>!e3.startsWith("_")));return files?files.sort(((a2,b3)=>a2.localeCompare(b3,void 0,{numeric:!0}))):[]}async processDocuments(allDocs2){let applyTotal=0,wholeItems=0;try{const chunks=[],docs=[];allDocs2.forEach((e3=>{e3._id.startsWith("h:")?chunks.push(e3):docs.push(e3)}));try{const e22=(await this.db.allDocs({include_docs:!0,keys:[...chunks.map((e3=>e3._id))]})).rows.map((e3=>{var _a8;return null!=(_a8=e3.id)?_a8:void 0})),existChunks=new Set(e22.filter((e3=>void 0!==e3))),saveChunks=chunks.filter((e3=>!existChunks.has(e3._id))).map((e3=>({...e3,_rev:void 0}))),ret=await this.db.bulkDocs(saveChunks,{new_edits:!0}),saveError=ret.filter((e3=>"error"in e3)).map((e3=>e3.id));saveChunks.filter((e3=>-1===saveError.indexOf(e3._id))).forEach((doc=>globalSlipBoard2.submit("read-chunk",doc._id,doc)));await this.updateCheckPointInfo((info3=>({...info3,knownIDs:setAllItems(info3.knownIDs,chunks.map((e3=>this.getDocKey(e3))))})));Logger(`Saved ${ret.length} chunks in transferred ${chunks.length} chunks (Error:${saveError.length})`,LOG_LEVEL_VERBOSE)}catch(ex){Logger("Applying chunks failed",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}const docsRevs=docs.map((e3=>[e3._id,[e3._rev]])).reduce(((acc,[id,revs])=>{var _a8;return{...acc,[id]:[...null!=(_a8=acc[id])?_a8:[],...revs]}}),{}),diffRevs=await this.db.revsDiff(docsRevs),saveDocs=docs.filter((e3=>{var _a8,_b4;return e3._id in diffRevs&&"missing"in diffRevs[e3._id]&&-1!==(null!=(_b4=null==(_a8=diffRevs[e3._id].missing)?void 0:_a8.indexOf(e3._rev))?_b4: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:key2,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 ${key2}.`,LOG_LEVEL_NOTICE);return!1}const decompressed=await wrappedInflate(value,{consume:!0});if(0==decompressed.length){await commit();downloaded++;Logger(`${TASK_TITLE}: ${key2} 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[key3,data]=strPiece.substring(1).split(UNIT_SPLIT);result.push({_id:key3,data:(str=data,str.startsWith("\\f")?str.substring(2).replace(/(\\n|\\r|\\\\)/g,(m3=>`${revMap2[m3]}`)):str),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}: ${key2} 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}: ${key2} cancelled for retry`,LOG_LEVEL_VERBOSE);cancel2();await delay(1e3);continue}}while(0==this.requestedStop);var str;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 key2 of files){count++;Logger(`Receiving Journal: ${count} / ${files.length}`,logLevel,"receivejournal");if(this.requestedStop){Logger(`Receiving canceled: ${key2}`,logLevel);return!1}if(this._currentCheckPointInfo.sentFiles.has(key2)){Logger(`Receiving Journal: ${key2} is own sent file`,LOG_LEVEL_VERBOSE);await this.updateCheckPointInfo((info3=>({...info3,receivedFiles:info3.receivedFiles.add(key2)})))}else try{const data=await this.downloadFile(key2);if(!1===data)throw new Error("Download Error");await this.trench.queuePermanent("parse_file",data);await this.updateCheckPointInfo((info3=>({...info3,receivedFiles:info3.receivedFiles.add(key2)})));this.notifier.notify()}catch(ex){Logger(`Could not download ${key2}`,logLevel);Logger(ex,-1);return!1}}}finally{this.isDownloading=!1;this.notifier.notify()}this.notifier.notify();return!0}))}async receiveRemoteJournal(showMessage=!1){this.updateInfo({syncStatus:"JOURNAL_RECEIVE"});this.requestedStop=!1;if((await Promise.all([this.downloadRemoteJournals(showMessage),this.processDownloadedJournals(showMessage)])).every((e3=>e3))&&await this.processDownloadedJournals(showMessage,!0)){this.updateInfo({syncStatus:"COMPLETED"});return!0}this.updateInfo({syncStatus:"ERRORED"});return!1}async sync(showResult=!1){var _a8;return null!=(_a8=await shareRunningResult("replicate",(async()=>{this.requestedStop=!1;const receiveResult=await this.receiveRemoteJournal(showResult);if(!this.requestedStop){if(receiveResult)return await this.sendLocalJournal(showResult);Logger("Could not receive remote journal, so we prevent sending local journals to prevent unwanted mass transfers",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}})))&&_a8}requestStop(){this.requestedStop=!0}};JournalSyncMinio=class extends JournalSyncAbstract{_getClient(){if(this._instance)return this._instance;const ep=this.endpoint?{endpoint:this.endpoint,forcePathStyle:!0}:{};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.$$customFetchHandler():void 0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED"});const bucketCustomHeaders=this.customHeaders;this._instance.middlewareStack.add(((next2,context2)=>args=>{bucketCustomHeaders.forEach((([key2,value])=>{key2&&value&&(args.request.headers[key2]=value)}));return next2(args)}),{name:"addBucketCustomHeadersMiddleware",step:"build"});this._instance.middlewareStack.add(applyMd5BodyChecksumMiddleware({md5:Md5,base64Encoder:data=>{return buffer=data.buffer,btoa(String.fromCharCode(...new Uint8Array(buffer)));var buffer},streamHasher:(hashConstructor,stream)=>{const result=promiseWithResolver(),hash2=new hashConstructor;stream.on("data",(chunk=>{hash2.update(chunk)}));stream.on("end",(()=>{result.resolve(hash2.digest())}));return result.promise}}),{step:"build",name:"applyMd5BodyChecksumMiddlewareForDeleteObjects"});return this._instance}async resetBucket(){var _a8;const client=this._getClient();let files=[],deleteCount=0,errorCount=0;try{do{files=await this.listFiles("",100);if(0==files.length)break;const cmd2=new DeleteObjectsCommand({Bucket:this.bucket,Delete:{Objects:files.map((e3=>({Key:`${this.prefix}${e3}`})))}}),r5=await client.send(cmd2),{Deleted,Errors}=r5;deleteCount+=(null==Deleted?void 0:Deleted.length)||0;errorCount+=(null==Errors?void 0:Errors.length)||0;Logger(`${deleteCount} items has been deleted!${0!=errorCount?` (${errorCount} items failed to delete)`:""}`,LOG_LEVEL_NOTICE,"reset-bucket")}while(0==files.length)}catch(ex){Logger("WARNING! Could not delete files. you should try it once or remake the bucket manually",LOG_LEVEL_NOTICE,"reset-bucket");Logger(ex,LOG_LEVEL_VERBOSE)}const journals=await this._getRemoteJournals();if(0==journals.length){Logger("Nothing to delete!",LOG_LEVEL_NOTICE);return!0}const cmd=new DeleteObjectsCommand({Bucket:this.bucket,Delete:{Objects:journals.map((e3=>({Key:e3})))}}),r4=await client.send(cmd);Logger(`${(null==(_a8=null==r4?void 0:r4.Deleted)?void 0:_a8.length)||0} items has been deleted!`,LOG_LEVEL_NOTICE);await this.resetCheckpointInfo();return!0}async uploadJson(key2,body){try{return await this.uploadFile(key2,new Blob([JSON.stringify(body)]),"application/json")}catch(ex){Logger(`Could not upload json ${key2}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async downloadJson(key2){try{const ret=await this.downloadFile(key2,!0);return!!ret&&JSON.parse((new TextDecoder).decode(ret))}catch(ex){Logger(`Could not download json ${key2}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async uploadFile(key2,blob,mime){try{let u2=new Uint8Array(await blob.arrayBuffer());const set2=this.env.getSettings();set2.encrypt&&""!=set2.passphrase&&(u2=await encryptBinary(u2,set2.passphrase,set2.useDynamicIterationCount));const client=this._getClient(),cmd=new PutObjectCommand({Bucket:this.bucket,Key:`${this.prefix}${key2}`,Body:u2,ContentType:mime});if(await client.send(cmd))return!0}catch(ex){Logger(`Could not upload ${key2}`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1}async downloadFile(key2,ignoreCache=!1){const client=this._getClient(),cmd=new GetObjectCommand({Bucket:this.bucket,Key:`${this.prefix}${key2}`,...ignoreCache?{ResponseCacheControl:"no-cache"}:{}}),r4=await client.send(cmd),set2=this.env.getSettings();try{if(r4.Body){let u2=await r4.Body.transformToByteArray();set2.encrypt&&""!=set2.passphrase&&(u2=await decryptBinary(u2,set2.passphrase,set2.useDynamicIterationCount));return u2}}catch(ex){Logger(`Could not download ${key2}`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1}async listFiles(from,limit){const client=this._getClient(),objects=await client.listObjectsV2({Bucket:this.bucket,Prefix:this.prefix,StartAfter:`${this.prefix||""}${from||""}`,...limit?{MaxKeys:limit}:{}});return objects.Contents?objects.Contents.filter((e3=>{var _a8;return null==(_a8=e3.Key)?void 0:_a8.startsWith(this.prefix)})).map((e3=>{var _a8;return null==(_a8=e3.Key)?void 0:_a8.substring(this.prefix.length)})):[]}async isAvailable(){const client=this._getClient(),cmd=new HeadBucketCommand({Bucket:this.bucket});try{await client.send(cmd);return!0}catch(ex){Logger("Could not connected to the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async getUsage(){const client=this._getClient();try{const objects=await client.listObjectsV2({Bucket:this.bucket});return objects.Contents?{estimatedSize:objects.Contents.reduce(((acc,e3)=>acc+(e3.Size||0)),0)}:{}}catch(ex){Logger("Could not get status of the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}};MILSTONE_DOCID="_00000000-milestone.json";currentVersionRange={min:0,max:2,current:2};LiveSyncJournalReplicator=class extends LiveSyncAbstractReplicator{constructor(env){super(env);this.syncStatus="NOT_CONNECTED";this.docArrived=0;this.docSent=0;this.lastSyncPullSeq=0;this.maxPullSeq=0;this.lastSyncPushSeq=0;this.maxPushSeq=0;this.nodeid="";this.remoteLocked=!1;this.remoteCleaned=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.updateInfo=()=>{this.env.replicationStat.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}};this.env=env;fireAndForget((()=>this.initializeDatabaseForReplication()));this.env.getDatabase().on("close",(()=>{this.closeReplication()}))}get client(){return this.setupJournalSyncClient()}setupJournalSyncClient(){const settings=this.env.getSettings(),id=settings.accessKey,key2=settings.secretKey,bucket=settings.bucket,prefix=settings.bucketPrefix,region=settings.region,endpoint=settings.endpoint,useCustomRequestHandler=settings.useCustomRequestHandler,customHeaders=settings.bucketCustomHeaders;this._client?this._client.applyNewConfig(id,key2,endpoint,bucket,prefix,this.env.simpleStore,this.env,useCustomRequestHandler,region,customHeaders):this._client=new JournalSyncMinio(id,key2,endpoint,bucket,prefix,this.env.simpleStore,this.env,useCustomRequestHandler,region,customHeaders);return this._client}async ensureBucketIsCompatible(deviceNodeID,currentVersionRange3){const downloadedMilestone=await this.client.downloadJson(MILSTONE_DOCID);return await ensureRemoteIsCompatible(downloadedMilestone,this.env.getSettings(),deviceNodeID,currentVersionRange3,(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();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);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},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},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 id=setting.accessKey,key2=setting.secretKey,bucket=setting.bucket,bucketPrefix=setting.bucketPrefix,region=setting.region,endpoint=setting.endpoint,useCustomRequestHandler=setting.useCustomRequestHandler,customHeaders=setting.bucketCustomHeaders,testClient=new JournalSyncMinio(id,key2,endpoint,bucket,bucketPrefix,this.env.simpleStore,this.env,useCustomRequestHandler,region,customHeaders);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){try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");return remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]||!1}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}}async getRemoteStatus(setting){const id=setting.accessKey,key2=setting.secretKey,bucket=setting.bucket,bucketPrefix=setting.bucketPrefix,region=setting.region,endpoint=setting.endpoint,useCustomRequestHandler=setting.useCustomRequestHandler,customHeaders=setting.bucketCustomHeaders,testClient=new JournalSyncMinio(id,key2,endpoint,bucket,bucketPrefix,this.env.simpleStore,this.env,useCustomRequestHandler,region,customHeaders);return await testClient.getUsage()}};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()}))}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.$$parseReplicationResult(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=async function*genReplication(s2,signal){const inbox=new Inbox(1e4),push2=function(e3){serialized("replicationResult",(async()=>{signal.aborted||(inbox.isDisposed?Logger("Inbox is disposed",LOG_LEVEL_VERBOSE):await inbox.post(e3))}))};s2.on("complete",(result=>push2(["complete",result])));s2.on("change",(result=>push2(["change",result])));s2.on("active",(()=>push2(["active"])));s2.on("denied",(err2=>push2(["denied",err2])));s2.on("error",(err2=>push2(["error",err2])));s2.on("paused",(err2=>push2(["paused",err2])));s2.then((()=>push2(["finally"]))).catch((()=>push2(["finally"])));const abortSymbol=Symbol("abort"),abortPromise=promiseWithResolver();signal.addEventListener("abort",(()=>{abortPromise.resolve(abortSymbol)}));try{for(;!inbox.isDisposed&&!signal.aborted;){const r4=await inbox.pick(void 0,[abortPromise.promise]);if(r4===NOT_AVAILABLE)break;yield r4}}catch(ex){if(!(ex instanceof Error&&"AbortError"==ex.name))throw ex;Logger("Replication aborted",LOG_LEVEL_VERBOSE)}finally{s2.cancel();inbox.dispose()}}(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.$$getLastPostFailedBySize()){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.$$getSimpleStore("sc-"),!1);await trench.eraseAllEphemerals();if(!remoteDB){const d4=await this.connectRemoteCouchDBWithSetting(setting,this.env.$$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}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} => ${sizeToHumanReadable2(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){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("Open settings and check message, please.",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.env.$$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),10)){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 ensure=await async function ensureDatabaseIsCompatible(db,setting,deviceNodeID,currentVersionRange3){const remoteMilestone=await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID),!1);return await ensureRemoteIsCompatible(remoteMilestone,setting,deviceNodeID,currentVersionRange3,(async info3=>{await db.put(info3)}))}(dbRet.db,setting,this.nodeid,currentVersionRange2);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.env.$$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)}}async tryCreateRemoteDatabase(setting){this.closeReplication();"string"!=typeof await this.connectRemoteCouchDBWithSetting(setting,this.env.$$isMobile(),!0)&&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.env.$$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),10)){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},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.env.$$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),10)){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_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.$$connectRemoteCouchDB(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 fetchRemoteChunks(missingChunks,showResult){const ret=await this.connectRemoteCouchDBWithSetting(this.env.getSettings(),this.env.$$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.env.$$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.env.$$isMobile(),!0);if("string"!=typeof dbRet)if(await checkRemoteVersion(dbRet.db,this.migrate.bind(this),10))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.env.$$isMobile(),!0);if("string"!=typeof dbRet)if(await checkRemoteVersion(dbRet.db,this.migrate.bind(this),10))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){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.env.$$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),10)){Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return!1}try{return(await dbRet.db.get(MILESTONE_DOCID)).tweak_values[DEVICE_ID_PREFERRED]}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.env.$$isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return(await dbRet.db.compact({interval:1e3})).ok}async getRemoteStatus(setting){var _a8;const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.env.$$isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri:setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet}),LOG_LEVEL_NOTICE);return!1}const info3=await dbRet.db.info();return{...info3,estimatedSize:(null==(_a8=null==info3?void 0:info3.sizes)?void 0:_a8.file)||0}}};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 key2 of Object.keys(request2.headers)){const keyLower=key2.toLowerCase();"host"!==keyLower&&"content-length"!==keyLower&&(transformedHeaders[keyLower]=request2.headers[key2])}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 key2 of Object.keys(headers))headersLower[key2.toLowerCase()]=headers[key2];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)}};measures=new Map;root_17=template('
 
');root4=template('

TESTING BENCH: Self-hosted LiveSync

Module Checks

Synchronisation Result Status

 

Performance test

',1);$$css5={hash:"svelte-qc8xos",code:".svelte-qc8xos {box-sizing:border-box;}"};import_obsidian7=require("obsidian");TestPaneView=class extends import_obsidian7.ItemView{constructor(leaf,plugin3,moduleDev){super(leaf);this.icon="view-log";this.title="Self-hosted LiveSync Test and Results";this.navigation=!0;this.plugin=plugin3;this.moduleDev=moduleDev}getIcon(){return"view-log"}getViewType(){return"ols-pane-test"}getDisplayText(){return"Self-hosted LiveSync Test and Results"}async onOpen(){this.component=new TestPane({target:this.contentEl,props:{plugin:this.plugin,moduleDev:this.moduleDev}});await Promise.resolve()}async onClose(){var _a8;null==(_a8=this.component)||_a8.$destroy();await Promise.resolve()}};ModuleDev=class extends AbstractObsidianModule{constructor(){super(...arguments);this.testResults=writable([])}$everyOnloadStart(){__onMissingTranslation((()=>{}));return Promise.resolve(!0)}async onMissingTranslation(key2){const outFile=`missing-translation-${(new Date).toISOString().split("T")[0]}.jsonl`,piece=JSON.stringify({[key2]:{}}),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((key2=>{this.onMissingTranslation(key2)}));eventHub.onEvent("document-stub-created",(detail=>{fireAndForget((async()=>{const stub=detail.stub,toc2=detail.toc,stubDocX=Object.entries(stub).map((([key2,value])=>[`## ${key2}`,Object.entries(value).map((([key22,value2])=>[`### ${key22}`,[...value2.entries()].map((([key3,value3])=>{var _a8;const isObsolete=value3.is_obsolete?" (obsolete)":"",desc=null!=(_a8=value3.desc)?_a8:"";return`#### ${key3}${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.core.$$showView("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.core.$$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,key2,result,summary,message){const logLine=`${name}: ${key2} ${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)}};SerializedFileAccess=class{constructor(app2,plugin3){this.touchedFiles=[];this.app=app2;this.plugin=plugin3}async tryAdapterStat(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await processReadFile(file,(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 processReadFile(file,(()=>this.app.vault.adapter.stat(path2)))}async adapterExists(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await processReadFile(file,(()=>this.app.vault.adapter.exists(path2)))}async adapterRemove(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await processReadFile(file,(()=>this.app.vault.adapter.remove(path2)))}async adapterRead(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await processReadFile(file,(()=>this.app.vault.adapter.read(path2)))}async adapterReadBinary(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await processReadFile(file,(()=>this.app.vault.adapter.readBinary(path2)))}async adapterReadAuto(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return isPlainText(path2)?await processReadFile(file,(()=>this.app.vault.adapter.read(path2))):await processReadFile(file,(()=>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 processWriteFile(file,(()=>this.app.vault.adapter.write(path2,data,options))):await processWriteFile(file,(()=>this.app.vault.adapter.writeBinary(path2,toArrayBuffer(data),options)))}async vaultCacheRead(file){return await processReadFile(file,(()=>this.app.vault.cachedRead(file)))}async vaultRead(file){return await processReadFile(file,(()=>this.app.vault.read(file)))}async vaultReadBinary(file){return await processReadFile(file,(()=>this.app.vault.readBinary(file)))}async vaultReadAuto(file){return isPlainText(file.path)?await processReadFile(file,(()=>this.app.vault.read(file))):await processReadFile(file,(()=>this.app.vault.readBinary(file)))}async vaultModify(file,data,options){return"string"==typeof data?await processWriteFile(file,(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 processWriteFile(file,(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 processWriteFile(path2,(()=>this.app.vault.create(path2,data,options))):await 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 processWriteFile(file,(()=>this.app.vault.delete(file,force)))}async trash(file,force=!1){return await processWriteFile(file,(()=>this.app.vault.trash(file,force)))}isStorageInsensitive(){var _a8;return null==(_a8=this.app.vault.adapter.insensitive)||_a8}getAbstractFileByPathInsensitive(path2){return 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},key2=`${path2}-${stat.mtime}-${stat.size}`;this.touchedFiles.unshift(key2);this.touchedFiles=this.touchedFiles.slice(0,100)}recentlyTouched(file){const key2="stat"in file?`${file.path}-${file.stat.mtime}-${file.stat.size}`:`${file.path}-${file.mtime}-${file.size}`;return-1!=this.touchedFiles.indexOf(key2)}clearTouched(){this.touchedFiles=[]}};StorageEventManager=class{};StorageEventManagerObsidian=class extends StorageEventManager{constructor(plugin3,core){super();this.bufferedQueuedItems=[];this.concurrentProcessing=Semaphore(5);this.waitedSince=new Map;this.processingCount=0;this.plugin=plugin3;this.core=core}get shouldBatchSave(){var _a8,_b4;return(null==(_a8=this.core.settings)?void 0:_a8.batchSave)&&1!=(null==(_b4=this.core.settings)?void 0:_b4.liveSync)}get batchSaveMinimumDelay(){var _a8,_b4;return null!=(_b4=null==(_a8=this.core.settings)?void 0:_a8.batchSaveMinimumDelay)?_b4:DEFAULT_SETTINGS.batchSaveMinimumDelay}get batchSaveMaximumDelay(){var _a8,_b4;return null!=(_b4=null==(_a8=this.core.settings)?void 0:_a8.batchSaveMaximumDelay)?_b4:DEFAULT_SETTINGS.batchSaveMaximumDelay}beginWatch(){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.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;const fileInfo=TFileToUXFileInfoStub(file);this.appendQueue([{type:"CREATE",file:fileInfo}],ctx)}watchVaultChange(file,ctx){if(file instanceof import_obsidian.TFolder)return;const fileInfo=TFileToUXFileInfoStub(file);this.appendQueue([{type:"CHANGED",file:fileInfo}],ctx)}watchVaultDelete(file,ctx){if(file instanceof import_obsidian.TFolder)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.plugin.settings&&(this.plugin.settings.useIgnoreFiles?this.plugin.$$isTargetFile(path2).then((()=>this._watchVaultRawEvents(path2))):this._watchVaultRawEvents(path2))}_watchVaultRawEvents(path2){if(!this.plugin.settings.syncInternalFiles&&!this.plugin.settings.usePluginSync)return;if(!this.plugin.settings.watchInternalFileChanges)return;if(!path2.startsWith(this.plugin.app.vault.configDir))return;const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns"),targetPatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");if(!ignorePatterns.some((e3=>e3.test(path2)))&&targetPatterns.some((e3=>e3.test(path2)))&&!path2.endsWith("/")){this.appendQueue([{type:"INTERNAL",file:(filename=path2,{name:filename.split("/").pop(),path:filename,isFolder:!1,stat:void 0,isInternal:!0,deleted:void 0}),skipBatchWait:!0}],null);var filename}}async appendQueue(params,ctx){if(!this.core.settings.isConfigured)return;if(this.core.settings.suspendFileWatching)return;this.core.$$markFileListPossiblyChanged();const processFiles=new Set;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.core.$$isFileSizeExceeded(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.core.$$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});processFiles.add(file.path);oldPath&&processFiles.add(oldPath)}for(const path2 of processFiles)fireAndForget((()=>this.startStandingBy(path2)))}enqueue(newItem){const filename=newItem.args.file.path;if(this.shouldBatchSave){Logger(`Request cancel for waiting of previous ${filename}`,-1);(function finishWaitingForTimeout(key2,hasTimeout=!1){globalSlipBoard.submit("wait-for-timeout",key2,!!hasTimeout)})(`storage-event-manager-batchsave-${filename}`)}this.bufferedQueuedItems.push(newItem);if("DELETE"==newItem.type)return this.flushQueue()}async startStandingBy(filename){await skipIfDuplicated(`storage-event-manager-${filename}`,(async()=>{Logger(`Processing ${filename}: Starting`,-1);const release=await this.concurrentProcessing.acquire();try{Logger(`Processing ${filename}: Started`,-1);let noMoreFiles=!1;do{const target=this.bufferedQueuedItems.find((e3=>e3.args.file.path==filename));if(void 0===target){noMoreFiles=!0;break}const operationType=target.type,type=target.type;if(target.cancelled){Logger(`Processing ${filename}: Cancelled (scheduled): ${operationType}`,-1);this.cancelStandingBy(target)}else{if(target.skipBatchWait)Logger(`Processing ${filename}:Requested to perform immediately ${filename}: ${operationType}`,-1);else if(this.shouldBatchSave&&("CREATE"==type||"CHANGED"==type)){const waitedSince=this.waitedSince.get(filename);let canWait=!0;const now3=Date.now();if(void 0!==waitedSince&&waitedSince+1e3*this.batchSaveMaximumDelaye3.skipBatchWait=!0));(function finishAllWaitingForTimeout(prefix,hasTimeout){globalSlipBoard.submitToAll("wait-for-timeout",prefix,!!hasTimeout)})("storage-event-manager-batchsave-",!0)}cancelQueue(key2){this.bufferedQueuedItems.forEach((e3=>{e3.key===key2&&(e3.skipBatchWait=!0)}))}updateStatus(){const allItems=this.bufferedQueuedItems.filter((e3=>!e3.cancelled)),batchedCount=allItems.filter((e3=>e3.batched&&!e3.skipBatchWait)).length;this.core.batched.value=batchedCount;this.core.processing.value=this.processingCount;this.core.totalQueued.value=allItems.length-batchedCount}async handleFileEvent(queue2){const file=queue2.args.file,lockKey=`handleFile:${file.path}`;return await serialized(lockKey,(async()=>{if("INTERNAL"==queue2.type||file.isInternal)await this.core.$anyProcessOptionalFileEvent(file.path);else{const key2=`file-last-proc-${queue2.type}-${file.path}`,last=Number(await this.core.kvDB.get(key2)||0);if("DELETE"==queue2.type)await this.core.$anyHandlerProcessesFileEvent(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.$anyHandlerProcessesFileEvent(queue2)){Logger(`STORAGE -> DB: Handler failed, cancel the relative operations: ${file.path}`,LOG_LEVEL_INFO);this.cancelRelativeEvent(queue2);return}}}}))}cancelRelativeEvent(item){this.cancelQueue(item.key)}};import_obsidian8=require("obsidian");ModuleFileAccessObsidian=class extends AbstractObsidianModule{constructor(){super(...arguments);this.vaultManager=new StorageEventManagerObsidian(this.plugin,this.core)}$everyOnload(){this.core.storageAccess=this;return Promise.resolve(!0)}$everyOnFirstInitialize(){this.vaultManager.beginWatch();return Promise.resolve(!0)}$allOnUnload(){return Promise.resolve(!0)}$everyCommitPendingFileEvent(){this.vaultManager.flushQueue();return Promise.resolve(!0)}$everyOnloadStart(){this.vaultAccess=new SerializedFileAccess(this.app,this.plugin);return Promise.resolve(!0)}$$isStorageInsensitive(){return this.vaultAccess.isStorageInsensitive()}$$shouldCheckCaseInsensitive(){return!this.$$isStorageInsensitive()&&!this.settings.handleFilenameCaseSensitive}async writeFileAuto(path2,data,opt){const file=this.vaultAccess.getAbstractFileByPath(path2);if(file instanceof import_obsidian8.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_obsidian8.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_obsidian8.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_obsidian8.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_obsidian8.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_obsidian8.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_obsidian8.TFile?TFileToUXFileInfoStub(file):null}async readStubContent(stub){const file=this.vaultAccess.getAbstractFileByPath(stub.path);if(!(file instanceof import_obsidian8.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,body:createBlob(data)}}getStub(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);return file instanceof import_obsidian8.TFile?TFileToUXFileInfoStub(file):file instanceof import_obsidian8.TFolder?function TFolderToUXFileInfoStub(file){var _a8;return{name:file.name,path:file.path,parent:null==(_a8=file.parent)?void 0:_a8.path,isFolder:!0,children:file.children.map((e3=>TFileToUXFileInfoStub(e3)))}}(file):null}getFiles(){return this.vaultAccess.getFiles().map((f4=>TFileToUXFileInfoStub(f4)))}getFileNames(){return this.vaultAccess.getFiles().map((f4=>f4.path))}async getFilesIncludeHidden(basePath,includeFilter,excludeFilter,skipFolder=[".git",".trash","node_modules"]){var _a8;let w2;try{w2=await this.app.vault.adapter.list(basePath)}catch(ex){this._log(`Could not traverse(getFilesIncludeHidden):${basePath}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}skipFolder=skipFolder.map((e3=>e3.toLowerCase()));let files=[];for(const file of w2.files)includeFilter&&includeFilter.length>0&&!includeFilter.some((e3=>e3.test(file)))||excludeFilter&&excludeFilter.some((ee=>ee.test(file)))||await this.plugin.$$isIgnoredByIgnoreFiles(file)||files.push(file);for(const v2 of w2.folders){const folderName=(null!=(_a8=v2.split("/").pop())?_a8:"").toLowerCase();skipFolder.some((e3=>folderName===e3))||excludeFilter&&excludeFilter.some((e3=>e3.test(v2)))||await this.plugin.$$isIgnoredByIgnoreFiles(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_obsidian8.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_obsidian8.TFile||xFile instanceof import_obsidian8.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_obsidian8.TFile||xFile instanceof import_obsidian8.TFolder?this.vaultAccess.trash(xFile,system):Promise.resolve()}async _deleteVaultItem(file){if(file instanceof import_obsidian8.TFile&&!await this.core.$$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_obsidian8.TFile||file instanceof import_obsidian8.TFolder?await this._deleteVaultItem(file):void 0}};require("obsidian");AutoClosableModal=class extends import_obsidian.Modal{_closeByUnload(){eventHub.off("plugin-unloaded",this._closeByUnload);this.close()}constructor(app2){super(app2);this._closeByUnload=this._closeByUnload.bind(this);eventHub.once("plugin-unloaded",this._closeByUnload)}onClose(){eventHub.off("plugin-unloaded",this._closeByUnload)}};InputStringDialog=class extends AutoClosableModal{constructor(app2,title,key2,placeholder,isPassword,onSubmit){super(app2);this.result=!1;this.isManuallyClosed=!1;this.isPassword=!1;this.onSubmit=onSubmit;this.title=title;this.placeholder=placeholder;this.key=key2;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(app2,note,placeholder,getItemsFun,callback){super(app2);this.callback=()=>{};this.getItemsFun=()=>["yes","no"];this.app=app2;this.setPlaceholder((null!=placeholder?placeholder:"y/n) ")+note);getItemsFun&&(this.getItemsFun=getItemsFun);this.callback=callback}getItems(){return this.getItemsFun()}getItemText(item){return item}onChooseItem(item,evt){var _a8;null==(_a8=this.callback)||_a8.call(this,item);this.callback=void 0}onClose(){setTimeout((()=>{if(this.callback){this.callback("");this.callback=void 0}}),100)}};MessageBox=class extends AutoClosableModal{constructor(plugin3,title,contentMd,buttons,defaultAction,timeout,wideButton,onSubmit){super(plugin3.app);this.result=!1;this.isManuallyClosed=!1;this.timer=void 0;this.plugin=plugin3;this.title=title;this.contentMd=contentMd;this.buttons=buttons;this.onSubmit=onSubmit;this.defaultAction=defaultAction;this.timeout=timeout;this.wideButton=wideButton;this.timeout&&(this.timer=setInterval((()=>{var _a8,_b4;if(void 0!==this.timeout){this.timeout--;if(this.timeout<0){if(this.timer){clearInterval(this.timer);null==(_a8=this.defaultButtonComponent)||_a8.setButtonText(`${defaultAction}`);this.timer=void 0}this.result=defaultAction;this.isManuallyClosed=!0;this.close()}else null==(_b4=this.defaultButtonComponent)||_b4.setButtonText(`( ${this.timeout} ) ${defaultAction}`)}}),1e3))}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);const div=contentEl.createDiv();div.style.userSelect="text";div.style.webkitUserSelect="text";import_obsidian.MarkdownRenderer.render(this.plugin.app,this.contentMd,div,"/",this.plugin);const buttonSetting=new import_obsidian.Setting(contentEl),labelWrapper=contentEl.createDiv();labelWrapper.addClass("sls-dialogue-note-wrapper");labelWrapper.createEl("label",{text:"To stop the countdown, tap anywhere on the dialogue"}).addClass("sls-dialogue-note-countdown");if(!this.timeout||!this.timer){labelWrapper.empty();labelWrapper.style.display="none"}buttonSetting.infoEl.style.display="none";buttonSetting.controlEl.style.flexWrap="wrap";if(this.wideButton){buttonSetting.controlEl.style.flexDirection="column";buttonSetting.controlEl.style.alignItems="center";buttonSetting.controlEl.style.justifyContent="center";buttonSetting.controlEl.style.flexGrow="1"}contentEl.addEventListener("click",(()=>{var _a8;if(this.timer){labelWrapper.empty();labelWrapper.style.display="none";clearInterval(this.timer);this.timer=void 0;null==(_a8=this.defaultButtonComponent)||_a8.setButtonText(`${this.defaultAction}`)}}));for(const button of this.buttons)buttonSetting.addButton((btn=>{btn.setButtonText(button).onClick((()=>{this.isManuallyClosed=!0;this.result=button;if(this.timer){clearInterval(this.timer);this.timer=void 0}this.close()}));if(button==this.defaultAction){this.defaultButtonComponent=btn;btn.setCta()}if(this.wideButton){btn.buttonEl.style.flexGrow="1";btn.buttonEl.style.width="100%"}return btn}))}onClose(){super.onClose();const{contentEl}=this;contentEl.empty();if(this.timer){clearInterval(this.timer);this.timer=void 0}this.isManuallyClosed?this.onSubmit(this.result):this.onSubmit(!1)}};askYesNo=(app2,message)=>new Promise((res2=>{new PopoverSelectString(app2,message,void 0,void 0,(result=>res2(result))).open()}));askSelectString=(app2,message,items)=>{const getItemsFun=()=>items;return new Promise((res2=>{new PopoverSelectString(app2,message,"",getItemsFun,(result=>res2(result))).open()}))};askString=(app2,title,key2,placeholder,isPassword=!1)=>new Promise((res2=>{new InputStringDialog(app2,title,key2,placeholder,isPassword,(result=>res2(result))).open()}));ModuleInputUIObsidian=class extends AbstractObsidianModule{$everyOnload(){this.core.confirm=this;(function setConfirmInstance(api){if(!instance){instance=api;p.resolve(api)}instance=api})(this);return Promise.resolve(!0)}askYesNo(message){return askYesNo(this.app,message)}askString(title,key2,placeholder,isPassword=!1){return askString(this.app,title,key2,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(key2,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-"+key2;scheduleTask(popupKey,1e3,(async()=>{var _a8;const popup=await memoIfNotExist(popupKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a8=null==popup?void 0:popup.noticeEl)?void 0:_a8.isShown())||memoObject(popupKey,new import_obsidian.Notice(fragment,0));scheduleTask(popupKey+"-close",2e4,(()=>{var _a9;const popup2=retrieveMemoObject(popupKey);if(popup2){(null==(_a9=null==popup2?void 0:popup2.noticeEl)?void 0:_a9.isShown())&&popup2.hide();disposeMemoObject(popupKey)}}))}))}confirmWithMessage(title,contentMd,buttons,defaultAction,timeout){return confirmWithMessage(this.plugin,title,contentMd,buttons,defaultAction,timeout)}};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_24_30={version:"0.24.30",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."}}};DoctorRegulation=DoctorRegulationV0_24_30;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"},couchDB_DBNAME:{name:"Database Name"},passphrase:{name:"Passphrase",desc:"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files."},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:"Remote Type",desc:"Remote server type"},endpoint:{name:"Endpoint URL",placeHolder:"https://........"},accessKey:{name:"Access Key"},secretKey:{name:"Secret Key"},region:{name:"Region",placeHolder:"auto"},bucket:{name:"Bucket Name"},useCustomRequestHandler:{name:"Use Custom HTTP Handler",desc:"Enable this if your Object Storage doesn't support CORS"},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},settingSyncFile:{name:"Filename",desc:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform."},preset:{name:"Presets",desc:"Apply preset configuration"},syncMode:{name:"Sync Mode"},periodicReplicationInterval:{name:"Periodic Sync interval",desc:"Interval (sec)"},syncInternalFilesBeforeReplication:{name:"Scan for hidden files before replication"},automaticallyDeleteMetadataOfDeletedFiles:{name:"Delete old metadata of deleted files on start-up",desc:"(Days passed, 0 to disable automatic-deletion)"},additionalSuffixOfDatabaseName:{name:"Database suffix",desc:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured."},hashAlg:{name:(null==(_a7=configurationNames.hashAlg)?void 0:_a7.name)||"",desc:"xxhash64 is the current default."},deviceAndVaultName:{name:"Device name",desc:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once."},displayLanguage:{name:"Display Language",desc:'Not all messages have been translated. And, please revert to "Default" when reporting errors.'},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},disableWorkerForGeneratingChunks:{name:"Do not split chunks in the background",desc:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour)."},processSmallFilesInUIThread:{name:"Process small files in the foreground",desc:"If enabled, the file under 1kb will be processed in the UI thread."},batchSaveMinimumDelay:{name:"Minimum delay for batch database updating",desc:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving."},batchSaveMaximumDelay:{name:"Maximum delay for batch database updating",desc:"Saving will be performed forcefully after this number of seconds."},notifyThresholdOfRemoteStorageSize:{name:"Notify when the estimated remote storage size exceeds on start up",desc:"MB (0 to disable)."},usePluginSyncV2:{name:"Enable per-file customization sync",desc:"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Compute revisions for chunks",desc:"If this enabled, all chunks will be stored with the revision made from its content."},sendChunksBulkMaxSize:{name:"Maximum size of chunks to send in one request",desc:"MB"},useAdvancedMode:{name:"Enable advanced features"},usePowerUserMode:{name:"Enable poweruser features"},useEdgeCaseMode:{name:"Enable edge case treatment features"},enableDebugTools:{name:"Enable Developers' Debug Tools.",desc:"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian."},suppressNotifyHiddenFilesChange:{name:"Suppress notification of hidden files change",desc:"If enabled, the notification of hidden files change will be suppressed."},syncMinimumInterval:{name:"Minimum interval for syncing",desc:"The minimum interval for automatic synchronisation on event."},useRequestAPI:{name:"Use Request API to avoid `inevitable` CORS problem",desc:"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option."},hideFileWarningNotice:{name:"Show status icon instead of file warnings banner",desc:"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown."},bucketPrefix:{name:"File prefix on the bucket",desc:"Effectively a directory. Should end with `/`. e.g., `vault-name/`."},chunkSplitterVersion:{name:"Chunk Splitter",desc:"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy."}};ModuleMigration=class extends AbstractModule{async migrateUsingDoctor(skipRebuild=!1,activateReason="updated",forceRescan=!1){var _a8,_b4;const r4=function checkUnsuitableValues(setting,regulation=DoctorRegulation){var _a8,_b4;const result={version:regulation.version,rules:{}};for(const key2 in regulation.rules){if(!regulation.rules.hasOwnProperty(key2))continue;const rule=regulation.rules[key2];if(!rule)continue;const value=setting[key2];if(rule.value!==value){if("number"==typeof value&&"min"in rule&&"max"in rule){const min=null!=(_a8=rule.min)?_a8:Number.MIN_SAFE_INTEGER,max3=null!=(_b4=rule.max)?_b4:Number.MAX_SAFE_INTEGER;if(value>=min&&value<=max3){Logger(`Rule satisfied: ${key2} is ${value} between ${min} and ${max3}`);continue}}if(!rule.detectionFunc||rule.detectionFunc(setting)){result.rules[key2]=rule;Logger(`Rule violation: ${key2} is ${value} but should be ${rule.value}`)}else Logger(`Rule condition satisfied: ${key2} is ${value}, and detection function returned false`)}else Logger(`Rule satisfied: ${key2} is ${value}`)}return result}(this.core.settings);if(forceRescan||r4.version!=this.settings.doctorProcessedVersion)if(0!=Object.entries(r4.rules).length){const OPT_YES=`${$msg("Doctor.Button.Yes")}`,OPT_NO=`${$msg("Doctor.Button.No")}`,OPT_DISMISS=`${$msg("Doctor.Button.DismissThisVersion")}`,issues2=Object.keys(r4.rules).map((key2=>`- ${getConfName(key2)}`)).join("\n"),msg=await this.core.confirm.askSelectStringDialogue($msg("Doctor.Dialogue.Main",{activateReason,issues:issues2}),[OPT_YES,OPT_NO,OPT_DISMISS],{title:$msg("Doctor.Dialogue.Title"),defaultAction:OPT_YES});if(msg==OPT_DISMISS){this.settings.doctorProcessedVersion=r4.version;await this.core.saveSettings();this._log("Marked as to be silent",LOG_LEVEL_VERBOSE);return}if(msg!=OPT_YES)return;let shouldRebuild=!1,shouldRebuildLocal=!1;const issueItems=Object.entries(r4.rules);this._log(`${issueItems.length} Issue(s) found `,LOG_LEVEL_VERBOSE);let idx2=0;const applySettings={},OPT_FIX=`${$msg("Doctor.Button.Fix")}`,OPT_SKIP=`${$msg("Doctor.Button.Skip")}`,OPT_FIXBUTNOREBUILD=`${$msg("Doctor.Button.FixButNoRebuild")}`;let skipped=0;for(const[key2,value]of issueItems){const levelMap={[1]:$msg("Doctor.Level.Necessary"),[2]:$msg("Doctor.Level.Recommended"),[3]:$msg("Doctor.Level.Optional"),[0]:$msg("Doctor.Level.Must")},level=value.level?levelMap[value.level]:"Unknown",options=[OPT_FIX];(!skipRebuild&&value.requireRebuild||value.requireRebuildLocal)&&options.push(OPT_FIXBUTNOREBUILD);options.push(OPT_SKIP);const note=skipRebuild?"":`${value.requireRebuild?$msg("Doctor.Message.RebuildRequired"):""}${value.requireRebuildLocal?$msg("Doctor.Message.RebuildLocalRequired"):""}`,ret=await this.core.confirm.askSelectStringDialogue($msg("Doctor.Dialogue.MainFix",{name:getConfName(key2),current:`${this.settings[key2]}`,reason:null!=(_a8=value.reason)?_a8:" N/A ",ideal:`${null!=(_b4=value.valueDisplay)?_b4:value.value}`,level:`${level}`,note}),options,{title:$msg("Doctor.Dialogue.TitleFix",{current:""+ ++idx2,total:`${issueItems.length}`}),defaultAction:OPT_FIX});if(ret==OPT_FIX||ret==OPT_FIXBUTNOREBUILD){applySettings[key2]=value.value;if(ret==OPT_FIX){shouldRebuild=shouldRebuild||value.requireRebuild||!1;shouldRebuildLocal=shouldRebuildLocal||value.requireRebuildLocal||!1}}else skipped++}Object.keys(applySettings).length>0&&(this.settings={...this.settings,...applySettings});(0==skipped||"no"==await this.core.confirm.askYesNoDialog($msg("Doctor.Message.SomeSkipped"),{title:$msg("Doctor.Dialogue.TitleAlmostDone"),defaultOption:"No"}))&&(this.settings.doctorProcessedVersion=r4.version);await this.core.saveSettings();if(!skipRebuild)if(shouldRebuild){await this.core.rebuilder.scheduleRebuild();await this.core.$$performRestart()}else if(shouldRebuildLocal){await this.core.rebuilder.scheduleFetch();await this.core.$$performRestart()}}else this._log($msg("Doctor.Message.NoIssues"),"updated"!==activateReason?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);else{const msg=Object.keys(r4.rules).length>0?"Issues found":"No issues found";this._log(`${msg} but marked as to be silent`,LOG_LEVEL_VERBOSE)}}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 message=$msg("moduleMigration.msgInitialSetup",{URI_DOC:$msg("moduleMigration.docUri")}),USE_SETUP=$msg("moduleMigration.optionHaveSetupUri"),NEXT=$msg("moduleMigration.optionNoSetupUri"),ret=await this.core.confirm.askSelectStringDialogue(message,[USE_SETUP,NEXT],{title:$msg("moduleMigration.titleWelcome"),defaultAction:USE_SETUP});if(ret===USE_SETUP){eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI2);return!1}return ret==NEXT}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 $everyOnFirstInitialize(){if(!this.localDatabase.isReady){this._log($msg("moduleMigration.logLocalDatabaseNotReady"),LOG_LEVEL_NOTICE);return!1}if(this.settings.isConfigured){await this.migrateUsingDoctor(!1);await this.migrateDisableBulkSend()}if(!this.settings.isConfigured){if(!await this.initialMessage()||!await this.askAgainForSetupURI()){this._log($msg("moduleMigration.logSetupCancelled"),LOG_LEVEL_NOTICE);return!1}await this.migrateUsingDoctor(!0)}return!0}$everyOnLayoutReady(){eventHub.onEvent(EVENT_REQUEST_RUN_DOCTOR,(async reason=>{await this.migrateUsingDoctor(!1,reason,!0)}));return Promise.resolve(!0)}};ModuleCheckRemoteSize=class extends AbstractModule{async $allScanStat(){var _a8;this._log($msg("moduleCheckRemoteSize.logCheckingStorageSizes"),LOG_LEVEL_VERBOSE);if(this.settings.notifyThresholdOfRemoteStorageSize<0){const message=$msg("moduleCheckRemoteSize.msgSetDBCapacity"),ANSWER_0=$msg("moduleCheckRemoteSize.optionNoWarn"),ANSWER_800=$msg("moduleCheckRemoteSize.option800MB"),ANSWER_2000=$msg("moduleCheckRemoteSize.option2GB"),ASK_ME_NEXT_TIME=$msg("moduleCheckRemoteSize.optionAskMeLater"),ret=await this.core.confirm.askSelectStringDialogue(message,[ANSWER_0,ANSWER_800,ANSWER_2000,ASK_ME_NEXT_TIME],{defaultAction:ASK_ME_NEXT_TIME,title:$msg("moduleCheckRemoteSize.titleDatabaseSizeNotify"),timeout:40});if(ret==ANSWER_0){this.settings.notifyThresholdOfRemoteStorageSize=0;await this.core.saveSettings()}else if(ret==ANSWER_800){this.settings.notifyThresholdOfRemoteStorageSize=800;await this.core.saveSettings()}else if(ret==ANSWER_2000){this.settings.notifyThresholdOfRemoteStorageSize=2e3;await this.core.saveSettings()}}if(this.settings.notifyThresholdOfRemoteStorageSize>0){const remoteStat=await(null==(_a8=this.core.replicator)?void 0:_a8.getRemoteStatus(this.settings));if(remoteStat){const estimatedSize=remoteStat.estimatedSize;if(estimatedSize){const maxSize=1024*this.settings.notifyThresholdOfRemoteStorageSize*1024;if(estimatedSize>maxSize){const message=$msg("moduleCheckRemoteSize.msgDatabaseGrowing",{estimatedSize:sizeToHumanReadable2(estimatedSize),maxSize:sizeToHumanReadable2(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:sizeToHumanReadable2(estimatedSize),notifySize:sizeToHumanReadable2(1024*this.settings.notifyThresholdOfRemoteStorageSize*1024)}),LOG_LEVEL_INFO)}else this._log($msg("moduleCheckRemoteSize.logCurrentStorageSize",{measuredSize:sizeToHumanReadable2(estimatedSize)}),LOG_LEVEL_INFO)}}}return!0}};import_diff_match_patch4=__toESM(require_diff_match_patch(),1);ModuleConflictResolver=class extends AbstractModule{async $$resolveConflictByDeletingRev(path2,deleteRevision,subTitle=""){const title=`Resolving ${subTitle?`[${subTitle}]`:""}:`;if(!await this.core.fileHandler.deleteRevisionFromDB(path2,deleteRevision)){this._log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}eventHub.emitEvent("conflict-cancelled",path2);this._log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path2}`,LOG_LEVEL_INFO);if(0!=(await this.core.databaseFileAccess.getConflictedRevs(path2)).length){this._log(`${title} some conflicts are left in ${path2}`,LOG_LEVEL_INFO);return AUTO_MERGED}if(isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)){this._log(`${title} ${path2} is a plugin metadata file, no need to write to storage`,LOG_LEVEL_INFO);return AUTO_MERGED}if(!await this.core.fileHandler.dbToStorage(path2,stripAllPrefixes(path2),!0)){this._log(`Could not write the resolved content to the storage: ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}const level=-1!==subTitle.indexOf("same")?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE;this._log(`${path2} has been merged automatically`,level);return AUTO_MERGED}async checkConflictAndPerformAutoMerge(path2){const ret=await this.localDatabase.tryAutoMerge(path2,!this.settings.disableMarkdownAutoMerge);if("ok"in ret)return ret.ok;if("result"in ret){const p4=ret.result;if(!await this.core.databaseFileAccess.storeContent(path2,p4)){this._log(`Merged content cannot be stored:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}return await this.core.$$resolveConflictByDeletingRev(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.core.$$resolveConflictByDeletingRev(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.core.$$resolveConflictByDeletingRev(path2,loser.rev,subTitle)}const dmp=new import_diff_match_patch4.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.core.$$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.core.$anyResolveConflictByUI(filename,conflictCheckResult)}else{this.settings.syncAfterMerge&&!this.core.$$isSuspended()&&await this.core.$$replicateByEvent();this._log("[conflict] Automatically merged, but we have to check it again");await this.core.$$queueConflictCheck(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 p4=conflictCheckResult.diff.map((e3=>e3[1])).join(""),delRev=testDoc._conflicts[0];if(!await this.core.databaseFileAccess.storeContent(filename,p4)){this._log(`Concatenated content cannot be stored:${filename}`,LOG_LEVEL_NOTICE);return!1}if(await this.core.$$resolveConflictByDeletingRev(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.core.$$resolveConflictByDeletingRev(filename,toDelete,"UI Selected")==MISSING_OR_ERROR){this._log(`Merge: Something went wrong: ${filename}, (${toDelete})`,LOG_LEVEL_NOTICE);return!1}}this.settings.syncAfterMerge&&!this.core.$$isSuspended()&&await this.core.$$replicateByEvent();await this.core.$$queueConflictCheck(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.core.$$queueConflictCheck(targetItem.path);await this.core.$$waitForAllConflictProcessed();return!0}return!1}async $allScanStat(){const notes=[];this._log("Checking conflicted files",LOG_LEVEL_VERBOSE);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);return!0}};import_obsidian10=require("obsidian");ModuleObsidianSettings=class extends AbstractObsidianModule{constructor(){super(...arguments);this.usedPassphrase=""}async $everyOnLayoutReady(){let isChanged=!1;if(""==this.settings.displayLanguage){const obsidianLanguage=(0,import_obsidian10.getLanguage)();if(-1!==SUPPORTED_I18N_LANGS.indexOf(obsidianLanguage)&&obsidianLanguage!=this.settings.displayLanguage&&""!=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.core.$$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.core.$$saveSettingData()}return!0}getPassphrase(settings){const methods={"":()=>Promise.resolve("*"),LOCALSTORAGE:()=>{var _a8;return Promise.resolve(null!=(_a8=localStorage.getItem("ls-setting-passphrase"))&&_a8)},ASK_AT_LAUNCH:()=>this.core.confirm.askString("Passphrase","passphrase","")},method=settings.configPassphraseStore;return(method in methods?methods[method]:methods[""])()}$$saveDeviceAndVaultName(){const lsKey="obsidian-live-sync-vaultanddevicename-"+this.core.$$getVaultName();localStorage.setItem(lsKey,this.core.$$getDeviceAndVaultName()||"")}$$clearUsedPassphrase(){this.usedPassphrase=""}async decryptConfigurationItem(encrypted,passphrase){const dec=await async function tryDecrypt(encryptedResult,passphrase,autoCalculateIterations){if(!passphrase)return!1;try{return await decrypt(encryptedResult,passphrase,autoCalculateIterations)}catch(e3){return!1}}(encrypted,passphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U",!1);if(dec){this.usedPassphrase=passphrase;return dec}return!1}async encryptConfigurationItem(src,settings){if(""!=this.usedPassphrase)return await encrypt(src,this.usedPassphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U",!1);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 encrypt(src,passphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U",!1);if(dec){this.usedPassphrase=passphrase;return dec}return""}get appId(){return`${"appId"in this.app?this.app.appId:""}`}async $$saveSettingData(){this.core.$$saveDeviceAndVaultName();const settings={...this.settings};settings.deviceAndVaultName="";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};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("setting-saved",settings)}tryDecodeJson(encoded){try{return!!encoded&&JSON.parse(encoded)}catch(e3){return!1}}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}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 key2 of keys3)key2 in decrypted&&(settings[key2]=decrypted[key2]);else{this._log("Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",128);for(const key2 of keys3)settings[key2]=""}}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=""}}}this.settings=settings;setLang(this.settings.displayLanguage);"workingEncrypt"in this.settings&&delete this.settings.workingEncrypt;"workingPassphrase"in this.settings&&delete this.settings.workingPassphrase;this.settings.disableRequestURI=!0;this.settings.gcDelay=0;this.settings.useHistory=!0;const lsKey="obsidian-live-sync-vaultanddevicename-"+this.core.$$getVaultName();if(""!=this.settings.deviceAndVaultName&&!localStorage.getItem(lsKey)){this.core.$$setDeviceAndVaultName(this.settings.deviceAndVaultName);this.$$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.core.$$setDeviceAndVaultName(localStorage.getItem(lsKey)||"");if(""==this.core.$$getDeviceAndVaultName()&&this.settings.usePluginSync){this._log("Device name missing. Disabling plug-in sync.",LOG_LEVEL_NOTICE);this.settings.usePluginSync=!1}""==this.settings.chunkSplitterVersion?this.settings.enableChunkSplitterV2?this.settings.useSegmenter?this.settings.chunkSplitterVersion="v2-segmenter":this.settings.chunkSplitterVersion="v2":this.settings.chunkSplitterVersion="":this.settings.chunkSplitterVersion in ChunkAlgorithmNames||(this.settings.chunkSplitterVersion="");eventHub.emitEvent("reload-setting-tab")}};ModuleRedFlag=class extends AbstractModule{constructor(){super(...arguments);this.isRedFlagRaised=async()=>await this.isFlagFileExist(FLAGMD_REDFLAG);this.isRedFlag2Raised=async()=>await this.isFlagFileExist(FLAGMD_REDFLAG2)||await this.isFlagFileExist(FLAGMD_REDFLAG2_HR);this.isRedFlag3Raised=async()=>await this.isFlagFileExist(FLAGMD_REDFLAG3)||await this.isFlagFileExist(FLAGMD_REDFLAG3_HR)}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 deleteRedFlag2(){await this.deleteFlagFile(FLAGMD_REDFLAG2);await this.deleteFlagFile(FLAGMD_REDFLAG2_HR)}async deleteRedFlag3(){await this.deleteFlagFile(FLAGMD_REDFLAG3);await this.deleteFlagFile(FLAGMD_REDFLAG3_HR)}async $everyOnLayoutReady(){try{const isRedFlagRaised=await this.isRedFlagRaised(),isRedFlag2Raised=await this.isRedFlag2Raised(),isRedFlag3Raised=await this.isRedFlag3Raised();if(isRedFlagRaised||isRedFlag2Raised||isRedFlag3Raised){if(isRedFlag2Raised&&"yes"!==await this.core.confirm.askYesNoDialog("Rebuild everything has been scheduled! Are you sure to rebuild everything?",{defaultOption:"Yes",timeout:0})){await this.deleteRedFlag2();await this.core.$$performRestart();return!1}if(isRedFlag3Raised&&"yes"!==await this.core.confirm.askYesNoDialog("Fetch again has been scheduled! Are you sure?",{defaultOption:"Yes",timeout:0})){await this.deleteRedFlag3();await this.core.$$performRestart();return!1}this.settings.batchSave=!1;await this.core.$allSuspendAllSync();await this.core.$allSuspendExtraSync();this.settings.suspendFileWatching=!0;await this.saveSettings();if(isRedFlag2Raised){this._log(`${FLAGMD_REDFLAG2} or ${FLAGMD_REDFLAG2_HR} has been detected! Self-hosted LiveSync suspends all sync and rebuild everything.`,LOG_LEVEL_NOTICE);await this.core.rebuilder.$rebuildEverything();await this.deleteRedFlag2();if("yes"==await this.core.confirm.askYesNoDialog("Do you want to resume file and database processing, and restart obsidian now?",{defaultOption:"Yes",timeout:15})){this.settings.suspendFileWatching=!1;await this.saveSettings();this.core.$$performRestart();return!1}}else if(isRedFlag3Raised){this._log(`${FLAGMD_REDFLAG3} or ${FLAGMD_REDFLAG3_HR} has been detected! Self-hosted LiveSync will discard the local database and fetch everything from the remote once again.`,LOG_LEVEL_NOTICE);const method1=$msg("RedFlag.Fetch.Method.FetchSafer"),method2=$msg("RedFlag.Fetch.Method.FetchSmoother"),method3=$msg("RedFlag.Fetch.Method.FetchTraditional"),methods=[method1,method2,method3],chunkMode=await this.core.confirm.askSelectStringDialogue($msg("RedFlag.Fetch.Method.Desc"),methods,{defaultAction:method1,timeout:0,title:$msg("RedFlag.Fetch.Method.Title")});let makeLocalChunkBeforeSync=!1,preventMakeLocalFilesBeforeSync=!1;if(chunkMode===method1)preventMakeLocalFilesBeforeSync=!0;else if(chunkMode===method2)makeLocalChunkBeforeSync=!0;else if(chunkMode!==method3){this._log("Cancelled the fetch operation",LOG_LEVEL_NOTICE);return!1}await this.core.rebuilder.$fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync);await this.deleteRedFlag3();if(this.settings.suspendFileWatching){if("yes"==await this.core.confirm.askYesNoDialog("Do you want to resume file and database processing, and restart obsidian now?",{defaultOption:"Yes",timeout:15})){this.settings.suspendFileWatching=!1;await this.saveSettings();this.core.$$performRestart();return!1}}else this._log("Your content of files will be synchronised gradually. Please wait for the completion.",LOG_LEVEL_NOTICE)}else{this.settings.writeLogToTheFile=!0;const warningMessage="The red flag is raised! The whole initialize steps are skipped, and any file changes are not captured.";this._log(warningMessage,LOG_LEVEL_NOTICE)}}}catch(ex){this._log("Something went wrong on FlagFile Handling",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}};ModuleObsidianMenu=class extends AbstractObsidianModule{$everyOnloadStart(){(0,import_obsidian.addIcon)("replicate",'\n \n \n \n \n ');this.addRibbonIcon("replicate",$msg("moduleObsidianMenu.replicate"),(async()=>{await this.core.$$replicate(!0)})).addClass("livesync-ribbon-replicate");this.addCommand({id:"livesync-replicate",name:"Replicate now",callback:async()=>{await this.core.$$replicate()}});this.addCommand({id:"livesync-dump",name:"Dump information of this doc ",callback:()=>{const file=this.core.$$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.core.$$queueConflictCheckIfOpen(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.core.$$realizeSettingSyncMode();await this.core.$$saveSettingData()}});this.addCommand({id:"livesync-suspendall",name:"Toggle All Sync.",callback:async()=>{if(this.core.$$isSuspended()){this.core.$$setSuspended(!1);this._log("Self-hosted LiveSync resumed",LOG_LEVEL_NOTICE)}else{this.core.$$setSuspended(!0);this._log("Self-hosted LiveSync suspended",LOG_LEVEL_NOTICE)}await this.core.$$realizeSettingSyncMode();await this.core.$$saveSettingData()}});this.addCommand({id:"livesync-scan-files",name:"Scan storage and database again",callback:async()=>{await this.core.$$performFullScan(!0)}});this.addCommand({id:"livesync-runbatch",name:"Run pended batch processes",callback:async()=>{await this.core.$everyCommitPendingFileEvent()}});this.addCommand({id:"livesync-abortsync",name:"Abort synchronization immediately",callback:()=>{this.core.replicator.terminateSync()}});return Promise.resolve(!0)}$everyOnload(){this.app.workspace.onLayoutReady(this.core.$$onLiveSyncReady.bind(this.core));return Promise.resolve(!0)}async $$showView(viewType){const leaves=this.app.workspace.getLeavesOfType(viewType);0==leaves.length?await this.app.workspace.getLeaf(!0).setViewState({type:viewType,active:!0}):await leaves[0].setViewState({type:viewType,active:!0});leaves.length>0&&await this.app.workspace.revealLeaf(leaves[0])}};import_qrcode_generator=__toESM(require_qrcode(),1);ModuleSetupObsidian=class extends AbstractObsidianModule{$everyOnload(){this.registerObsidianProtocolHandler("setuplivesync",(async conf=>{conf.settings?await this.setupWizard(conf.settings):conf.settingsQR&&await this.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()))));return Promise.resolve(!0)}async encodeQR(){const settingArr=[],fullIndexes=Object.entries(KeyIndexOfSettings);for(const[settingKey,index6]of fullIndexes){const settingValue=this.settings[settingKey];index6<0||(settingArr[index6]=settingValue)}const w2=function encodeAnyArray(obj){return obj.map((v2=>{if(null===v2)return"n";if(!1===v2)return"f";if(!0===v2)return"t";if(void 0===v2)return"u";if("number"==typeof v2){const b36=v2.toString(36),strNum=v2.toString(),expression=b36.length=settingArr.length)continue;const settingValue=settingArr[index6];newSettings[settingKey]=settingValue}console.warn(newSettings);await this.applySettingWizard(this.settings,newSettings,"QR Code")}async command_copySetupURI(stripExtra=!0){const encryptingPassphrase=await this.core.confirm.askString("Encrypt your settings","The passphrase to encrypt the setup URI","",!0);if(!1===encryptingPassphrase)return;const setting={...this.settings,configPassphraseStore:"",encryptedCouchDBConnection:"",encryptedPassphrase:""};stripExtra&&delete setting.pluginSyncExtendedSetting;const keys3=Object.keys(setting);for(const k2 of keys3)JSON.stringify(k2 in setting?setting[k2]:"")==JSON.stringify(k2 in DEFAULT_SETTINGS?DEFAULT_SETTINGS[k2]:"*")&&delete setting[k2];const encryptedSetting=encodeURIComponent(await encrypt(JSON.stringify(setting),encryptingPassphrase,!1)),uri=`${configURIBase}${encryptedSetting} `;await navigator.clipboard.writeText(uri);this._log("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}async command_copySetupURIFull(){const encryptingPassphrase=await this.core.confirm.askString("Encrypt your settings","The passphrase to encrypt the setup URI","",!0);if(!1===encryptingPassphrase)return;const setting={...this.settings,configPassphraseStore:"",encryptedCouchDBConnection:"",encryptedPassphrase:""},encryptedSetting=encodeURIComponent(await encrypt(JSON.stringify(setting),encryptingPassphrase,!1)),uri=`${configURIBase}${encryptedSetting} `;await navigator.clipboard.writeText(uri);this._log("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}async command_copySetupURIWithSync(){await this.command_copySetupURI(!1)}async command_openSetupURI(){const setupURI=await this.core.confirm.askString("Easy setup","Set up URI",`${configURIBase} aaaaa`);if(!1===setupURI)return;if(!setupURI.startsWith(`${configURIBase}`)){this._log("Set up URI looks wrong.",LOG_LEVEL_NOTICE);return}const config=decodeURIComponent(setupURI.substring(34));await this.setupWizard(config)}async applySettingWizard(oldConf,newConf,method="Setup URI"){if("yes"==await this.core.confirm.askYesNoDialog("Importing Configuration from the "+method+". Are you sure to proceed ? ",{})){const newSettingW=Object.assign({},DEFAULT_SETTINGS,newConf);this.core.replicator.closeReplication();this.settings.suspendFileWatching=!0;console.dir(newSettingW);newSettingW.configPassphraseStore="";newSettingW.encryptedPassphrase="";newSettingW.encryptedCouchDBConnection="";newSettingW.additionalSuffixOfDatabaseName=`${"appId"in this.app?this.app.appId:""} `;const setupJustImport="Don't sync anything, just apply the settings.",setupAsNew="This is a new client - sync everything from the remote server.",setupAsMerge="This is an existing client - merge existing files with the server.",setupAgain="Initialise new server data - ideal for new or broken servers.",setupManually="Continue and configure manually.";newSettingW.syncInternalFiles=!1;newSettingW.usePluginSync=!1;newSettingW.isConfigured=!0;newSettingW.useIndexedDBAdapter||(newSettingW.useIndexedDBAdapter=!0);const setupType=await this.core.confirm.askSelectStringDialogue("How would you like to set it up?",[setupAsNew,setupAgain,setupAsMerge,setupJustImport,setupManually],{defaultAction:setupAsNew});if(setupType==setupJustImport){this.core.settings=newSettingW;this.core.$$clearUsedPassphrase();await this.core.saveSettings()}else if(setupType==setupAsNew){this.core.settings=newSettingW;this.core.$$clearUsedPassphrase();await this.core.saveSettings();await this.core.rebuilder.$fetchLocal()}else if(setupType==setupAsMerge){this.core.settings=newSettingW;this.core.$$clearUsedPassphrase();await this.core.saveSettings();await this.core.rebuilder.$fetchLocal(!0)}else if(setupType==setupAgain){const confirm="This operation will rebuild all databases with files on this device. Any files on the remote database not synced here will be lost.";if(await this.core.confirm.askSelectStringDialogue("Are you sure you want to do this?",["Cancel",confirm],{defaultAction:"Cancel"})!=confirm)return;this.core.settings=newSettingW;await this.core.saveSettings();this.core.$$clearUsedPassphrase();await this.core.rebuilder.$rebuildEverything()}else if(setupType==setupManually){const keepLocalDB=await this.core.confirm.askYesNoDialog("Keep local DB?",{defaultOption:"No"}),keepRemoteDB=await this.core.confirm.askYesNoDialog("Keep remote DB?",{defaultOption:"No"});if("yes"==keepLocalDB&&"yes"==keepRemoteDB){this.core.settings=newSettingW;this.core.$$clearUsedPassphrase();await this.core.$allSuspendAllSync();await this.core.$allSuspendExtraSync();await this.core.saveSettings();if("yes"==await this.core.confirm.askYesNoDialog("Unlock and replicate?",{defaultOption:"Yes"})){await this.core.$$replicate(!0);await this.core.$$markRemoteUnlocked()}this._log("Configuration loaded.",LOG_LEVEL_NOTICE);return}if("no"==keepLocalDB&&"no"==keepRemoteDB&&"yes"!=await this.core.confirm.askYesNoDialog("Drop everything?",{defaultOption:"No"})){this._log("Cancelled",LOG_LEVEL_NOTICE);this.core.settings=oldConf;return}let initDB;this.core.settings=newSettingW;this.core.$$clearUsedPassphrase();await this.core.saveSettings();if("no"==keepLocalDB){await this.core.$$resetLocalDatabase();await this.core.localDatabase.initializeDatabase();"yes"==await this.core.confirm.askYesNoDialog("Rebuild the database?",{defaultOption:"Yes"})?initDB=this.core.$$initializeDatabase(!0):await this.core.$$markRemoteResolved()}if("no"==keepRemoteDB){await this.core.$$tryResetRemoteDatabase();await this.core.$$markRemoteLocked()}if(("no"==keepLocalDB||"no"==keepRemoteDB)&&"yes"==await this.core.confirm.askYesNoDialog("Replicate once?",{defaultOption:"Yes"})){null!=initDB&&await initDB;await this.core.$$replicate(!0)}}this._log("Configuration loaded.",LOG_LEVEL_NOTICE)}else{this._log("Cancelled",LOG_LEVEL_NOTICE);this.core.settings=oldConf}}async setupWizard(confString){try{const oldConf=JSON.parse(JSON.stringify(this.settings)),encryptingPassphrase=await this.core.confirm.askString("Passphrase","The passphrase to decrypt your setup URI","",!0);if(!1===encryptingPassphrase)return;const newConf=await JSON.parse(await decrypt(confString,encryptingPassphrase,!1));if(newConf){await this.applySettingWizard(oldConf,newConf);this._log("Configuration loaded.",LOG_LEVEL_NOTICE)}else this._log("Cancelled.",LOG_LEVEL_NOTICE)}catch(ex){this._log("Couldn't parse or decrypt configuration uri.",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}}};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)));await this.localDatabase.hashCaches.clear();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.core.$$isTargetFile(path2)){this._log("File is not target",LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log("File should be ignored",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.core.$$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}};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);await isDocContentSame(getDocDataAsArray(entry.data),readFile.body)?markChangesAreSame(file,file.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.core.$$queueConflictCheckIfOpen(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}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.core.$$isTargetFile(path2)){this._log(`File ${path2} is not the target file`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log(`File ${path2} should be ignored`,LOG_LEVEL_VERBOSE);return!1}const lockKey=`processFileEvent-${path2}`;return await serialized(lockKey,(async()=>{switch(type){case"CREATE":case"CHANGED":return await this.storeFileToDB(item.args.file);case"DELETE":return await this.deleteFileFromDB(item.args.file);case"INTERNAL":return!1;default:this._log(`Unsupported event type: ${type}`,LOG_LEVEL_VERBOSE);return!1}}))}async $anyProcessReplicatedDoc(entry){return await serialized(entry.path,(async()=>{var _a8,_b4;if(!await this.core.$$isTargetFile(entry.path)){this._log(`File ${entry.path} is not the target file`,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}{this._log(`Processing ${path2} (${entry._id.substring(0,8)}: ${null==(_a8=entry._rev)?void 0:_a8.substring(0,5)}) :Started...`,LOG_LEVEL_VERBOSE);eventHub.emitEvent("conflict-cancelled",path2);const ret=await this.dbToStorage(entry,targetFile);this._log(`Processing ${path2} (${entry._id.substring(0,8)} :${null==(_b4=entry._rev)?void 0:_b4.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.core.$$isTargetFile(file)){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")}};new(PouchError=class extends Error{constructor(status,error,reason){super();this.status=status;this.name=error;this.message=reason;this.error=!0}toString(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})}})(401,"unauthorized","Name or password is incorrect.");MISSING_BULK_DOCS=new PouchError(400,"bad_request","Missing JSON list of 'docs'");MISSING_DOC=new PouchError(404,"not_found","missing");REV_CONFLICT=new PouchError(409,"conflict","Document update conflict");INVALID_ID=new PouchError(400,"bad_request","_id field must contain a string");MISSING_ID=new PouchError(412,"missing_id","_id is required for puts");RESERVED_ID=new PouchError(400,"bad_request","Only reserved document ids may start with underscore.");new PouchError(412,"precondition_failed","Database not open");UNKNOWN_ERROR=new PouchError(500,"unknown_error","Database encountered an unknown error");BAD_ARG=new PouchError(500,"badarg","Some query argument is invalid");new PouchError(400,"invalid_request","Request was invalid");QUERY_PARSE_ERROR=new PouchError(400,"query_parse_error","Some query parameter is invalid");DOC_VALIDATION=new PouchError(500,"doc_validation","Bad special document member");BAD_REQUEST=new PouchError(400,"bad_request","Something wrong with the request");NOT_AN_OBJECT=new PouchError(400,"bad_request","Document must be a JSON object");new PouchError(404,"not_found","Database not found");IDB_ERROR=new PouchError(500,"indexed_db_went_bad","unknown");new PouchError(500,"web_sql_went_bad","unknown");new PouchError(500,"levelDB_went_went_bad","unknown");new PouchError(403,"forbidden","Forbidden by design doc validate_doc_update function");INVALID_REV=new PouchError(400,"bad_request","Invalid rev format");new PouchError(412,"file_exists","The database could not be created, the file already exists.");MISSING_STUB=new PouchError(412,"missing_stub","A pre-existing attachment stub wasn't found");new PouchError(413,"invalid_url","Provided URL is invalid");rnds82=new Uint8Array(16);regex_default2=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;validate_default2=function validate3(uuid2){return"string"==typeof uuid2&®ex_default2.test(uuid2)};byteToHex2=[];for(i2=0;i2<256;++i2)byteToHex2.push((i2+256).toString(16).substr(1));stringify_default2=function stringify2(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid2=(byteToHex2[arr[offset+0]]+byteToHex2[arr[offset+1]]+byteToHex2[arr[offset+2]]+byteToHex2[arr[offset+3]]+"-"+byteToHex2[arr[offset+4]]+byteToHex2[arr[offset+5]]+"-"+byteToHex2[arr[offset+6]]+byteToHex2[arr[offset+7]]+"-"+byteToHex2[arr[offset+8]]+byteToHex2[arr[offset+9]]+"-"+byteToHex2[arr[offset+10]]+byteToHex2[arr[offset+11]]+byteToHex2[arr[offset+12]]+byteToHex2[arr[offset+13]]+byteToHex2[arr[offset+14]]+byteToHex2[arr[offset+15]]).toLowerCase();if(!validate_default2(uuid2))throw TypeError("Stringified UUID is invalid");return uuid2};v4_default2=function v42(options,buf,offset){var rnds,i2;(rnds=(options=options||{}).random||(options.rng||rng2)())[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;if(buf){offset=offset||0;for(i2=0;i2<16;++i2)buf[offset+i2]=rnds[i2];return buf}return stringify_default2(rnds)};thisAtob=function(str){return atob(str)};thisBtoa=function(str){return btoa(str)};import_spark_md5=__toESM(require_spark_md5());self.setImmediate||self.setTimeout;import_events20=__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_events20.default{constructor(){super();this._listeners={};hasLocalStorage()&&addEventListener("storage",(e3=>{this.emit(e3.key)}))}addListener(dbName,id,db,opts){function eventFunction(){if(self3._listeners[id])if(inprogress)inprogress="waiting";else{inprogress=!0;var changesOpts=pick(opts,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary","return_docs"]);db.changes(changesOpts).on("change",(function(c3){if(c3.seq>opts.since&&!opts.cancelled){opts.since=c3.seq;opts.onChange(c3)}})).on("complete",(function(){"waiting"===inprogress&&nextTick(eventFunction);inprogress=!1})).on("error",(function onError(){inprogress=!1}))}}var inprogress,self3;if(!this._listeners[id]){inprogress=!1;self3=this;this._listeners[id]=eventFunction;this.on(dbName,eventFunction)}}removeListener(dbName,id){if(id in this._listeners){super.removeListener(dbName,this._listeners[id]);delete this._listeners[id]}}notifyLocalWindows(dbName){hasLocalStorage()&&(localStorage[dbName]="a"===localStorage[dbName]?"b":"a")}notify(dbName){this.emit(dbName);this.notifyLocalWindows(dbName)}};(function f2(){}).name;keys2=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];qName="queryKey";qParser=/(?:^|&)([^&=]*)=?([^&]*)/g;parser=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;uuid=v4_default2;f3=fetch;h2=Headers;MIN_MAGNITUDE=-324;MAGNITUDE_DIGITS=3;SEP="";combinationFields=["$or","$nor","$not"];matchers={$elemMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.some((function(val2){return rowFilter(val2,userValue,Object.keys(userValue))})):docFieldValue.some((function(val2){return matchSelector(userValue,doc,parsedField,val2)})))},$allMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.every((function(val2){return rowFilter(val2,userValue,Object.keys(userValue))})):docFieldValue.every((function(val2){return matchSelector(userValue,doc,parsedField,val2)})))},$eq:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&0===collate(docFieldValue,userValue)},$gte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>=0},$gt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>0},$lte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<=0},$lt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<0},$exists:function(doc,userValue,parsedField,docFieldValue){return userValue?fieldIsNotUndefined(docFieldValue):!fieldIsNotUndefined(docFieldValue)},$mod:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&function modField(docFieldValue,userValue){return"number"==typeof docFieldValue&&parseInt(docFieldValue,10)===docFieldValue&&docFieldValue%userValue[0]===userValue[1]}(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)&&function arraySize(docFieldValue,userValue){return docFieldValue.length===userValue}(docFieldValue,userValue)},$all:function(doc,userValue,parsedField,docFieldValue){return Array.isArray(docFieldValue)&&function arrayContainsAllValues(docFieldValue,userValue){return userValue.every((function(val2){return docFieldValue.some((function(docFieldValueItem){return 0===collate(val2,docFieldValueItem)}))}))}(docFieldValue,userValue)},$regex:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&"string"==typeof docFieldValue&&userValue.every((function(regexValue){return function regexMatch(docFieldValue,userValue){return new RegExp(userValue).test(docFieldValue)}(docFieldValue,regexValue)}))},$type:function(doc,userValue,parsedField,docFieldValue){return function typeMatch(docFieldValue,userValue){switch(userValue){case"null":return null===docFieldValue;case"boolean":return"boolean"==typeof docFieldValue;case"number":return"number"==typeof docFieldValue;case"string":return"string"==typeof docFieldValue;case"array":return docFieldValue instanceof Array;case"object":return"[object Object]"==={}.toString.call(docFieldValue)}}(docFieldValue,userValue)}};index_browser_es_default=function applyChangesFilterPlugin(PouchDB2){PouchDB2._changesFilterPlugin={validate:validate4,normalize,shouldFilter,filter:filter2}};import_events21=__toESM(require_events());Changes2=class extends import_events21.default{constructor(db,opts,callback){var complete,promise;super();this.db=db;opts=opts?clone2(opts):{};complete=opts.complete=once2(((err2,resp)=>{err2?function listenerCount(ee,type){return"listenerCount"in ee?ee.listenerCount(type):import_events20.default.listenerCount(ee,type)}(this,"error")>0&&this.emit("error",err2):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,pending2,lastSeq)=>{this.isCancelled||function tryCatchInChangeListener(self3,change,pending2,lastSeq){try{self3.emit("change",change,pending2,lastSeq)}catch(e3){guardedConsole("error",'Error in .on("change", function):',e3)}}(this,change,pending2,lastSeq)};promise=new Promise((function(fulfill,reject){opts.complete=function(err2,res2){err2?reject(err2):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,(err2=>{if(err2)return callback(err2);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(key2){key2 in opts&&guardedConsole("warn",'The "'+key2+'" 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_events21.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(err2){var result=err2?null:{ok:!0,id:doc._id,rev:doc._rev};cb2(err2,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(err2){if(err2.reason===MISSING_DOC.message)return createAttachment({_id:docId});throw err2}))})).bind(this);this.removeAttachment=adapterFun("removeAttachment",(function(docId,attachmentId,rev$$1,callback){this.get(docId,((err2,obj)=>{if(err2)callback(err2);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)}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(err2,rev_tree){if(err2&&404===err2.status&&"missing"===err2.message)missing.set(id,{missing:req[id]});else{if(err2)return callback(err2);(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)}))})(id,rev_tree)}if(++count===ids.length){var missingObj={};missing.forEach((function(value,key2){missingObj[key2]=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,((err2,revTree)=>{var height,candidates,revs;if(err2)return callback(err2);height=function computeHeight(revs){var height={},edges=[];traverseRevTree(revs,(function(isLeaf,pos,id,prnt){var rev$$1=pos+"-"+id;isLeaf&&(height[rev$$1]=0);void 0!==prnt&&edges.push({from:prnt,to:rev$$1});return rev$$1}));edges.reverse();edges.forEach((function(edge){void 0===height[edge.from]?height[edge.from]=1+height[edge.to]:height[edge.from]=Math.min(height[edge.from],1+height[edge.to])}));return height}(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(err2,doc){var existing,i3,l3;if(err2)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,key2;if(err2){err2.docId=id;return cb2(err2)}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){(err2=new Error("invalid rev tree")).docId=id;return cb2(err2)}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((key3=>{this._getAttachment(doc._id,key3,attachments[key3],{binary:opts.binary,metadata,ctx},(function(err3,data){var att=doc._attachments[key3];att.data=data;delete att.stub;delete att.length;--count||cb2(null,doc)}))}))}else{if(doc._attachments)for(key2 in doc._attachments)Object.prototype.hasOwnProperty.call(doc._attachments,key2)&&(doc._attachments[key2].stub=!0);cb2(null,doc)}}));if("all"===opts.open_revs)this._getRevisionTree(id,(function(err2,rev_tree){if(err2)return cb2(err2);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(err2)return callback(err2);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)){(function allDocsKeysParse(opts){var keys3="limit"in opts?opts.keys.slice(opts.skip,opts.limit+opts.skip):opts.skip>0?opts.keys.slice(opts.skip):opts.keys;opts.keys=keys3;opts.skip=0;delete opts.limit;if(opts.descending){keys3.reverse();opts.descending=!1}})(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(((err2,info3)=>{if(err2)return callback(err2);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,((err2,resp)=>{if(err2)return callback(err2);this._destroyed=!0;this.emit("destroyed");callback(null,resp||{ok:!0})}))};if(isRemote(this))return destroyDb();this.get("_local/_pouch_dependentDbs",((err2,localDoc)=>{var dependentDbs,PouchDB2,deletedMap;if(err2)return 404!==err2.status?callback(err2):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=err2=>{this.activeTasks.remove(taskId,err2);callback(err2)},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);(function appendPurgeSeq(db,docId,rev$$1){return db.get("_local/purges").then((function(doc){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>self.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-self.purged_infos_limit);doc.purgeSeq=purgeSeq;return doc})).catch((function(err2){if(404!==err2.status)throw err2;return{_id:"_local/purges",purges:[{docId,rev:rev$$1,purgeSeq:0}],purgeSeq:0}})).then((function(doc){return db.put(doc)}))})(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(err2){this.failed=err2;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=function parseAdapter(name,opts){var adapters,preferredAdapters,prefix,adapterName,i2,adapter,match3=name.match(/([a-z-]*):\/\/(.*)/);if(match3)return{name:/https?/.test(match3[1])?match3[1]+"://"+match3[2]:match3[2],adapter:match3[1]};adapters=PouchDB.adapters;preferredAdapters=PouchDB.preferredAdapters;prefix=PouchDB.prefix;if(!(adapterName=opts.adapter))for(i2=0;i2{if(err2)return this.taskqueue.fail(err2);(function prepareForDestruction(self3){function onDestroyed(from_constructor){self3.removeListener("closed",onClosed);from_constructor||self3.constructor.emit("destroyed",self3.name)}function onClosed(){self3.removeListener("destroyed",onDestroyed);self3.constructor.emit("unref",self3)}self3.once("destroyed",onDestroyed);self3.once("closed",onClosed);self3.constructor.emit("ref",self3)})(this);this.emit("created",this);PouchDB.emit("created",this.name);this.taskqueue.ready(this)}))}};PouchDB=createClass(PouchInternal,(function(name,opts){PouchInternal.prototype._setup.call(this,name,opts)}));ActiveTasks=class{constructor(){this.tasks={}}list(){return Object.values(this.tasks)}add(task){const id=v4_default2();this.tasks[id]={id,name:task.name,total_items:task.total_items,created_at:(new Date).toJSON()};return id}get(id){return this.tasks[id]}remove(id,reason){delete this.tasks[id];return this.tasks}update(id,updatedTask){const task=this.tasks[id];if(void 0!==task){const mergedTask={id:task.id,name:task.name,created_at:task.created_at,total_items:updatedTask.total_items||task.total_items,completed_items:updatedTask.completed_items||task.completed_items,updated_at:(new Date).toJSON()};this.tasks[id]=mergedTask}return this.tasks}};PouchDB.adapters={};PouchDB.preferredAdapters=[];PouchDB.prefix="_pouch_";eventEmitter=new import_events21.default;(function setUpEventEmitter(Pouch){Object.keys(import_events21.default.prototype).forEach((function(key2){"function"==typeof import_events21.default.prototype[key2]&&(Pouch[key2]=eventEmitter[key2].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(key2){key2 in PouchWithDefaults||(PouchWithDefaults[key2]=PouchDB[key2])}));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());import_spark_md52=__toESM(require_spark_md5());setImmediateShim2=self.setImmediate||self.setTimeout;MD5_CHUNK_SIZE2=32768;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)};import_spark_md53=__toESM(require_spark_md5());setImmediateShim3=self.setImmediate||self.setTimeout;MD5_CHUNK_SIZE3=32768;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){}}};import_spark_md54=__toESM(require_spark_md5());self.setImmediate||self.setTimeout;persistentQueues={};tempViewQueue=new(TaskQueue2=class{constructor(){this.promise=Promise.resolve()}add(promiseFactory){this.promise=this.promise.catch((()=>{})).then((()=>promiseFactory()));return this.promise}finish(){return this.promise}});index_es_default5=function createAbstractMapReduce(localDocName2,mapper3,reducer3,ddocValidator3){function tryMap(db,fun,doc){try{fun(doc)}catch(e3){emitError(db,e3,{fun,doc})}}function tryReduce(db,fun,keys3,values,rereduce){try{return{output:fun(keys3,values,rereduce)}}catch(e3){emitError(db,e3,{fun,keys:keys3,values,rereduce});return{error:e3}}}function sortByKeyThenValue(x2,y2){const keyCompare=collate(x2.key,y2.key);return 0!==keyCompare?keyCompare:collate(x2.value,y2.value)}function sliceResults(results,limit,skip){skip=skip||0;return"number"==typeof limit?results.slice(skip,limit+skip):skip>0?results.slice(skip):results}function rowToDocId(row){const val2=row.value;return val2&&"object"==typeof val2&&val2._id||row.id}function postprocessAttachments(opts){return function(res2){opts.include_docs&&opts.attachments&&opts.binary&&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)}}}(res2);return res2}}function addHttpParam(paramName,opts,params,asJson){let val2=opts[paramName];if(void 0!==val2){asJson&&(val2=encodeURIComponent(JSON.stringify(val2)));params.push(paramName+"="+val2)}}function coerceInteger(integerCandidate){if(void 0!==integerCandidate){const asNumber=Number(integerCandidate);return isNaN(asNumber)||asNumber!==parseInt(integerCandidate,10)?integerCandidate:asNumber}}function 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}}function defaultsTo(value){return function(reason){if(404===reason.status)return value;throw reason}}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 async function updateViewInQueue(view,opts){function createIndexableKeysToKeyValues(mapResults2){const indexableKeysToKeyValues=new Map;let lastKey;for(let i2=0,len=mapResults2.length;i20&&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(key2,value){const output={id:doc._id,key:normalizeKey(key2)};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 async function processNextBatch(){return 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=function createDocIdsToChangesAndEmits(results){const docIdsToChangesAndEmits=new Map;for(const change of results){if("_"!==change.doc._id[0]){mapResults=[];doc=change.doc;doc._deleted||tryMap(view.sourceDB,mapFun,doc);mapResults.sort(sortByKeyThenValue);const indexableKeysToKeyValues=createIndexableKeysToKeyValues(mapResults);docIdsToChangesAndEmits.set(change.doc._id,[indexableKeysToKeyValues,change.changes])}currentSeq=change.seq}return docIdsToChangesAndEmits}(results);queue2.add(function processChange2(docIdsToChangesAndEmits,seq){return function(){return 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 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 function isGenOne(changes3){return 1===changes3.length&&/^1-/.test(changes3[0].rev)}(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 key2 of newKeys)if(!oldKeys.has(key2)){const kvDoc={_id:key2},keyValue=indexableKeysToKeyValues.get(key2);"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))}(docId,view,docIdsToChangesAndEmits)}))).then((function(listOfDocsToPersist){var docsToPersist=listOfDocsToPersist.flat();lastSeqDoc.seq=seq;docsToPersist.push(lastSeqDoc);return view.db.bulkDocs({docs:docsToPersist})})).then((()=>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(err2){if(404!==err2.status)throw err2}))}(view)))}))}(view,docIdsToChangesAndEmits,seq)}}(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.lengthpurgeSeq})).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([]))}))}())}();await queue2.finish();view.seq=currentSeq;view.sourceDB.activeTasks.remove(taskId)}catch(error){view.sourceDB.activeTasks.remove(taskId,error)}}(view,opts)}))()}function queryView(view,opts){return sequentialize(getQueue(view),(function(){return 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=function parseIndexableString(str){for(var collationIndex2,parsedNum,parsedStr,ch4,arrayElement,objElement,stack2=[],metaStack=[],i2=0;;)if("\0"!==(collationIndex2=str[i2++]))switch(collationIndex2){case"1":stack2.push(null);break;case"2":stack2.push("1"===str[i2]);i2++;break;case"3":parsedNum=parseNumber2(str,i2);stack2.push(parsedNum.num);i2+=parsedNum.length;break;case"4":parsedStr="";for(;"\0"!==(ch4=str[i2]);){parsedStr+=ch4;i2++}parsedStr=parsedStr.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"");stack2.push(parsedStr);break;case"5":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"6":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop2(stack2,metaStack)}}(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?function reduceView(view,results,options){0===options.group_level&&delete options.group_level;const shouldGroup=options.group||options.group_level,reduceFun=reducer3(view.reduceFun),groups=[],lvl=isNaN(options.group_level)?Number.POSITIVE_INFINITY:options.group_level;for(const result of results){const last=groups[groups.length-1];let groupKey=shouldGroup?result.key:null;shouldGroup&&Array.isArray(groupKey)&&(groupKey=groupKey.slice(0,lvl));if(last&&0===collate(last.groupKey,groupKey)){last.keys.push([result.key,result.id]);last.values.push(result.value)}else groups.push({keys:[[result.key,result.id]],values:[result.value],groupKey})}results=[];for(const group of groups){const reduceTry=tryReduce(view.sourceDB,reduceFun,group.keys,group.values,!1);if(reduceTry.error&&reduceTry.error instanceof BuiltInError)throw reduceTry.error;results.push({value:reduceTry.error?null:reduceTry.output,key:group.groupKey})}return{rows:sliceResults(results,options.limit,options.skip)}}(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(key2){const viewOpts={startkey:toIndexableString([key2]),endkey:toIndexableString([key2,{}])};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))}}(view,opts)}))()}return{query:function abstractQuery(fun,opts,callback){const db=this;if("function"==typeof opts){callback=opts;opts={}}opts=opts?function coerceOptions(opts){opts.group_level=coerceInteger(opts.group_level);opts.limit=coerceInteger(opts.limit);opts.skip=coerceInteger(opts.skip);return opts}(opts):{};"function"==typeof fun&&(fun={map:fun});const promise=Promise.resolve().then((function(){return async function queryPromised(db,fun,opts){if("function"==typeof db._query)return function customQuery(db,fun,opts){return new Promise((function(resolve,reject){db._query(fun,opts,(function(err2,res2){if(err2)return reject(err2);resolve(res2)}))}))}(db,fun,opts);if(isRemote(db))return 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 key2 of Object.keys(fun))Array.isArray(fun[key2])?body[key2]=fun[key2]:body[key2]=fun[key2].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))}(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 function fin(promise,finalPromiseFactory){return promise.then((function(res2){return finalPromiseFactory().then((function(){return res2}))}),(function(reason){return finalPromiseFactory().then((function(){throw reason}))}))}(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)}}(db,fun,opts)}));promisedCallback(promise,callback);return promise},viewCleanup:function callbackify(fun){return function(...args){var cb2=args.pop(),promise=fun.apply(this,args);"function"==typeof cb2&&promisedCallback(promise,cb2);return promise}}((function(){const db=this;return"function"==typeof db._viewCleanup?function customViewCleanup(db){return new Promise((function(resolve,reject){db._viewCleanup((function(err2,res2){if(err2)return reject(err2);resolve(res2)}))}))}(db):isRemote(db)?async function httpViewCleanup(db){return(await db.fetch("_view_cleanup",{headers:new h2({"Content-Type":"application/json"}),method:"POST"})).json()}(db):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(err2){if(404===err2.status)return{ok:!0};throw err2}}(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_events22.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}),(err2=>{this.cancel();callback?callback(err2):this.emit("error",err2);this.removeAllListeners();if(callback)throw err2}));this.then=function(success,err2){return promise.then(success,err2)};this.catch=function(err2){return promise.catch(err2)}}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)}};import_spark_md56=__toESM(require_spark_md5());self.setImmediate||self.setTimeout;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};flatten="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 function createMapper(fields,emit2,selector){const isShallow=function checkShallow(fields){return fields.every((field=>-1===field.indexOf(".")))}(fields),isSingle=1===fields.length;return isShallow?isSingle?function createShallowSingleMapper(field,emit2,selector){return function(doc){selector&&!matchesSelector(doc,selector)||emit2(doc[field])}}(fields[0],emit2,selector):function createShallowMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=fields.map((field=>doc[field]));emit2(toEmit)}}(fields,emit2,selector):isSingle?function createDeepSingleMapper(field,emit2,selector){const parsedField=parseField(field);return function(doc){if(selector&&!matchesSelector(doc,selector))return;const value=getDeepValue(doc,parsedField);void 0!==value&&emit2(value)}}(fields[0],emit2,selector):function createDeepMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=[];for(const field of fields){const value=getDeepValue(doc,parseField(field));if(void 0===value)return;toEmit.push(value)}emit2(toEmit)}}(fields,emit2,selector)}(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 async function mapAllTasksWithConcurrencyLimit(limit,tasks3){const results=new Map;for await(const v2 of 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}}(limit,tasks3))results.set(v2.key,v2);return[...results.entries()].sort(((a2,b3)=>a2[0]-b3[0])).map((e3=>e3[1]))}(1,tasks3)).map((e3=>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")}(e3)));await function appendPurgeSeqs(db,docs){return db.get("_local/purges").then((function(doc){for(const[docId,rev$$1]of docs){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>db.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-db.purged_infos_limit);doc.purgeSeq=purgeSeq}return doc})).catch((function(err2){if(404!==err2.status)throw err2;return{_id:"_local/purges",purges:docs.map((([docId,rev$$1],idx2)=>({docId,rev:rev$$1,purgeSeq:idx2}))),purgeSeq:docs.length}})).then((function(doc){return db.put(doc)}))}(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)))}));import_obsidian.Notice;ModuleObsidianAPI=class extends AbstractObsidianModule{constructor(){super(...arguments);this._authHeader=new AuthorizationHeaderGenerator;this.last_successful_post=!1}$$customFetchHandler(){this._customHandler||(this._customHandler=new ObsHttpHandler(void 0,void 0));return this._customHandler}$$getLastPostFailedBySize(){return!this.last_successful_post}async _fetchByAPI(url,authHeader,opts){var _a8,_b4;const body=null==opts?void 0:opts.body,transformedHeaders={...null==opts?void 0:opts.headers};""!=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!=(_b4=null!=(_a8=null==transformedHeaders?void 0:transformedHeaders["content-type"])?_a8:null==transformedHeaders?void 0:transformedHeaders["Content-Type"])?_b4:"application/json"},r4=await async function fetchByAPI(request2,errorAsResult=!1){return await(0,import_obsidian.requestUrl)({...request2,throw:!errorAsResult})}(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}`,-1);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){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.";const db=new index_es_default(uri,{adapter:"http",auth:"username"in auth?auth:void 0,skip_setup:!performSetup,fetch:async(url,opts)=>{var _a8;const authHeader=await this._authHeader.getAuthorizationHeader(auth);let size="";const localURL=url.toString().substring(uri.length),method=null!=(_a8=null==opts?void 0:opts.method)?_a8:"GET";if(null==opts?void 0:opts.body){const opts_length=opts.body.toString().length;if(opts_length>1e7&&isCloudantURI(uri)){this.last_successful_post=!1;this._log("This request should fail on IBM Cloudant.",LOG_LEVEL_VERBOSE);throw new Error("This request should fail on IBM Cloudant.")}size=` (${opts_length})`}try{const headers=new Headers(null==opts?void 0:opts.headers);if(customHeaders)for(const[key2,value]of Object.entries(customHeaders))key2&&value&&headers.append(key2,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}`,-1);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)}}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._log("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._log(`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._log(`Failed to fetch: ${msg}`,LOG_LEVEL_NOTICE);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);(function disableEncryption(){preprocessOutgoing=async doc=>await Promise.resolve(doc)})();"false"!==passphrase&&"string"==typeof passphrase&&enableEncryption(db,passphrase,useDynamicIterationCount,!1);if(skipInfo)return{db,info:{db_name:"",doc_count:0,update_seq:""}};try{const info3=await db.info();return{db,info:info3}}catch(ex){const msg=`${null==ex?void 0:ex.name}:${null==ex?void 0:ex.message}`;this._log(ex,LOG_LEVEL_VERBOSE);return msg}}$$isMobile(){return this.app.isMobile}$$vaultName(){return this.app.vault.getName()}$$getVaultName(){var _a8;return this.core.$$vaultName()+((null==(_a8=this.settings)?void 0:_a8.additionalSuffixOfDatabaseName)?"-"+this.settings.additionalSuffixOfDatabaseName:"")}$$getActiveFilePath(){const file=this.app.workspace.getActiveFile();if(file)return getPathFromTFile(file)}$anyGetAppId(){return Promise.resolve(`${"appId"in this.app?this.app.appId:""}`)}};ModuleObsidianEvents=class extends AbstractObsidianModule{constructor(){super(...arguments);this.hasFocus=!0;this.isLastHidden=!1}$everyOnloadStart(){this.plugin.registerEvent(this.app.vault.on("rename",((file,oldPath)=>{eventHub.emitEvent("file-renamed",{newPath:file.path,old:oldPath})})));this.plugin.registerEvent(this.app.workspace.on("active-leaf-change",(()=>eventHub.emitEvent("leaf-active-changed"))));return Promise.resolve(!0)}$$performRestart(){this._performAppReload()}_performAppReload(){this.app.commands.executeCommandById("app:reload")}swapSaveCommand(){var _a8,_b4;this._log("Modifying callback of the save command",LOG_LEVEL_VERBOSE);const saveCommandDefinition=null==(_b4=null==(_a8=this.app.commands)?void 0:_a8.commands)?void 0:_b4["editor:save-file"],save=null==saveCommandDefinition?void 0:saveCommandDefinition.callback;if("function"==typeof save){this.initialCallback=save;saveCommandDefinition.callback=()=>{scheduleTask("syncOnEditorSave",250,(()=>{if(this.core.$$isUnloaded()){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.core.$$replicateByEvent()))}}));save()}}const _this=this;window.CodeMirrorAdapter.commands.save=()=>{_this.app.commands.executeCommandById("editor:save-file")}}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.core.$$performFullScan()}}async watchWindowVisibilityAsync(){if(this.settings.suspendFileWatching)return;if(!this.settings.isConfigured)return;if(!this.core.$$isReady())return;if(this.isLastHidden&&!this.hasFocus)return;const isHidden=document.hidden;if(this.isLastHidden!==isHidden){this.isLastHidden=isHidden;await this.core.$everyCommitPendingFileEvent();if(isHidden)await this.core.$everyBeforeSuspendProcess();else{if(this.core.$$isSuspended())return;if(!this.hasFocus)return;await this.core.$everyOnResumeProcess();await this.core.$everyAfterResumeProcess()}}}watchWorkspaceOpen(file){this.settings.suspendFileWatching||this.settings.isConfigured&&this.core.$$isReady()&&file&&scheduleTask("watch-workspace-open",500,(()=>fireAndForget((()=>this.watchWorkspaceOpenAsync(file)))))}async watchWorkspaceOpenAsync(file){if(!this.settings.suspendFileWatching&&this.settings.isConfigured&&this.core.$$isReady()){await this.core.$everyCommitPendingFileEvent();if(null!=file){this.settings.syncOnFileOpen&&!this.core.$$isSuspended()&&await this.core.$$replicateByEvent();await this.core.$$queueConflictCheckIfOpen(file.path)}}}$everyOnLayoutReady(){this.swapSaveCommand();this.registerWatchEvents();return Promise.resolve(!0)}$$askReload(message){this.core.$$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.core.$$scheduleAppReload()}))}$$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}))}}};combineOnUpdate=(func1,func2)=>()=>({...func1(),...func2()});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:}};import_obsidian11=require("obsidian");LiveSyncSetting=class _LiveSyncSetting extends import_obsidian11.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(key2,value){var _a8,_b4,_c3,_d2;{const paneName=findAttrFromParent(this.settingEl,"data-pane"),panelName=findAttrFromParent(this.settingEl,"data-panel");(function createStub(name,key2,value,panel,pane){var _a8;{pane in stubs||(stubs[pane]={});panel in stubs[pane]||(stubs[pane][panel]=new Map);const old=null!=(_a8=stubs[pane][panel].get(name))?_a8:{};stubs[pane][panel].set(name,{...old,[key2]:value});scheduleTask("update-stub",100,(()=>{eventHub.emitEvent("document-stub-created",{toc,stub:stubs})}))}})("string"==typeof this.nameBuf?this.nameBuf:null!=(_b4=null==(_a8=this.nameBuf.textContent)?void 0:_a8.toString())?_b4:"",key2,"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(key2,opt){this.autoWireSetting(key2,opt);return this}autoWireSetting(key2,opt){const conf=getConfig(key2);if(!conf)return;const name=`${conf.name}${statusDisplay(conf.status)}`;this.setName(name);conf.desc&&this.setDesc(conf.desc);this._createDocStub("key",key2);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=key2;(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_obsidian11.TextComponent&&component2.setPlaceholder(this.placeHolderBuf);(null==opt?void 0:opt.onUpdate)&&this.addOnUpdate(opt.onUpdate)}async commitValue(value){const key2=this.selfKey;if(void 0!==key2&&value!=_LiveSyncSetting.env.editingSettings[key2]){_LiveSyncSetting.env.editingSettings[key2]=value;this.holdValue||await _LiveSyncSetting.env.saveSettings([key2])}_LiveSyncSetting.env.requestUpdate()}autoWireText(key2,opt){const conf=this.autoWireSetting(key2,opt);this.addText((text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo((value=>{text2.setValue(value)}));this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key2]}`);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(key2,opt){const conf=this.autoWireSetting(key2,opt);this.addTextArea((text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo((value=>{text2.setValue(value)}));this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key2]}`);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(key2,opt){const conf=this.autoWireSetting(key2,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[key2]}`)};this.invalidateValue();text2.onChange((async TextValue=>{var _a8,_b4;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==(_a8=opt.clampMin)?void 0:_a8.toString())||"~",max:(null==(_b4=opt.clampMax)?void 0:_b4.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(key2,opt){const conf=this.autoWireSetting(key2,opt);this.addToggle((toggle=>{this.autoWiredComponent=toggle;const setValue=wrapMemo((value=>{toggle.setValue((null==opt?void 0:opt.invert)?!value:value)}));this.invalidateValue=()=>{var _a8;return setValue(null!=(_a8=_LiveSyncSetting.env.editingSettings[key2])&&_a8)};this.invalidateValue();toggle.onChange((async value=>{await this.commitValue((null==opt?void 0:opt.invert)?!value:value)}));this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}autoWireDropDown(key2,opt){const conf=this.autoWireSetting(key2,opt);this.addDropdown((dropdown=>{this.autoWiredComponent=dropdown;const setValue=wrapMemo((value=>{dropdown.setValue(value)}));dropdown.addOptions(opt.options);this.invalidateValue=()=>setValue(_LiveSyncSetting.env.editingSettings[key2]||"");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_obsidian11.ButtonComponent&&(newConf[k2]?component2.setCta():component2.removeCta());this.prevStatus[k2]=newConf[k2]}break;case"isWarning":{const component2=this.autoWiredComponent;component2 instanceof import_obsidian11.ButtonComponent&&newConf[k2]&&component2.setWarning();this.prevStatus[k2]=newConf[k2]}break}}}_onUpdate(){var _a8,_b4;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!=(_b4=null==(_a8=_LiveSyncSetting.env.initialSettings)?void 0:_a8[this.selfKey])?_b4:"")}):"";this.controlEl.toggleClass("sls-item-dirty",isDirty2);if(!this.hasPassword){this.nameEl.toggleClass("sls-item-dirty-help",isDirty2);this.setTooltip(alt,{delay:10,placement:"right"})}}this._applyOnUpdateHandlers()}};updateInformation='## 0.24.31\n\n10th July, 2025\n\n### Fixed\n\n- The description of `Enable Developers\' Debug Tools.` has been refined.\n - Now performance impact is more clearly stated.\n- Automatic conflict checking and resolution has been improved.\n - It now works parallelly for each other file, instead of sequentially. It makes significantly faster on first synchronisation when with local files information.\n- Resolving conflicts dialogue will not be shown for the multiple files at once.\n - It will be shown for each file, one by one.\n\n## 0.24.30\n\n9th July, 2025\n\n### New Feature\n\n- New chunking algorithm `V3: Fine deduplication` has been added, and will be recommended after updates.\n - The Rabin-Karp algorithm is used for efficient chunking.\n - This will be the default in the new installations.\n - It is more robust and faster than the previous one.\n - We can change it in the `Advanced` pane of the settings.\n- New language `ko` (Korean) has been added.\n - Thank you for your contribution, [@ellixspace](https://x.com/ellixspace)!\n - Any contributions are welcome, from any route. Please let me know if I seem to be unaware of this. It is often the case that I am not really aware of it.\n- Chinese (Simplified) translation has been updated.\n - Thank you for your contribution, [@52sanmao](https://github.com/52sanmao)!\n\n### Fixed\n\n- Numeric settings are now never lost the focus during value changing.\n- Doctor now redacts more sensitive information on error reports.\n\n### Improved\n\n- All translations have been rewritten into YAML format, to easier to manage and contribute.\n - We can write them with comments, newlines, and other YAML features.\n- Doctor recommendations are now shown in a user-friendly notation.\n - We can now see the recommended as `V3: Fine deduplication` instead of `v3-rabin-karp`.\n\n### Refactored\n\n- Never-ending `ObsidianLiveSyncSettingTab.ts` has finally been separated into each pane\'s file.\n- Some commented-out code has been removed.\n\n### Acknowledgement\n\n- Jun Murakami, Shun Ishiguro, and Yoshihiro Oyama. 2012. Implementation and Evaluation of a Cache Deduplication Mechanism with Content-Defined Chunking. In _IPSJ SIG Technical Report_, Vol.2012-ARC-202, No.4. Information Processing Society of Japan, 1-7.\n\n## 0.24.29\n\n20th June, 2025\n\n### Fixed\n\n- Synchronisation with buckets now works correctly, regardless of whether a prefix is set or the bucket has been (re-) initialised (#664).\n- An information message is now displayed again, during any automatic synchronisation is enabled (#662).\n\n### Tidied up\n\n- Importing paths have been tidied up.\n\n## 0.24.28\n\n15th June, 2025\n\n### Fixed\n\n- Batch Update is no longer available in LiveSync mode to avoid unexpected behaviour. (#653)\n- Now compatible with Cloudflare R2 again for bucket synchronisation.\n - @edo-bari-ikutsu, thank you for [your contribution](https://github.com/vrtmrz/livesync-commonlib/pull/12)!\n- Prevention of broken behaviour due to database connection failures added (#649).\n\n## 0.24.27\n\n10th June, 2025\n\n### Improved\n\n- We can use prefix for path for the Bucket synchronisation.\n - For example, if you set the `vaultName/` as a prefix for the bucket in the root directory, all data will be transferred to the bucket under the `vaultName/` directory.\n- The "Use Request API to avoid `inevitable` CORS problem" option is now promoted to the normal setting, not a niche patch.\n\n### Fixed\n\n- Now switching replicators applied immediately, without the need to restart Obsidian.\n\n### Tidied up\n\n- Some dependencies have been updated to the latest version.\n\n## 0.24.26\n\n14th May, 2025\n\nThis update introduces an option to circumvent Cross-Origin Resource Sharing\n(CORS) constraints for CouchDB requests, by leveraging Obsidian\'s native request\nAPI. The implementation of such a feature had previously been deferred due to\nsignificant security considerations.\n\nCORS is a vital security mechanism, enabling servers like CouchDB -- which\nfunctions as a sophisticated REST API -- to control access from different\norigins, thereby ensuring secure communication across trust boundaries. I had\nlong hesitated to offer a CORS circumvention method, as it deviates from\nsecurity best practices; My preference was for users to configure CORS correctly\non the server-side.\n\nHowever, this policy has shifted due to specific reports of intractable\nCORS-related configuration issues, particularly within enterprise proxy\nenvironments where proxy servers can unpredictably alter or block\ncommunications. Given that a primary objective of the "Self-hosted LiveSync"\nplugin is to facilitate secure Obsidian usage within stringent corporate\nsettings, addressing these \'unavoidable\' user-reported problems became\nessential. Mostly raison d\'être of this plugin.\n\nConsequently, the option "Use Request API to avoid `inevitable` CORS problem"\nhas been implemented. Users are strongly advised to enable this _only_ when\noperating within a trusted environment. We can enable this option in the `Patch` pane.\n\nHowever, just to whisper, this is tremendously fast.\n\n### New Features\n\n- Automatic display-language changing according to the Obsidian language\n setting.\n - We will be asked on the migration or first startup.\n - **Note: Please revert to the default language if you report any issues.**\n - Not all messages are translated yet. We welcome your contribution!\n- Now we can limit files to be synchronised even in the hidden files.\n- "Use Request API to avoid `inevitable` CORS problem" has been implemented.\n - Less secure, please use it only if you are sure that you are in the trusted\n environment and be able to ignore the CORS. No `Web viewer` or similar tools\n are recommended. (To avoid the origin forged attack). If you are able to\n configure the server setting, always that is recommended.\n- `Show status icon instead of file warnings banner` has been implemented.\n - If enabled, the ⛔ icon will be shown inside the status instead of the file\n warnings banner. No details will be shown.\n\n### Improved\n\n- All regular expressions can be inverted by prefixing `!!` now.\n\n### Fixed\n\n- No longer unexpected files will be gathered during hidden file sync.\n- No longer broken `\\n` and new-line characters during the bucket\n synchronisation.\n- We can purge the remote bucket again if we using MinIO instead of AWS S3 or\n Cloudflare R2.\n- Purging the remote bucket is now more reliable.\n - 100 files are purged at a time.\n- Some wrong messages have been fixed.\n\n### Behaviour changed\n\n- Entering into the deeper directories to gather the hidden files is now limited\n by `/` or `\\/` prefixed ignore filters. (It means that directories are scanned\n deeper than before).\n - However, inside the these directories, the files are still limited by the\n ignore filters.\n\n### Etcetera\n\n- Some code has been tidied up.\n- Trying less warning-suppressing and be more safer-coding.\n- Dependent libraries have been updated to the latest version.\n- Some build processes have been separated to `pre` and `post` processes.\n\nOlder notes are in\n[updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md).\n';lastVersion=~~(versionNumberString2Number("0.24.31")/1e3);import_obsidian12=require("obsidian");root_110=template('
  • ');root5=template('
    ');$$css6={hash:"svelte-1rsazmf",code:"label.svelte-1rsazmf {min-width:4em;width:4em;display:inline-flex;flex-direction:row;justify-content:flex-end;}ul.svelte-1rsazmf {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-1rsazmf {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-1rsazmf input:where(.svelte-1rsazmf) {min-width:10em;}button.iconbutton.svelte-1rsazmf {max-width:4em;}.chip.svelte-1rsazmf {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-1rsazmf:empty {display:none;}"};EVENT_REQUEST_SHOW_HISTORY="show-history";LocalDatabaseMaintenance=class extends LiveSyncCommands{$everyOnload(){return Promise.resolve(!0)}onunload(){}onload(){}async allChunks(includeDeleted=!1){const p4=this._progress("",LOG_LEVEL_NOTICE);p4.log("Retrieving chunks informations..");try{return await this.localDatabase.allChunks(includeDeleted)}finally{p4.done()}}get database(){return this.localDatabase.localDatabase}clearHash(){this.localDatabase.hashCaches.clear()}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((([key2,e3])=>e3._deleted)).filter((([key2,e3])=>used.has(e3._id))).map((([key2,e3])=>e3)),completelyLostChunks=[],dataLostChunks=[...existing].filter((([key2,e3])=>e3._deleted&&""===e3.data)).map((([key2,e3])=>e3)).filter((e3=>used.has(e3._id)));for(const e3 of dataLostChunks){let resurrected=null;const availableRevs=((await this.database.get(e3._id,{rev:e3._rev,revs:!0,revs_info:!0,conflicts:!0}))._revs_info||[]).filter((e4=>"available"==e4.status)).map((e4=>e4.rev)).sort(((a2,b3)=>getNoFromRev(a2)-getNoFromRev(b3)));for(const rev3 of availableRevs){const revDoc=await this.database.get(e3._id,{rev:rev3});if("leaf"==revDoc.type&&""!==revDoc.data){resurrected=revDoc.data;break}}null!==resurrected?excessiveDeletions.push({...e3,data:resurrected,_deleted:!1}):completelyLostChunks.push(e3._id)}const resurrectChunks=excessiveDeletions.filter((e3=>""!==e3.data)).map((e3=>({...e3,_deleted:!1})));if(0==resurrectChunks.length){this._notice("No chunks are found to be resurrected.");return}const message=`We have following chunks that are deleted but still used in the database.\n\n- Completely lost chunks: ${completelyLostChunks.length}\n- Resurrectable chunks: ${resurrectChunks.length}\n\nDo you want to resurrect these chunks?`;if(await this.confirm("Resurrect Chunks",message,"Resurrect","Cancel")){const result=await this.database.bulkDocs(resurrectChunks);this.clearHash();const resurrectedChunks=result.filter((e3=>"ok"in e3)).map((e3=>e3.id));this._notice(`Resurrected chunks: ${resurrectedChunks.length} / ${resurrectChunks.length}`)}else this._notice("Resurrect operation is cancelled.")}async commitFileDeletion(){if(!this.isAvailable())return;const p4=this._progress("",LOG_LEVEL_NOTICE);p4.log("Searching for deleted files..");const deletedDocs=(await this.database.allDocs({include_docs:!0})).rows.filter((e3=>{var _a8,_b4,_c3;return("newnote"==(null==(_a8=e3.doc)?void 0:_a8.type)||"plain"==(null==(_b4=e3.doc)?void 0:_b4.type))&&(null==(_c3=e3.doc)?void 0:_c3.deleted)}));if(0==deletedDocs.length){p4.done("No deleted files found.");return}p4.log(`Found ${deletedDocs.length} deleted files.`);const message=`We have following files that are marked as deleted.\n\n- Deleted files: ${deletedDocs.length}\n\nAre you sure to delete these files permanently?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation affects the database permanently. Deleted files will not be recovered after this operation.\n> And, the chunks that are used in the deleted files will be ready for compaction.`,deletingDocs=deletedDocs.map((e3=>({...e3.doc,_deleted:!0})));if(await this.confirm("Delete Files",message,"Delete","Cancel")){const result=await this.database.bulkDocs(deletingDocs);this.clearHash();p4.done(`Deleted ${result.filter((e3=>"ok"in e3)).length} / ${deletedDocs.length} files.`)}else p4.done("Deletion operation is cancelled.")}async commitChunkDeletion(){if(!this.isAvailable())return;const{existing}=await this.allChunks(!0),deletedChunks=[...existing].filter((([key2,e3])=>e3._deleted&&""!==e3.data)).map((([key2,e3])=>e3)),deletedNotVacantChunks=deletedChunks.map((e3=>({...e3,data:"",_deleted:!0}))),humanSize=sizeToHumanReadable2(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((([key2,e3])=>!used.has(e3._id))).map((([key2,e3])=>e3)).map((e3=>({...e3,_deleted:!0}))),humanSize=sizeToHumanReadable2(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((([key2,e3])=>!used.has(e3._id))).map((([key2,e3])=>e3)),deleteChunks=unusedChunks.map((e3=>({...e3,data:"",_deleted:!0}))),humanSize=sizeToHumanReadable2(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()}}};toc=new Set;stubs={};ObsidianLiveSyncSettingTab=class extends import_obsidian.PluginSettingTab{constructor(app2,plugin3){super(app2,plugin3);this.selectedScreen="";this.settingComponents=[];this.controlledElementFunc=[];this.onSavedHandlers=[];this.inWizard=!1;this.isShown=!1;this.manifestVersion="0.24.31";this.updateInformation='## 0.24.31\n\n10th July, 2025\n\n### Fixed\n\n- The description of `Enable Developers\' Debug Tools.` has been refined.\n - Now performance impact is more clearly stated.\n- Automatic conflict checking and resolution has been improved.\n - It now works parallelly for each other file, instead of sequentially. It makes significantly faster on first synchronisation when with local files information.\n- Resolving conflicts dialogue will not be shown for the multiple files at once.\n - It will be shown for each file, one by one.\n\n## 0.24.30\n\n9th July, 2025\n\n### New Feature\n\n- New chunking algorithm `V3: Fine deduplication` has been added, and will be recommended after updates.\n - The Rabin-Karp algorithm is used for efficient chunking.\n - This will be the default in the new installations.\n - It is more robust and faster than the previous one.\n - We can change it in the `Advanced` pane of the settings.\n- New language `ko` (Korean) has been added.\n - Thank you for your contribution, [@ellixspace](https://x.com/ellixspace)!\n - Any contributions are welcome, from any route. Please let me know if I seem to be unaware of this. It is often the case that I am not really aware of it.\n- Chinese (Simplified) translation has been updated.\n - Thank you for your contribution, [@52sanmao](https://github.com/52sanmao)!\n\n### Fixed\n\n- Numeric settings are now never lost the focus during value changing.\n- Doctor now redacts more sensitive information on error reports.\n\n### Improved\n\n- All translations have been rewritten into YAML format, to easier to manage and contribute.\n - We can write them with comments, newlines, and other YAML features.\n- Doctor recommendations are now shown in a user-friendly notation.\n - We can now see the recommended as `V3: Fine deduplication` instead of `v3-rabin-karp`.\n\n### Refactored\n\n- Never-ending `ObsidianLiveSyncSettingTab.ts` has finally been separated into each pane\'s file.\n- Some commented-out code has been removed.\n\n### Acknowledgement\n\n- Jun Murakami, Shun Ishiguro, and Yoshihiro Oyama. 2012. Implementation and Evaluation of a Cache Deduplication Mechanism with Content-Defined Chunking. In _IPSJ SIG Technical Report_, Vol.2012-ARC-202, No.4. Information Processing Society of Japan, 1-7.\n\n## 0.24.29\n\n20th June, 2025\n\n### Fixed\n\n- Synchronisation with buckets now works correctly, regardless of whether a prefix is set or the bucket has been (re-) initialised (#664).\n- An information message is now displayed again, during any automatic synchronisation is enabled (#662).\n\n### Tidied up\n\n- Importing paths have been tidied up.\n\n## 0.24.28\n\n15th June, 2025\n\n### Fixed\n\n- Batch Update is no longer available in LiveSync mode to avoid unexpected behaviour. (#653)\n- Now compatible with Cloudflare R2 again for bucket synchronisation.\n - @edo-bari-ikutsu, thank you for [your contribution](https://github.com/vrtmrz/livesync-commonlib/pull/12)!\n- Prevention of broken behaviour due to database connection failures added (#649).\n\n## 0.24.27\n\n10th June, 2025\n\n### Improved\n\n- We can use prefix for path for the Bucket synchronisation.\n - For example, if you set the `vaultName/` as a prefix for the bucket in the root directory, all data will be transferred to the bucket under the `vaultName/` directory.\n- The "Use Request API to avoid `inevitable` CORS problem" option is now promoted to the normal setting, not a niche patch.\n\n### Fixed\n\n- Now switching replicators applied immediately, without the need to restart Obsidian.\n\n### Tidied up\n\n- Some dependencies have been updated to the latest version.\n\n## 0.24.26\n\n14th May, 2025\n\nThis update introduces an option to circumvent Cross-Origin Resource Sharing\n(CORS) constraints for CouchDB requests, by leveraging Obsidian\'s native request\nAPI. The implementation of such a feature had previously been deferred due to\nsignificant security considerations.\n\nCORS is a vital security mechanism, enabling servers like CouchDB -- which\nfunctions as a sophisticated REST API -- to control access from different\norigins, thereby ensuring secure communication across trust boundaries. I had\nlong hesitated to offer a CORS circumvention method, as it deviates from\nsecurity best practices; My preference was for users to configure CORS correctly\non the server-side.\n\nHowever, this policy has shifted due to specific reports of intractable\nCORS-related configuration issues, particularly within enterprise proxy\nenvironments where proxy servers can unpredictably alter or block\ncommunications. Given that a primary objective of the "Self-hosted LiveSync"\nplugin is to facilitate secure Obsidian usage within stringent corporate\nsettings, addressing these \'unavoidable\' user-reported problems became\nessential. Mostly raison d\'être of this plugin.\n\nConsequently, the option "Use Request API to avoid `inevitable` CORS problem"\nhas been implemented. Users are strongly advised to enable this _only_ when\noperating within a trusted environment. We can enable this option in the `Patch` pane.\n\nHowever, just to whisper, this is tremendously fast.\n\n### New Features\n\n- Automatic display-language changing according to the Obsidian language\n setting.\n - We will be asked on the migration or first startup.\n - **Note: Please revert to the default language if you report any issues.**\n - Not all messages are translated yet. We welcome your contribution!\n- Now we can limit files to be synchronised even in the hidden files.\n- "Use Request API to avoid `inevitable` CORS problem" has been implemented.\n - Less secure, please use it only if you are sure that you are in the trusted\n environment and be able to ignore the CORS. No `Web viewer` or similar tools\n are recommended. (To avoid the origin forged attack). If you are able to\n configure the server setting, always that is recommended.\n- `Show status icon instead of file warnings banner` has been implemented.\n - If enabled, the ⛔ icon will be shown inside the status instead of the file\n warnings banner. No details will be shown.\n\n### Improved\n\n- All regular expressions can be inverted by prefixing `!!` now.\n\n### Fixed\n\n- No longer unexpected files will be gathered during hidden file sync.\n- No longer broken `\\n` and new-line characters during the bucket\n synchronisation.\n- We can purge the remote bucket again if we using MinIO instead of AWS S3 or\n Cloudflare R2.\n- Purging the remote bucket is now more reliable.\n - 100 files are purged at a time.\n- Some wrong messages have been fixed.\n\n### Behaviour changed\n\n- Entering into the deeper directories to gather the hidden files is now limited\n by `/` or `\\/` prefixed ignore filters. (It means that directories are scanned\n deeper than before).\n - However, inside the these directories, the files are still limited by the\n ignore filters.\n\n### Etcetera\n\n- Some code has been tidied up.\n- Trying less warning-suppressing and be more safer-coding.\n- Dependent libraries have been updated to the latest version.\n- Some build processes have been separated to `pre` and `post` processes.\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.plugin.$anyNewReplicator(settingForCheck);if(!(replicator instanceof LiveSyncCouchDBReplicator))return!0;const db=await replicator.connectRemoteCouchDBWithSetting(settingForCheck,this.plugin.$$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.plugin.$allSuspendAllSync();await this.plugin.$allSuspendExtraSync();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 editingSettings(){this._editingSettings||this.reloadAllSettings();return this._editingSettings}set editingSettings(v2){this._editingSettings||this.reloadAllSettings();this._editingSettings=v2}applySetting(keys3){for(const k2 of keys3)if(this.isDirty(k2)&&!(k2 in OnDialogSettingsDefault)){this.plugin.settings[k2]=this.editingSettings[k2];this.initialSettings[k2]=this.plugin.settings[k2]}keys3.forEach((e3=>this.refreshSetting(e3)))}applyAllSettings(){var _a8;const changedKeys=Object.keys(null!=(_a8=this.editingSettings)?_a8:{}).filter((e3=>this.isDirty(e3)));this.applySetting(changedKeys);this.reloadAllSettings()}async saveLocalSetting(key2){var _a8,_b4,_c3,_d2;if("configPassphrase"==key2){localStorage.setItem("ls-setting-passphrase",null!=(_b4=null==(_a8=this.editingSettings)?void 0:_a8[key2])?_b4:"");return await Promise.resolve()}if("deviceAndVaultName"==key2){this.plugin.$$setDeviceAndVaultName(null!=(_d2=null==(_c3=this.editingSettings)?void 0:_c3[key2])?_d2:"");this.plugin.$$saveDeviceAndVaultName();return await Promise.resolve()}}async saveSettings(keys3){let hasChanged=!1;const appliedKeys=[];for(const k2 of keys3)if(this.isDirty(k2)){appliedKeys.push(k2);if(k2 in OnDialogSettingsDefault){await this.saveLocalSetting(k2);this.initialSettings[k2]=this.editingSettings[k2]}else{this.plugin.settings[k2]=this.editingSettings[k2];this.initialSettings[k2]=this.plugin.settings[k2];hasChanged=!0}}hasChanged&&await this.plugin.saveSettings();const handlers2=this.onSavedHandlers.filter((e3=>-1!==appliedKeys.indexOf(e3.key))).map((e3=>e3.handler(this.editingSettings[e3.key])));await Promise.all(handlers2);keys3.forEach((e3=>this.refreshSetting(e3)))}async saveAllDirtySettings(){var _a8;const changedKeys=Object.keys(null!=(_a8=this.editingSettings)?_a8:{}).filter((e3=>this.isDirty(e3)));await this.saveSettings(changedKeys);this.reloadAllSettings()}requestUpdate(){scheduleTask("update-setting",10,(()=>{for(const setting of this.settingComponents)setting._onUpdate();for(const func of this.controlledElementFunc)func()}))}reloadAllLocalSettings(){const ret={...OnDialogSettingsDefault};ret.configPassphrase=localStorage.getItem("ls-setting-passphrase")||"";ret.preset="";ret.deviceAndVaultName=this.plugin.$$getDeviceAndVaultName();return ret}computeAllLocalSettings(){var _a8,_b4;return{syncMode:(null==(_a8=this.editingSettings)?void 0:_a8.liveSync)?"LIVESYNC":(null==(_b4=this.editingSettings)?void 0:_b4.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(key2){const localSetting=this.reloadAllLocalSettings();if(key2 in this.plugin.settings)if(key2 in localSetting){this.initialSettings[key2]=localSetting[key2];this.editingSettings[key2]=localSetting[key2]}else{this.initialSettings[key2]=this.plugin.settings[key2];this.editingSettings[key2]=this.initialSettings[key2]}this.editingSettings={...this.editingSettings,...this.computeAllLocalSettings()};this.requestUpdate()}isDirty(key2){var _a8;return isObjectDifferent(this.editingSettings[key2],null==(_a8=this.initialSettings)?void 0:_a8[key2])}isSomeDirty(keys3){return keys3.some((e3=>this.isDirty(e3)))}isConfiguredAs(key2,value){return!!this.editingSettings&&this.editingSettings[key2]==value}async testConnection(settingOverride={}){const trialSetting={...this.editingSettings,...settingOverride},replicator=await this.plugin.$anyNewReplicator(trialSetting);await replicator.tryConnectRemote(trialSetting);const status=await replicator.getRemoteStatus(trialSetting);status&&status.estimatedSize&&Logger($msg("obsidianLiveSyncSettingTab.logEstimatedSize",{size:sizeToHumanReadable2(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,tag2,o2,callback,func){const element2=el.createEl(tag2,o2,callback);func&&this.handleElement(element2,func);return element2}addEl(el,tag2,o2,callback,func){const elm=this.createEl(el,tag2,o2,callback,func);return Promise.resolve(elm)}addOnSaved(key2,func){this.onSavedHandlers.push({key:key2,handler:func})}resetEditingSettings(){this._editingSettings=void 0;this.initialSettings=void 0}hide(){this.isShown=!1}requestReload(){var _a8;if(this.isShown){const newConf=this.plugin.settings,keys3=Object.keys(newConf);let hasLoaded=!1;for(const k2 of keys3)if(isObjectDifferent(newConf[k2],null==(_a8=this.initialSettings)?void 0:_a8[k2]))if(this.isDirty(k2))this.plugin.confirm.askInPopup(`config-reloaded-${k2}`,$msg("obsidianLiveSyncSettingTab.msgSettingModified",{setting:getConfName(k2)}),(anchor=>{anchor.text=$msg("obsidianLiveSyncSettingTab.optionHere");anchor.addEventListener("click",(()=>{this.refreshSetting(k2);this.display()}))}));else{this.refreshSetting(k2);if(k2 in OnDialogSettingsDefault)continue;hasLoaded=!0}hasLoaded?this.display():this.requestUpdate()}else this.reloadAllSettings(!0)}changeDisplay(screen){for(const k2 in this.screenElements)k2==screen?this.screenElements[k2].forEach((element2=>element2.removeClass("setting-collapsed"))):this.screenElements[k2].forEach((element2=>element2.addClass("setting-collapsed")));this.menuEl&&this.menuEl.querySelectorAll(".sls-setting-label").forEach((element2=>{if(element2.hasClass(`c-${screen}`)){element2.addClass("selected");element2.querySelector("input[type=radio]").checked=!0}else{element2.removeClass("selected");element2.querySelector("input[type=radio]").checked=!1}}));this.selectedScreen=screen}async enableMinimalSetup(){this.editingSettings.liveSync=!1;this.editingSettings.periodicReplication=!1;this.editingSettings.syncOnSave=!1;this.editingSettings.syncOnEditorSave=!1;this.editingSettings.syncOnStart=!1;this.editingSettings.syncOnFileOpen=!1;this.editingSettings.syncAfterMerge=!1;this.plugin.replicator.closeReplication();await this.saveAllDirtySettings();this.containerEl.addClass("isWizard");this.inWizard=!0;this.changeDisplay("20")}addScreenElement(key2,element2){key2 in this.screenElements||(this.screenElements[key2]=[]);this.screenElements[key2].push(element2)}selectPane(event2){const target=event2.target;if("INPUT"==target.tagName){const value=target.getAttribute("value");value&&this.selectedScreen!=value&&this.changeDisplay(value)}}isNeedRebuildLocal(){return this.isSomeDirty(["useIndexedDBAdapter","doNotUseFixedRevisionForChunks","handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isNeedRebuildRemote(){return this.isSomeDirty(["doNotUseFixedRevisionForChunks","handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isAnySyncEnabled(){var _a8,_b4,_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==(_b4=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b4.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.plugin.$$scheduleAppReload();this.closeSetting()}else if(result==OPTION_REBUILD_BOTH){await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG2_HR,"");this.plugin.$$scheduleAppReload();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));(function yieldNextAnimationFrame(){return currentYieldingAnimationFrame||(currentYieldingAnimationFrame=(async()=>{const ret=await function yieldAnimationFrame(){return new Promise((res2=>requestAnimationFrame(res2)))}();currentYieldingAnimationFrame=void 0;return ret})())})().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()}))}async dryRunGC(){await skipIfDuplicated("cleanup",(async()=>{const replicator=this.plugin.$$getReplicator();if(!(replicator instanceof LiveSyncCouchDBReplicator))return;const remoteDBConn=await replicator.connectRemoteCouchDBWithSetting(this.plugin.settings,this.plugin.$$isMobile());if("string"!=typeof remoteDBConn){await purgeUnreferencedChunks(remoteDBConn.db,!0,this.plugin.settings,!1);await purgeUnreferencedChunks(this.plugin.localDatabase.localDatabase,!0);this.plugin.localDatabase.hashCaches.clear()}else Logger(remoteDBConn)}))}async dbGC(){await skipIfDuplicated("cleanup",(async()=>{const replicator=this.plugin.$$getReplicator();if(!(replicator instanceof LiveSyncCouchDBReplicator))return;await this.plugin.$$getReplicator().markRemoteLocked(this.plugin.settings,!0,!0);const remoteDBConnection=await replicator.connectRemoteCouchDBWithSetting(this.plugin.settings,this.plugin.$$isMobile());if("string"!=typeof remoteDBConnection){await purgeUnreferencedChunks(remoteDBConnection.db,!1,this.plugin.settings,!0);await purgeUnreferencedChunks(this.plugin.localDatabase.localDatabase,!1);this.plugin.localDatabase.hashCaches.clear();await balanceChunkPurgedDBs(this.plugin.localDatabase.localDatabase,remoteDBConnection.db);this.plugin.localDatabase.refreshSettings();Logger("The remote database has been cleaned up! Other devices will be cleaned up on the next synchronisation.")}else Logger(remoteDBConnection)}))}getMinioJournalSyncClient(){const id=this.plugin.settings.accessKey,key2=this.plugin.settings.secretKey,bucket=this.plugin.settings.bucket,prefix=this.plugin.settings.bucketPrefix,region=this.plugin.settings.region,endpoint=this.plugin.settings.endpoint,useCustomRequestHandler=this.plugin.settings.useCustomRequestHandler,customHeaders=this.plugin.settings.bucketCustomHeaders;return new JournalSyncMinio(id,key2,endpoint,bucket,prefix,this.plugin.simpleStore,this.plugin,useCustomRequestHandler,region,customHeaders)}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:""}`}};DocumentHistoryModal=class extends import_obsidian.Modal{constructor(app2,plugin3,file,id,revision){super(app2);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.plugin.$$id2path(id));"1"==localStorage.getItem("ols-history-highlightdiff")&&(this.showDiff=!0)}async loadFile(initialRev){var _a8,_b4;this.id||(this.id=await this.plugin.$$path2id(this.file));const db=this.plugin.localDatabase;try{const w2=await db.getRaw(this.id,{revs_info:!0});this.revs_info=null!=(_b4=null==(_a8=w2._revs_info)?void 0:_a8.filter((e3=>"available"==(null==e3?void 0:e3.status))))?_b4:[];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(key2){const v2=this.BlobURLs.get(key2);v2&&URL.revokeObjectURL(v2);this.BlobURLs.delete(key2)}generateBlobURL(key2,data){this.revokeURL(key2);const v2=URL.createObjectURL(new Blob([data],{endings:"transparent",type:"application/octet-stream"}));this.BlobURLs.set(key2,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",{},(label=>{label.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()))}))})));label.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=function stripPrefix(prefixedPath){const[prefix,body]=prefixedPath.split(":",2);return body||prefix}(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)}))}};require("obsidian");ModuleObsidianDocumentHistory=class extends AbstractObsidianModule{$everyOnloadStart(){this.addCommand({id:"livesync-history",name:"Show history",callback:()=>{const file=this.core.$$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)}}};root_111=template('
    Gathering information...
    ');root_24=template('Chunks');root_33=template('
    ');root_44=template('
    ');root_64=template(' ');root_83=template(' ');root_53=template(' ');root_93=template('
    ');root_102=template('
    ');root6=template('

    Vault history

    DatePathRevStat
    ');$$css7={hash:"svelte-1vjy5r1",code:".svelte-1vjy5r1 {box-sizing:border-box;}.globalhistory.svelte-1vjy5r1 {margin-bottom:2em;}table.svelte-1vjy5r1 {width:100%;}.more.svelte-1vjy5r1 > div:where(.svelte-1vjy5r1) {display:flex;}.more.svelte-1vjy5r1 > div:where(.svelte-1vjy5r1) > button:where(.svelte-1vjy5r1) {flex-grow:1;}th.svelte-1vjy5r1 {position:sticky;top:0;backdrop-filter:blur(10px);}td.mtime.svelte-1vjy5r1 {white-space:break-spaces;}td.path.svelte-1vjy5r1 {word-break:break-word;}.row.svelte-1vjy5r1 {display:flex;flex-direction:row;flex-wrap:wrap;}.row.svelte-1vjy5r1 > label:where(.svelte-1vjy5r1) {display:flex;align-items:center;min-width:5em;}.row.svelte-1vjy5r1 > input:where(.svelte-1vjy5r1) {flex-grow:1;}.filenames.svelte-1vjy5r1 {display:flex;flex-direction:column;}.filenames.svelte-1vjy5r1 > .path:where(.svelte-1vjy5r1) {font-size:70%;}.rev.svelte-1vjy5r1 {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.core.$$showView("global-history")}};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.core.$$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("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.`,-1);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.core.$$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.core.$$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)}}};ModuleInitializerFile=class extends AbstractModule{async $$performFullScan(showingNotice){this._log("Opening the key-value database",LOG_LEVEL_VERBOSE);const isInitialized=await this.core.kvDB.get("initialized")||!1;if(!this.settings.isConfigured){showingNotice&&this._log("LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.",LOG_LEVEL_NOTICE,"syncAll");return}showingNotice&&this._log("Initializing",LOG_LEVEL_NOTICE,"syncAll");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.core.$$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.core.$$isTargetFile(path2,!0)){if(!(entry=doc,"children"in entry)){this._log(`Invalid entry: ${path2}`,LOG_LEVEL_INFO);continue}_DBEntries.push(doc)}}var entry;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(((key2,msg)=>{processStatus[key2]=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 async function*withConcurrency(iterable,callback,concurrency){const processes=new Set,mapTaskToPromise=new Map;let serial=0;const enqueue=item=>{const idx2=serial++,promise=(async()=>[idx2,await callback(item)])();processes.add(promise);mapTaskToPromise.set(idx2,promise)},consume=async()=>{const r4=await Promise.race(processes),item=mapTaskToPromise.get(r4[0]);processes.delete(item);mapTaskToPromise.delete(r4[0]);return r4[1]};for await(const t3 of iterable){for(;processes.size>=concurrency;)yield await consume();enqueue(t3)}for(;processes.size>0;)yield await consume()}(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.core.$$isFileSizeExceeded(file.stat.size))this._log(`UPDATE DATABASE: ${e3} has been skipped due to file size exceeding the limit`,logLevel);else{const path2=file.path;await this.core.fileHandler.storeFileToDB(file);eventHub.emitEvent("event-file-changed",{file:path2,automated:!0})}})));initProcess.push(runAll("UPDATE STORAGE",filesExistOnlyInDatabase,(async e3=>{var _a8,_b4,_c3;const w2=databaseFileNameMap[databaseFileNameCI2CS[e3]],path2=null!=(_a8=getPath2(w2))?_a8:e3;if(!w2||w2.deleted||w2._deleted)w2?this._log(`Deletion history skipped: ${path2}`,LOG_LEVEL_VERBOSE):this._log(`entry not found: ${path2}`);else if(this.core.$$isFileSizeExceeded(w2.size))this._log(`UPDATE STORAGE: ${path2} has been skipped due to file size exceeding the limit`,logLevel);else{if(null!=(_c3=null==(_b4=w2._conflicts)?void 0:_b4.length)&&_c3){this._log(`UPDATE STORAGE: ${path2} has conflicts. skipped (x)`,LOG_LEVEL_INFO);return}await this.core.fileHandler.dbToStorage(path2,null,!0);eventHub.emitEvent("event-file-changed",{file:e3,automated:!0});this._log(`Check or pull from db:${path2} OK`)}})));const fileMap=filesExistBoth.map((path2=>({file:storageFileNameMap[storageFileNameCI2CS[path2]],doc:databaseFileNameMap[databaseFileNameCI2CS[path2]]})));initProcess.push(runAll("SYNC DATABASE AND STORAGE",fileMap,(async e3=>{var _a8,_b4;const{file,doc}=e3;null!=(_b4=null==(_a8=doc._conflicts)?void 0:_a8.length)&&_b4?this._log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`,LOG_LEVEL_INFO):this.core.$$isFileSizeExceeded(file.stat.size)||this.core.$$isFileSizeExceeded(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")}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.core.$$isFileSizeExceeded(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.core.$$isFileSizeExceeded(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,-1);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){this.core.$$resetIsReady();if(!reopenDatabase||await this.core.$$openDatabase()){this.localDatabase.isReady&&await this.core.$$performFullScan(showingNotice);if(!await this.core.$everyOnDatabaseInitialized(showingNotice)){this._log("Initializing database has been failed on some module",LOG_LEVEL_NOTICE);return!1}this.core.$$markIsReady();await this.core.$everyCommitPendingFileEvent();return!0}this.core.$$resetIsReady();return!1}};ModuleKeyValueDB=class extends AbstractModule{tryCloseKvDB(){var _a8;try{null==(_a8=this.core.kvDB)||_a8.close();return!0}catch(e3){this._log("Failed to close KeyValueDB",LOG_LEVEL_VERBOSE);this._log(e3);return!1}}async openKeyValueDB(){await delay(10);try{this.tryCloseKvDB();await delay(10);await yieldMicrotask();this.core.kvDB=await OpenKeyValueDatabase(this.core.$$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}$allOnDBUnload(db){this.core.kvDB&&this.core.kvDB.close()}$allOnDBClose(db){this.core.kvDB&&this.core.kvDB.close()}async $everyOnloadAfterLoadSettings(){if(!await this.openKeyValueDB())return!1;this.core.simpleStore=this.core.$$getSimpleStore("os");return Promise.resolve(!0)}$$getSimpleStore(kind){const prefix=`${kind}-`;return{get:async key2=>await this.core.kvDB.get(`${prefix}${key2}`),set:async(key2,value)=>{await this.core.kvDB.set(`${prefix}${key2}`,value)},delete:async key2=>{await this.core.kvDB.del(`${prefix}${key2}`)},keys:async(from,to,count)=>{const ret=this.core.kvDB.keys(IDBKeyRange.bound(`${prefix}${from||""}`,`${prefix}${to||""}`),count);return(await ret).map((e3=>e3.toString())).filter((e3=>e3.startsWith(prefix))).map((e3=>e3.substring(prefix.length)))}}}$everyOnInitializeDatabase(db){return this.openKeyValueDB()}async $everyOnResetDatabase(db){try{const kvDBKey="queued-files";await this.core.kvDB.del(kvDBKey);await this.core.kvDB.destroy();await yieldMicrotask();this.core.kvDB=await OpenKeyValueDatabase(this.core.$$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}};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+"-indexeddb",optionPass)}return new index_es_default(name,optionPass)}};ModuleReplicator=class extends AbstractModule{constructor(){super(...arguments);this._saveQueuedFiles=throttle((()=>{const saveData=this.replicationResultProcessor._queue.filter((e3=>null!=e3)).map((e3=>{var _a8;return null!=(_a8=null==e3?void 0:e3._id)?_a8:""}));fireAndForget((()=>this.core.kvDB.set("queued-files",saveData)))}),100);this.replicationResultProcessor=new QueueProcessor((async docs=>{if(this.settings.suspendParseReplicationResult)return;const change=docs[0];if(change)if(function isChunk(str){return str.startsWith("h:")}(change._id))globalSlipBoard2.submit("read-chunk",change._id,change);else if(!await this.core.$anyModuleParsedReplicationResultItem(change))if("versioninfo"!=change.type){if(change._id!=SYNCINFO_ID&&!change._id.startsWith("_design")&&isAnyNote(change)){const docPath=getPath2(change);if(!await this.core.$$isTargetFile(docPath)){Logger(`Skipped: ${docPath}`,LOG_LEVEL_VERBOSE);return}this.databaseQueuedProcessor._isSuspended&&Logger(`Processing scheduled: ${docPath}`,LOG_LEVEL_INFO);const size=change.size;if(this.core.$$isFileSizeExceeded(size)){Logger(`Processing ${docPath} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);return}this.databaseQueuedProcessor.enqueue(change)}}else if(change.version>10){this.core.replicator.closeReplication();Logger("Remote database updated to incompatible version. update your Self-hosted LiveSync plugin.",LOG_LEVEL_NOTICE)}}),{batchSize:1,suspended:!0,concurrentLimit:100,delay:0,totalRemainingReactiveSource:this.core.replicationResultCount}).replaceEnqueueProcessor(((queue2,newItem)=>[...queue2.filter((e3=>e3._id!=newItem._id)),newItem])).startPipeline().onUpdateProgress((()=>{this.saveQueuedFiles()}));this.databaseQueuedProcessor=new QueueProcessor((async docs=>{var _a8;const dbDoc=docs[0],path2=getPath2(dbDoc),doc=await this.localDatabase.getDBEntryFromMeta({...dbDoc},!1,!0);doc?await this.core.$anyProcessOptionalSyncFiles(dbDoc)||(isValidPath(getPath2(doc))?this.storageApplyingProcessor.enqueue(doc):Logger(`Skipped: ${path2} (${doc._id.substring(0,8)})`,LOG_LEVEL_VERBOSE)):Logger(`Something went wrong while gathering content of ${path2} (${dbDoc._id.substring(0,8)}, ${null==(_a8=dbDoc._rev)?void 0:_a8.substring(0,10)}) `,LOG_LEVEL_NOTICE)}),{suspended:!0,batchSize:1,concurrentLimit:10,yieldThreshold:1,delay:0,totalRemainingReactiveSource:this.core.databaseQueueCount}).replaceEnqueueProcessor(((queue2,newItem)=>[...queue2.filter((e3=>e3._id!=newItem._id)),newItem])).startPipeline();this.storageApplyingProcessor=new QueueProcessor((async docs=>{const entry=docs[0];await this.core.$anyProcessReplicatedDoc(entry)}),{suspended:!0,batchSize:1,concurrentLimit:6,yieldThreshold:1,delay:0,totalRemainingReactiveSource:this.core.storageApplyingCount}).replaceEnqueueProcessor(((queue2,newItem)=>[...queue2.filter((e3=>e3._id!=newItem._id)),newItem])).startPipeline()}$everyOnloadAfterLoadSettings(){eventHub.onEvent("file-saved",(()=>{this.settings.syncOnSave&&!this.core.$$isSuspended()&&scheduleTask("perform-replicate-after-save",250,(()=>this.core.$$replicateByEvent()))}));eventHub.onEvent("setting-saved",(setting=>{this._replicatorType!==setting.remoteType&&this.setReplicator()}));return Promise.resolve(!0)}async setReplicator(){const replicator=await this.core.$anyNewReplicator();if(!replicator){this._log($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();return!0}$$getReplicator(){return this.core.replicator}$everyOnInitializeDatabase(db){return this.setReplicator()}$everyOnResetDatabase(db){return this.setReplicator()}async $everyBeforeReplicate(showMessage){await this.loadQueuedFiles();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()=>{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.core.$$getReplicator();if(!(replicator instanceof LiveSyncCouchDBReplicator))return;const remoteDB=await replicator.connectRemoteCouchDBWithSetting(this.settings,this.core.$$isMobile(),!0);if("string"==typeof remoteDB){Logger(remoteDB,LOG_LEVEL_NOTICE);return!1}await purgeUnreferencedChunks(this.localDatabase.localDatabase,!1);this.localDatabase.hashCaches.clear();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.hashCaches.clear();await this.core.$$getReplicator().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 $$_replicate(showMessage=!1){var _a8;if(!this.core.$$isReady())return;if(isLockAcquired("cleanup")){Logger($msg("Replicator.Message.Cleaned"),LOG_LEVEL_NOTICE);return}if(""!=this.settings.versionUpFlash){Logger($msg("Replicator.Message.VersionUpFlash"),LOG_LEVEL_NOTICE);return}if(!await this.core.$everyCommitPendingFileEvent()){Logger($msg("Replicator.Message.Pending"),LOG_LEVEL_NOTICE);return!1}if(!await this.core.$everyBeforeReplicate(showMessage)){Logger($msg("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_NOTICE);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.core.$$askResolvingMismatchedTweaks(this.core.replicator.preferredTweakValue);else if(null==(_a8=this.core.replicator)?void 0:_a8.remoteLockedAndDeviceNotAccepted)if(this.core.replicator.remoteCleaned&&this.settings.useIndexedDBAdapter)await this.cleaned(showMessage);else{const message=$msg("Replicator.Dialogue.Locked.Message"),CHOICE_FETCH=$msg("Replicator.Dialogue.Locked.Action.Fetch"),CHOICE_DISMISS=$msg("Replicator.Dialogue.Locked.Action.Dismiss"),CHOICE_UNLOCK=$msg("Replicator.Dialogue.Locked.Action.Unlock"),ret2=await this.core.confirm.askSelectStringDialogue(message,[CHOICE_FETCH,CHOICE_UNLOCK,CHOICE_DISMISS],{title:$msg("Replicator.Dialogue.Locked.Title"),defaultAction:CHOICE_DISMISS,timeout:60});if(ret2==CHOICE_FETCH){this._log($msg("Replicator.Dialogue.Locked.Message.Fetch"),LOG_LEVEL_NOTICE);await this.core.rebuilder.scheduleFetch();this.core.$$scheduleAppReload();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?function rateLimitedSharedExecution(key2,interval,proc){key2 in waitingTasks||(waitingTasks[key2]={task:void 0,previous:0,leastNext:0});if(waitingTasks[key2].task){waitingTasks[key2].leastNext=Date.now()+interval;return waitingTasks[key2].task.promise}const previous=waitingTasks[key2].previous,delay2=0==previous?0:Math.max(interval-(Date.now()-previous),0),task=promiseWithResolver();task.promise.finally((()=>{if(waitingTasks[key2].task===task){waitingTasks[key2].task=void 0;waitingTasks[key2].previous=Math.max(Date.now(),waitingTasks[key2].leastNext)}}));waitingTasks[key2]={task,previous:Date.now(),leastNext:Date.now()+interval};scheduleTask("thin-out-"+key2,delay2,(async()=>{try{task.resolve(await proc())}catch(ex){task.reject(ex)}}));return task.promise}("replicationOnEvent",least,(async()=>await this.$$replicate())):await shareRunningResult("replication",(()=>this.core.$$replicate()))}$$parseReplicationResult(docs){this.settings.suspendParseReplicationResult&&!this.replicationResultProcessor.isSuspended&&this.replicationResultProcessor.suspend();this.replicationResultProcessor.enqueueAll(docs);!this.settings.suspendParseReplicationResult&&this.replicationResultProcessor.isSuspended&&this.replicationResultProcessor.resume()}saveQueuedFiles(){this._saveQueuedFiles()}async loadQueuedFiles(){var _a8;if(!this.settings.suspendParseReplicationResult&&this.settings.isConfigured){try{const kvDBKey="queued-files",chunkedIds=arrayToChunkedArray([...new Set(null!=(_a8=await this.core.kvDB.get(kvDBKey))?_a8:[])],100);this.replicationResultProcessor.isSuspended&&this.replicationResultProcessor.resume();for await(const idsBatch of chunkedIds){const ret=await this.localDatabase.allDocsRaw({keys:idsBatch,include_docs:!0,limit:100}),docs=ret.rows.filter((e3=>e3.doc)).map((e3=>e3.doc)),errors=ret.rows.filter((e3=>!e3.doc&&!e3.value.deleted));if(errors.length>0){Logger("Some queued processes were not resurrected");Logger(JSON.stringify(errors),LOG_LEVEL_VERBOSE)}this.replicationResultProcessor.enqueueAll(docs)}}catch(e3){Logger("Failed to load queued files.",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE)}finally{this.replicationResultProcessor.isSuspended&&this.replicationResultProcessor.resume()}try{await this.replicationResultProcessor.waitForAllProcessed()}catch(e3){Logger("Failed to wait for all queued files to be processed.",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE)}}}$everyBeforeSuspendProcess(){this.core.replicator.closeReplication();return Promise.resolve(!0)}async $$replicateAllToServer(showingNotice=!1,sendChunksInBulkDisabled=!1){if(!this.core.$$isReady())return!1;if(!await this.core.$everyBeforeReplicate(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.core.$anyAfterConnectCheckFailed();return"CHECKAGAIN"==checkResult?await this.core.$$replicateAllToServer(showingNotice):!checkResult}async $$replicateAllFromServer(showingNotice=!1){if(!this.core.$$isReady())return!1;if(await this.core.replicator.replicateAllFromServer(this.settings,showingNotice))return!0;const checkResult=await this.core.$anyAfterConnectCheckFailed();return"CHECKAGAIN"==checkResult?await this.core.$$replicateAllFromServer(showingNotice):!checkResult}};ModuleReplicatorCouchDB=class extends AbstractModule{$anyNewReplicator(settingOverride={}){const settings={...this.settings,...settingOverride};if(settings.remoteType!=REMOTE_MINIO&&settings.remoteType!=REMOTE_P2P)return Promise.resolve(new LiveSyncCouchDBReplicator(this.core))}$everyAfterResumeProcess(){if(this.settings.remoteType!=REMOTE_MINIO&&this.settings.remoteType!=REMOTE_P2P){this.settings.liveSync&&fireAndForget((()=>this.core.replicator.openReplication(this.settings,!0,!1,!1)));!this.settings.liveSync&&this.settings.syncOnStart&&fireAndForget((()=>this.core.replicator.openReplication(this.settings,!1,!1,!1)))}return Promise.resolve(!0)}};ModuleReplicatorMinIO=class extends AbstractModule{$anyNewReplicator(settingOverride={}){if({...this.settings,...settingOverride}.remoteType==REMOTE_MINIO)return Promise.resolve(new LiveSyncJournalReplicator(this.core))}};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(){eventHub.onEvent("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);if(stripPrefix2&&isInternalMetadata(tempId)){const out=function stripInternalMetadataPrefix(id){return id.substring(ICHeaderLength)}(tempId);return out}return tempId}async $$path2id(filename,prefix){const destPath=addPrefix(filename,null!=prefix?prefix:"");return await async function path2id(filename,obfuscatePassphrase,caseInsensitive){const temp=filename.split(":"),path2=temp.pop(),normalizedPath=normalizePath(path2);temp.push(normalizedPath);const fixedPath=temp.join(":"),out=await 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}`)}(fixedPath,obfuscatePassphrase,caseInsensitive);return out}(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 _a9;if(keepFileCheckList&&prev)return prev;if(!keepFileCheckList&&prev&&!this.fileListPossiblyChanged)return prev;const fileList=null!=(_a9=ctx.get("fileList"))?_a9:[],vaultFiles=this.core.storageAccess.getFileNames().sort();if(prev&&vaultFiles.length==fileList.length){const fl3=new Set([...fileList,...vaultFiles]);if(fileList.length==fl3.size&&vaultFiles.length==fl3.size)return prev}ctx.set("fileList",vaultFiles);const fileCount2={};for(const file2 of vaultFiles){const lc3=file2.toLowerCase();fileCount2[lc3]?fileCount2[lc3]++:fileCount2[lc3]=1}return fileCount2})),filepath=getStoragePathFromUXFileInfo(file),lc2=filepath.toLowerCase();if(this.core.$$shouldCheckCaseInsensitive()&&lc2 in fileCount&&fileCount[lc2]>1)return!1;const fileNameLC=null==(_a8=getStoragePathFromUXFileInfo(file).split("/").pop())?void 0:_a8.toLowerCase();if(this.settings.useIgnoreFiles){this.ignoreFiles.some((e3=>e3.toLowerCase()==fileNameLC))&&await this.readIgnoreFile(filepath);if(await this.core.$$isIgnoredByIgnoreFiles(file))return!1}return!!(null==(_b4=this.localDatabase)?void 0:_b4.isTargetFile(filepath))}async readIgnoreFile(path2){try{const gitignore=(await this.core.storageAccess.readFileText(path2)).split(/\r?\n/g);this.ignoreFileCache.set(path2,gitignore);return gitignore}catch(ex){this._log(`Failed to read ignore file ${path2}`);this._log(ex,LOG_LEVEL_VERBOSE);this.ignoreFileCache.set(path2,!1);return!1}}async getIgnoreFile(path2){var _a8;return this.ignoreFileCache.has(path2)?null!=(_a8=this.ignoreFileCache.get(path2))&&_a8:await this.readIgnoreFile(path2)}async $$isIgnoredByIgnoreFiles(file){if(!this.settings.useIgnoreFiles)return!1;const filepath=getStoragePathFromUXFileInfo(file);this.ignoreFileCache.has(filepath)&&await this.readIgnoreFile(filepath);return!await async function isAcceptedAll(path2,ignoreFiles,getList){const intermediatePaths=unique(path2.substring(0,path2.lastIndexOf("/")).split("/").reduce(((p4,c3)=>[...p4,p4[p4.length-1]+"/"+c3]),[""]).map((e3=>e3.substring(1)))).reverse();for(const intermediatePath of intermediatePaths)for(const ignoreFile of ignoreFiles){const ignoreFilePath=intermediatePath+"/"+ignoreFile,list=await getList(ignoreFilePath);if(!1===list)continue;const result=isAccepted(path2.substring(intermediatePath.length?intermediatePath.length+1:0),list);if(void 0!==result)return result}return!0}(filepath,this.ignoreFiles,(filename=>this.getIgnoreFile(filename)))}};ModulePeriodicProcess=class extends AbstractModule{constructor(){super(...arguments);this.periodicSyncProcessor=new PeriodicProcessor(this.core,(async()=>await this.core.$$replicate()))}_disablePeriodic(){var _a8;null==(_a8=this.periodicSyncProcessor)||_a8.disable();return Promise.resolve(!0)}_resumePeriodic(){this.periodicSyncProcessor.enable(this.settings.periodicReplication?1e3*this.settings.periodicReplicationInterval:0);return Promise.resolve(!0)}$allOnUnload(){return this._disablePeriodic()}$everyBeforeRealizeSetting(){return this._disablePeriodic()}$everyBeforeSuspendProcess(){return this._disablePeriodic()}$everyAfterResumeProcess(){return this._resumePeriodic()}$everyAfterRealizeSetting(){return this._resumePeriodic()}};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)}};ModuleLocalDatabaseObsidian=class extends AbstractModule{$everyOnloadStart(){return Promise.resolve(!0)}async $$openDatabase(){null!=this.localDatabase&&await this.localDatabase.close();const vaultName=this.core.$$getVaultName();this._log($msg("moduleLocalDatabase.logWaitingForReady"));this.core.localDatabase=new LiveSyncLocalDB(vaultName,this.core);(function initializeStores(vaultName){sameChangePairs=new PersistentMap(`ls-persist-same-changes-${vaultName}`)})(vaultName);return await this.localDatabase.initializeDatabase()}$$isDatabaseReady(){return null!=this.localDatabase&&this.localDatabase.isReady}};ModuleConflictChecker=class extends AbstractModule{constructor(){super(...arguments);this.conflictResolveQueue=new QueueProcessor((async filenames=>{const filename=filenames[0];return await this.core.$$resolveConflict(filename)}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:0,keepResultUntilDownstreamConnected:!1}).replaceEnqueueProcessor(((queue2,newEntity)=>{(function sendValue(id,result){globalSlipBoard.submit("x-compatibility-value",id,result)})("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.core.$$getActiveFilePath();if(af2&&af2!=path2){this._log(`${file} is conflicted, merging process has been postponed.`,LOG_LEVEL_NOTICE);return}}await this.core.$$queueConflictCheck(path2)}async $$queueConflictCheck(file){const optionalConflictResult=await this.core.$anyGetOptionalConflictCheckMethod(file);1!=optionalConflictResult&&("newer"===optionalConflictResult?await this.core.$anyResolveConflictByNewest(file):this.conflictCheckQueue.enqueue(file))}$$waitForAllConflictProcessed(){return this.conflictResolveQueue.waitForAllProcessed()}};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.core.$$askResolvingMismatchedTweaks(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 key2=v2[0],valueMine=escapeMarkdownValue(mine[key2]),valuePreferred=escapeMarkdownValue(preferred[key2]);if(valueMine!=valuePreferred){-1!==IncompatibleChanges.indexOf(key2)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key2)continue;const isFromConditionMet="from"in pattern&&pattern.from===mine[key2],isToConditionMet="to"in pattern&&pattern.to===preferred[key2];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key2)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:confName(key2),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.core.$$checkAndAskResolvingMismatchedTweaks(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.core.$$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 $$checkAndAskUseRemoteConfiguration(trialSetting){const replicator=await this.core.$anyNewReplicator(trialSetting);if(await replicator.tryConnectRemote(trialSetting)){const preferred=await replicator.getRemotePreferredTweakValues(trialSetting);if(preferred)return await this.$$askUseRemoteConfiguration(trialSetting,preferred);this._log("Failed to get the preferred tweak values from the remote server.",LOG_LEVEL_NOTICE);return{result:!1,requireFetch:!1}}this._log("Failed to connect to the remote server.",LOG_LEVEL_NOTICE);return{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 key2=v2[0],remoteValueForDisplay=escapeMarkdownValue(preferred[key2]),currentValueForDisplay=`${escapeMarkdownValue(null==trialSetting?void 0:trialSetting[key2])}`;if((null==trialSetting?void 0:trialSetting[key2])!==preferred[key2]){-1!==IncompatibleChanges.indexOf(key2)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key2)continue;const isFromConditionMet="from"in pattern&&pattern.from===(null==trialSetting?void 0:trialSetting[key2]),isToConditionMet="to"in pattern&&pattern.to===preferred[key2];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key2)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:confName(key2),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}}};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(key2,proc){if(!await this._test(key2,proc))throw new Error(`${key2}`);return!0}tryReplicate(){if(!this.settings.liveSync)return shareRunningResult("replicate-test",(async()=>{await this.core.$$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.core.$anyResolveConflictByNewest("_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.core.$anyResolveConflictByNewest("_STEP_ACK.md");await this.core.storageAccess.writeFileAuto("_STEP_ACK.md",stepContent);await this.tryReplicate();return!0}async performStep({step,title,isGameChanger,proc,check}){if(isGameChanger){await this._proceed(step,title);try{await proc()}catch(e3){this._log(`Error: ${e3}`);return!1}return await this._orDie(`Step ${step} - ${title}`,(async()=>await this.waitWithReplicating(check)))}return await this._join(step,title)}async nonLiveTestRunner(isLeader,testMain){const storage=this.core.storageAccess;let testFileName;this.addTestResult("-------Starting ... ",!0,`Test as ${isLeader?"Leader":"Receiver"} command file IT.md`);isLeader&&await this._proceed(0,"start");await this.tryReplicate();await this.performStep({step:0,title:"Make sure that command File Not Exists",isGameChanger:isLeader,proc:async()=>await storage.removeHidden("IT.md"),check:async()=>!await storage.isExistsIncludeHidden("IT.md")});await this.performStep({step:1,title:"Make sure that command File Not Exists On Receiver",isGameChanger:!isLeader,proc:async()=>await storage.removeHidden("ITx.md"),check:async()=>!await storage.isExistsIncludeHidden("ITx.md")});await this.performStep({step:2,title:"Decide the test file name",isGameChanger:isLeader,proc:async()=>{testFileName=Date.now()+"-"+Math.ceil(1e3*Math.random())+".md";await storage.writeFileAuto("IT.md",testFileName)},check:()=>Promise.resolve(!0)});await this.performStep({step:3,title:"Wait for the command file to be arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await storage.isExistsIncludeHidden("IT.md")});await this.performStep({step:4,title:"Send the response file",isGameChanger:!isLeader,proc:async()=>{await storage.writeHiddenFileAuto("ITx.md","!")},check:()=>Promise.resolve(!0)});await this.performStep({step:5,title:"Wait for the response file to be arrived",isGameChanger:isLeader,proc:async()=>{},check:async()=>await storage.isExistsIncludeHidden("ITx.md")});await this.performStep({step:6,title:"Proceed to begin the test",isGameChanger:isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await this.performStep({step:6,title:"Begin the test",isGameChanger:!0,proc:async()=>{},check:()=>Promise.resolve(!0)});try{this.addTestResult("** Main------",!0,"");if(isLeader)return await testMain(testFileName,!0);{const testFileName2=await this.readStorageContent("IT.md");this.addTestResult("testFileName",!0,`Request client to use :${testFileName2}`);return await testMain(testFileName2,!1)}}finally{this.addTestResult("Teardown",!0,`Deleting ${testFileName}`);await storage.removeHidden(testFileName)}return!0}async testBasic(filename,isLeader){const storage=this.core.storageAccess,database=this.core.databaseFileAccess;await this.addTestResult("---**Starting Basic Test**---",!0,`Test as ${isLeader?"Leader":"Receiver"} command file ${filename}`);await this.performStep({step:0,title:"Make sure that file is not exist",isGameChanger:!isLeader,proc:async()=>{},check:async()=>!await storage.isExists(filename)});await this.performStep({step:1,title:"Write a file",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World"),check:async()=>await storage.isExists(filename)});await this.performStep({step:2,title:"Make sure the file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await storage.isExists(filename)});await this.performStep({step:3,title:"Update to Hello World 2",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World 2"),check:async()=>await this.storageContentIsEqual(filename,"Hello World 2")});await this.performStep({step:4,title:"Make sure the modified file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Hello World 2")});await this.performStep({step:5,title:"Update to Hello World 3",isGameChanger:!isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World 3"),check:async()=>await this.storageContentIsEqual(filename,"Hello World 3")});await this.performStep({step:6,title:"Make sure the modified file is arrived",isGameChanger:isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Hello World 3")});await this.performStep({step:7,title:"Update to Multiline",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D"),check:async()=>await this.storageContentIsEqual(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D")});await this.performStep({step:8,title:"Make sure the modified file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D")});if(!this.settings.liveSync){const multiLineContentL="Line1:A\nLine2:B\nLine3:C!\nLine4:D",multiLineContentC="Line1:A\nLine2:bbbbb\nLine3:C\nLine4:D";await this.performStep({step:9,title:"Progress to be conflicted",isGameChanger:isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await storage.writeFileAuto(filename,isLeader?multiLineContentL:multiLineContentC);await this.performStep({step:10,title:"Update As Conflicted",isGameChanger:!isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await this.performStep({step:10,title:"Make sure Automatically resolved",isGameChanger:isLeader,proc:async()=>{},check:async()=>0===(await database.getConflictedRevs(filename)).length});await this.performStep({step:11,title:"Make sure Automatically resolved",isGameChanger:!isLeader,proc:async()=>{},check:async()=>0===(await database.getConflictedRevs(filename)).length});const sensiblyMergedContent="Line1:A\nLine2:bbbbb\nLine3:C!\nLine4:D";await this.performStep({step:12,title:"Make sure Sensibly Merged on Leader",isGameChanger:isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,sensiblyMergedContent)});await this.performStep({step:13,title:"Make sure Sensibly Merged on Receiver",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,sensiblyMergedContent)})}await this.performStep({step:14,title:"Delete File",isGameChanger:isLeader,proc:async()=>{await storage.removeHidden(filename)},check:async()=>!await storage.isExists(filename)});await this.performStep({step:15,title:"Make sure File is deleted",isGameChanger:!isLeader,proc:async()=>{},check:async()=>!await storage.isExists(filename)});this._log("The Basic Test has been completed",LOG_LEVEL_NOTICE);return!0}async testBasicEvent(isLeader){this.settings.liveSync=!1;await this.saveSettings();await this._test("basic",(async()=>await this.nonLiveTestRunner(isLeader,((t3,l2)=>this.testBasic(t3,l2)))))}async testBasicLive(isLeader){this.settings.liveSync=!0;await this.saveSettings();await this._test("basic",(async()=>await this.nonLiveTestRunner(isLeader,((t3,l2)=>this.testBasic(t3,l2)))))}async $everyModuleTestMultiDevice(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);const isLeader=-1===this.core.$$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)}};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 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.core.$allAskUsingOptionalSyncFeature(opt)}async rebuildRemote(){await this.core.$allSuspendExtraSync();this.core.settings.isConfigured=!0;await this.core.$$realizeSettingSyncMode();await this.core.$$markRemoteLocked();await this.core.$$tryResetRemoteDatabase();await this.core.$$markRemoteLocked();await delay(500);await this.askUsingOptionalFeature({enableOverwrite:!0});await delay(1e3);await this.core.$$replicateAllToServer(!0);await delay(1e3);await this.core.$$replicateAllToServer(!0,!0)}$rebuildRemote(){return this.rebuildRemote()}async rebuildEverything(){await this.core.$allSuspendExtraSync();await this.askUseNewAdapter();this.core.settings.isConfigured=!0;await this.core.$$realizeSettingSyncMode();await this.resetLocalDatabase();await delay(1e3);await this.core.$$initializeDatabase(!0);await this.core.$$markRemoteLocked();await this.core.$$tryResetRemoteDatabase();await this.core.$$markRemoteLocked();await delay(500);await this.askUsingOptionalFeature({enableOverwrite:!1});await delay(1e3);await this.core.$$replicateAllToServer(!0);await delay(1e3);await this.core.$$replicateAllToServer(!0,!0)}$rebuildEverything(){return this.rebuildEverything()}$fetchLocal(makeLocalChunkBeforeSync){return this.fetchLocal(makeLocalChunkBeforeSync)}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.core.$$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.core.$$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();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.core.$allSuspendExtraSync()}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.core.$$performFullScan(!0);await this.core.$everyBeforeReplicate(!1);await this.core.saveSettings()}}async askUseNewAdapter(){if(!this.core.settings.useIndexedDBAdapter){const message="Now this core has been configured to use the old database adapter for keeping compatibility. Do you want to deactivate it?",CHOICE_YES="Yes, disable and use latest",choices=[CHOICE_YES,"No, keep compatibility"];await this.core.confirm.confirmWithMessage("Database adapter",message,choices,CHOICE_YES,10)==CHOICE_YES&&(this.core.settings.useIndexedDBAdapter=!0)}}async fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync){await this.core.$allSuspendExtraSync();await this.askUseNewAdapter();this.core.settings.isConfigured=!0;await this.suspendReflectingDatabase();await this.core.$$realizeSettingSyncMode();await this.resetLocalDatabase();await delay(1e3);await this.core.$$openDatabase();this.core.$$markIsReady();makeLocalChunkBeforeSync?await this.core.fileHandler.createAllChunks(!0):preventMakeLocalFilesBeforeSync||await this.core.$$initializeDatabase(!0);await this.core.$$markRemoteResolved();await delay(500);await this.core.$$replicateAllFromServer(!0);await delay(1e3);await this.core.$$replicateAllFromServer(!0);await this.resumeReflectingDatabase();await this.askUsingOptionalFeature({enableFetch:!0})}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.core.$$resetLocalDatabase();const suffix=await this.core.$anyGetAppId()||"";this.core.settings.additionalSuffixOfDatabaseName=suffix;await this.core.$$resetLocalDatabase();eventHub.emitEvent("database-rebuilt")}async fetchRemoteChunks(){if(!this.core.settings.doNotSuspendOnFetching&&this.core.settings.readChunksOnline&&this.core.settings.remoteType==REMOTE_COUCHDB){this._log("Fetching chunks",LOG_LEVEL_NOTICE);const replicator=this.core.$$getReplicator(),remoteDB=await replicator.connectRemoteCouchDBWithSetting(this.settings,this.core.$$isMobile(),!0);"string"==typeof remoteDB?this._log(remoteDB,LOG_LEVEL_NOTICE):await async function fetchAllUsedChunks(local,remote){try{const chunksOnRemote=await collectChunks(remote,"INUSE");await transferChunks("r2l","remote -> local",remote,local,chunksOnRemote);Logger("remote -> local: Done",LOG_LEVEL_NOTICE,"balance-r2l")}catch(ex){Logger("Something went wrong on balancing!",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}(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.core.$anyResolveConflictByNewest(file)}this._log("Done!",LOG_LEVEL_NOTICE,"resolveAllConflictedFilesByNewerOnes")}};import_obsidian14=require("obsidian");ModuleReplicateTest=class extends AbstractObsidianModule{constructor(){super(...arguments);this.testRootPath="_test/";this.testInfoPath="_testinfo/";this.watchIsSynchronised=!1}get isLeader(){return this.core.$$getVaultName().indexOf("dev")>=0&&this.core.$$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_obsidian14.parseYaml)(await this.readFileContent(fileMine)),pair=(0,import_obsidian14.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=[],webcrypto5=await getWebCrypto();for(const file of files){if(!await this.core.$$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),hash2=await webcrypto5.subtle.digest("SHA-1",hashSrc),hashStr=uint8ArrayToHexString(new Uint8Array(hash2)),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_obsidian14.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),webcrypto5=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),hash2=await webcrypto5.subtle.digest("SHA-1",hashSrc),hashStr=uint8ArrayToHexString(new Uint8Array(hash2)),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_obsidian14.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_obsidian14.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.core.$$replicate();this.isLeader&&await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"wonka.md","Resolve! \n*****, the amazing chocolatier!!");await this.core.$$replicate();await this.core.$$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.core.$$replicate();await this.core.$$replicate();return!!await this.waitFor((async()=>{await this.core.$$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.core.$$replicate();this.isLeader&&await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"concat.md","Resolve To concatenate\nABCDEFG");await this.core.$$replicate();await this.core.$$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.core.$$replicate();await this.core.$$replicate();return!!await this.waitFor((async()=>{await this.core.$$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.core.$$replicate();await this.core.$$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.core.$$replicate();await this.core.$$replicate();await delay(1e3);if("no"!=await this.core.confirm.askYesNoDialog("Ready to check result?",{timeout:30,defaultOption:"Yes"})){await this.core.$$replicate();await this.core.$$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.core.$$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()}};ModuleLiveSyncMain=class extends AbstractModule{constructor(){super(...arguments);this.isReady=!1;this._suspended=!1;this._unloaded=!1}async $$onLiveSyncReady(){if(await this.core.$everyOnLayoutReady()){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();await this.core.$$scheduleAppReload();return}}if(!await this.core.$$initializeDatabase(!1,!1))return!1;if(await this.core.$everyOnFirstInitialize()){await this.core.$$realizeSettingSyncMode();fireAndForget((async()=>{this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"),LOG_LEVEL_VERBOSE);await this.core.$allScanStat()?this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"),LOG_LEVEL_VERBOSE):this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"),LOG_LEVEL_NOTICE)}))}}}$$wireUpEvents(){eventHub.onEvent("setting-saved",(settings=>{this.localDatabase.settings=settings;setLang(settings.displayLanguage);eventHub.emitEvent("reload-setting-tab")}));eventHub.onEvent("setting-saved",(settings=>{fireAndForget((()=>this.core.$$realizeSettingSyncMode()))}))}async $$onLiveSyncLoad(){this.$$wireUpEvents();eventHub.emitEvent("plugin-loaded",this.core);this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));if(!await this.core.$everyOnloadStart()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return}this._log($msg("moduleLiveSyncMain.logPluginVersion",{manifestVersion:"0.24.31",packageVersion:"0.24.31"}));await this.core.$$loadSettings();if(!await this.core.$everyOnloadAfterLoadSettings()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return}const lsKey="obsidian-live-sync-ver"+this.core.$$getVaultName(),last_version=localStorage.getItem(lsKey);~~(versionNumberString2Number("0.24.31")/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)<10){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,"10");await this.core.$$openDatabase();this.core.$$realizeSettingSyncMode=this.core.$$realizeSettingSyncMode.bind(this);this.core.$$onLiveSyncReady=this.core.$$onLiveSyncReady.bind(this);await this.core.$everyOnload();await Promise.all(this.core.addOns.map((e3=>e3.onload())))}async $$onLiveSyncUnload(){var _a8;eventHub.emitEvent("plugin-unloaded");await this.core.$allStartOnUnload();(function cancelAllPeriodicTask(){for(const v2 in intervals)cancelPeriodicTask(v2)})();(function cancelAllTasks(){for(const v2 of tasks2.keys())cancelTask(v2)})();(function stopAllRunningProcessors(){const processors=[...allRunningProcessors];for(const processor of processors)processor.terminate()})();await this.core.$allOnUnload();this._unloaded=!0;for(const addOn of this.core.addOns)addOn.onunload();if(null!=this.localDatabase){this.localDatabase.onunload();this.core.replicator&&(null==(_a8=this.core.replicator)||_a8.closeReplication());await this.localDatabase.close()}eventHub.emitEvent("platform-unloaded");eventHub.offAll();this._log($msg("moduleLiveSyncMain.logUnloadingPlugin"))}async $$realizeSettingSyncMode(){await this.core.$everyBeforeSuspendProcess();await this.core.$everyBeforeRealizeSetting();this.localDatabase.refreshSettings();await this.core.$everyCommitPendingFileEvent();await this.core.$everyRealizeSettingSyncMode();if(!this.core.$$isSuspended()){await this.core.$everyOnResumeProcess();await this.core.$everyAfterResumeProcess();await this.core.$everyAfterRealizeSetting()}}$$isReloadingScheduled(){return void 0!==this.core._totalProcessingCount}$$isReady(){return this.isReady}$$markIsReady(){this.isReady=!0}$$resetIsReady(){this.isReady=!1}$$isSuspended(){var _a8;return this._suspended||!(null==(_a8=this.settings)?void 0:_a8.isConfigured)}$$setSuspended(value){this._suspended=value}$$isUnloaded(){return this._unloaded}};ModuleExtraSyncObsidian=class extends AbstractObsidianModule{constructor(){super(...arguments);this.deviceAndVaultName=""}$$getDeviceAndVaultName(){return this.deviceAndVaultName}$$setDeviceAndVaultName(name){this.deviceAndVaultName=name}};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_25=template(" ");root_113=template('
    ');root_34=template(' ');on_click2=(__3,makeDecision)=>makeDecision(!0,!0);on_click_1=(__4,makeDecision)=>makeDecision(!0,!1);root_54=template(' ',1);on_click_2=(__5,makeDecision)=>makeDecision(!1,!0);on_click_3=(__6,makeDecision)=>makeDecision(!1,!1);root_65=template(' ',1);root_45=template(" ",1);on_click_4=(__7,revokeDecision)=>revokeDecision();root_72=template('');root_94=template('');root_103=template('');root_84=template('
    ');root7=template('
    ');$$css8={hash:"svelte-d7sijc",code:"tr.svelte-d7sijc:nth-child(odd) {background-color:var(--background-primary-alt);}.info.svelte-d7sijc {display:flex;flex-direction:column;justify-content:center;align-items:center;padding:var(--size-4-1) var(--size-4-1);}.peer-id.svelte-d7sijc {font-size:0.8em;}.status-chips.svelte-d7sijc {display:flex;flex-direction:column;justify-content:center;align-items:center;\n /* min-width: 10em; */}.buttons.svelte-d7sijc {display:flex;flex-direction:column;justify-content:center;align-items:center;}.buttons.svelte-d7sijc .row:where(.svelte-d7sijc) {display:flex;justify-content:center;align-items:center;flex-wrap:wrap;\n /* padding: var(--size-4-1) var(--size-4-1); */}.chip.svelte-d7sijc {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-d7sijc {background-color:var(--background-modifier-success);color:var(--text-normal);}.chip.connected-live.svelte-d7sijc {background-color:var(--background-modifier-success);border-color:var(--background-modifier-success);color:var(--text-normal);}.chip.accepted.svelte-d7sijc {background-color:var(--background-modifier-success);color:var(--text-normal);}.chip.waiting.svelte-d7sijc {background-color:var(--background-secondary);}.chip.unknown.svelte-d7sijc {background-color:var(--background-primary);color:var(--text-warning);}.chip.denied.svelte-d7sijc {background-color:var(--background-modifier-error);color:var(--text-error);}.chip.attr.svelte-d7sijc {background-color:var(--background-secondary);}.button.svelte-d7sijc {margin:var(--size-4-1);}.button.affirmative.svelte-d7sijc {background-color:var(--interactive-accent);color:var(--text-normal);}.button.affirmative.svelte-d7sijc:hover {background-color:var(--interactive-accent-hover);}.button.negative.svelte-d7sijc {background-color:var(--background-modifier-error);color:var(--text-error);}.button.negative.svelte-d7sijc:hover {background-color:var(--background-modifier-error-hover);}"};delegate(["click"]);root_114=template('

    ');on_click3=(__5,useDefaultRelay)=>useDefaultRelay();on_click_12=(__6,chooseRandom)=>chooseRandom();root_26=template('

    No Connection

    ');root_35=template('

    ');root_46=template("");root_73=template("");root_85=template("");root_55=template('
    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);root8=template('

    Peer to Peer Replicator

    Connection Settings

    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

    Signaling Server Connection

    Peers

    NameActionCommand
    ');$$css9={hash:"svelte-1i6qkqk",code:"article.svelte-1i6qkqk {max-width:100%;}article.svelte-1i6qkqk p:where(.svelte-1i6qkqk) {user-select:text;-webkit-user-select:text;}h2.svelte-1i6qkqk {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-1i6qkqk {background-color:var(--background-modifier-error);}input.svelte-1i6qkqk {background-color:transparent;}th.svelte-1i6qkqk {\n /* display: flex;\n justify-content: center;\n align-items: center; */min-height:var(--input-height);}td.svelte-1i6qkqk {min-height:var(--input-height);}td.svelte-1i6qkqk > label:where(.svelte-1i6qkqk) {display:flex;flex-direction:row;align-items:center;justify-content:flex-start;min-height:var(--input-height);}td.svelte-1i6qkqk > label:where(.svelte-1i6qkqk) > :where(.svelte-1i6qkqk) {margin:auto var(--size-4-1);}table.peers.svelte-1i6qkqk {width:100%;}.important.svelte-1i6qkqk {color:var(--text-error);font-size:1.2em;font-weight:bold;}.important-sub.svelte-1i6qkqk {color:var(--text-warning);}.settings.svelte-1i6qkqk label:where(.svelte-1i6qkqk) {display:flex;flex-direction:row;align-items:center;justify-content:flex-start;flex-wrap:wrap;}"};delegate(["click"]);import_obsidian15=require("obsidian");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_obsidian15.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():await this.plugin.$$scheduleAppReload()}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]=function removeFromList(item,list){return list.split(",").map((e3=>e3.trim())).filter((p4=>p4!==item)).filter((p4=>p4)).join(",")}(peer.name,this.plugin.settings[targetSetting]);await this.plugin.saveSettings()}else{this.plugin.settings[targetSetting]=function addToList(item,list){return unique(list.split(",").map((e3=>e3.trim())).concat(item).filter((p4=>p4))).join(",")}(peer.name,this.plugin.settings[targetSetting]);await this.plugin.saveSettings()}await this.plugin.saveSettings()}getViewType(){return"p2p-replicator"}getDisplayText(){return"Peer-to-Peer Replicator"}async onClose(){await super.onClose();this.m&&this.m.hide()}instantiateComponent(target){const cmdSync=this.plugin.getAddOn(P2PReplicator.name);if(!cmdSync)throw new Error("Replicator not found");return mount(P2PReplicatorPane,{target,props:{plugin:cmdSync.plugin,cmdSync}})}};require("obsidian");ObsidianAPIBase=class extends APIBase{constructor(options){super();this.app=options.app}};eventHub.onceEvent("platform-unloaded",(()=>{instance2=void 0;p3.resolve(void 0)}));instance2=void 0;p3=promiseWithResolver();import_obsidian17=require("obsidian");Environment=class extends ObsidianAPIBase{async onInit(){this.crypto=await function getWebCrypto2(){if(webcrypto4)return Promise.resolve(webcrypto4);if(globalThis.crypto){webcrypto4=globalThis.crypto;return Promise.resolve(webcrypto4)}throw new Error("WebCrypto not available")}()}getPlatformName(){return getPlatformName()}getPackageVersion(){return"0.24.31"}getManifestVersion(){return"0.24.31"}getVaultName(){return this.app.vault.getName()}};eventHub.onceEvent("app-supplied",(app2=>{const platformAPI=new Environment({app:app2});platformAPI.onInit().then((()=>function setEnvironmentInstance(env){if(instance2)instance2=env;else{instance2=env;p3.resolve(env)}}(platformAPI)))}));P2PReplicatorCommandBase=class extends LiveSyncCommands{constructor(plugin3){super(plugin3);this.storeP2PStatusLine=reactiveSource("")}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.plugin.$$parseReplicationResult(docs)}onunload(){throw new Error("Method not implemented.")}onload(){throw new Error("Method not implemented.")}init(){this._simpleStore=this.plugin.$$getSimpleStore("p2p-sync");return Promise.resolve(this)}};P2PReplicator=class extends(function P2PReplicatorMixIn(base){return class MixInP2PReplicatorCommand extends base{constructor(...args){super(...args);this.p2pLogCollector=new P2PLogCollector;setReplicatorFunc((()=>this._replicatorInstance));(function addP2PEventHandlers(instance3){eventHub.onEvent("p2p-advertisement-received",(peerId=>{var _a8;return null==(_a8=instance3._replicatorInstance)?void 0:_a8.onNewPeer(peerId)}));eventHub.onEvent("p2p-device-leaved",(info3=>{var _a8;return null==(_a8=instance3._replicatorInstance)?void 0:_a8.onPeerLeaved(info3)}));eventHub.onEvent(EVENT_REQUEST_STATUS,(()=>{var _a8;null==(_a8=instance3._replicatorInstance)||_a8.requestStatus()}));eventHub.onEvent("database-rebuilt",(async()=>{await instance3.initialiseP2PReplicator()}));eventHub.onEvent("p2p-request-force-open",(()=>{instance3.open()}));eventHub.onEvent("platform-unloaded",(()=>{instance3.close()}));eventHub.onEvent("setting-saved",(async settings=>{await instance3.initialiseP2PReplicator()}))})(this);this.afterConstructor()}afterConstructor(){}getPlatform(){return"unknown"}async open(){await async function openP2PReplicator(instance3){var _a8;if(instance3.settings.P2P_Enabled)if(instance3._replicatorInstance)await(null==(_a8=instance3._replicatorInstance)?void 0:_a8.open());else{await instance3.initialiseP2PReplicator();await instance3._replicatorInstance.open()}else instance3._notice($msg("P2P.NotEnabled"))}(this)}async close(){await async function closeP2PReplicator(instance3){var _a8;await(null==(_a8=instance3._replicatorInstance)?void 0:_a8.close());instance3._replicatorInstance=void 0}(this)}getConfig(key2){const dbKey=`${this.plugin.$$getVaultName()}-${key2}`;return localStorage.getItem(dbKey)}setConfig(key2,value){const dbKey=`${this.plugin.$$getVaultName()}-${key2}`;localStorage.setItem(dbKey,value)}enableBroadcastCastings(){var _a8;return null==(_a8=null==this?void 0:this._replicatorInstance)?void 0:_a8.enableBroadcastChanges()}disableBroadcastCastings(){var _a8;return null==(_a8=null==this?void 0:this._replicatorInstance)?void 0:_a8.disableBroadcastChanges()}init(){return super.init()}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("p2p_device_name")||this.plugin.$$getVaultName(),getSettings=()=>this.settings,store=()=>this.simpleStore(),getDB=()=>this.getDB(),getConfirm=()=>this.confirm,getPlatform=()=>this.getPlatform(),env={get db(){return getDB()},get confirm(){return getConfirm()},get deviceName(){return getInitialDeviceName()},get platform(){return getPlatform()},get settings(){return getSettings()},processReplicatedDocs:async docs=>{await this.handleReplicatedDocuments(docs)},get simpleStore(){return store()}};this._replicatorInstance=new TrysteroReplicator(env);return this._replicatorInstance}catch(e3){this._log(e3 instanceof Error?e3.message:"Something occurred on Initialising P2P Replicator",LOG_LEVEL_INFO);this._log(e3,LOG_LEVEL_VERBOSE);throw e3}}}}(P2PReplicatorCommandBase)){constructor(){super(...arguments);this.storeP2PStatusLine=reactiveSource("")}$anyNewReplicator(settingOverride={}){if({...this.settings,...settingOverride}.remoteType==REMOTE_P2P)return Promise.resolve(new LiveSyncTrysteroReplicator(this.plugin))}getPlatform(){return getPlatformName()}onunload(){(function removeP2PReplicatorInstance(){setReplicatorFunc((()=>{}))})();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 $everyOnLoadStart(){return await Promise.resolve()}async openPane(){await this.plugin.$$showView("p2p-replicator")}async $everyOnloadStart(){this.plugin.registerView("p2p-replicator",(leaf=>new P2PReplicatorPaneView(leaf,this.plugin)));this.plugin.addCommand({id:"open-p2p-replicator",name:"P2P Sync : Open P2P Replicator",callback:async()=>{await this.openPane()}});this.plugin.addCommand({id:"p2p-establish-connection",name:"P2P Sync : Connect to the Signalling Server",checkCallback:isChecking=>{var _a8,_b4,_c3;if(isChecking)return!(null!=(_c3=null==(_b4=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b4.isServing)&&_c3);this.open()}});this.plugin.addCommand({id:"p2p-close-connection",name:"P2P Sync : Disconnect from the Signalling Server",checkCallback:isChecking=>{var _a8,_b4,_c3;if(isChecking)return null!=(_c3=null==(_b4=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b4.isServing)&&_c3;Logger("Closing P2P Connection",LOG_LEVEL_NOTICE);this.close()}});this.plugin.addCommand({id:"replicate-now-by-p2p",name:"Replicate now by P2P",checkCallback:isChecking=>{var _a8,_b4,_c3;if(isChecking)return this.settings.remoteType!=REMOTE_P2P&&!!(null==(_b4=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b4.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);return Promise.resolve(!0)}};InterceptiveAll=Promise.resolve(!0);InterceptiveEvery=Promise.resolve(!0);InterceptiveAny=Promise.resolve(void 0);ObsidianLiveSyncPlugin=class extends import_obsidian.Plugin{constructor(){super(...arguments);this.addOns=[new ConfigSync(this),new HiddenFileSync(this),new LocalDatabaseMaintenance(this),new P2PReplicator(this)];this.modules=[new ModuleLiveSyncMain(this),new ModuleExtraSyncObsidian(this,this),new ModuleDatabaseFileAccess(this),new ModulePouchDB(this),new ModuleConflictChecker(this),new ModuleLocalDatabaseObsidian(this),new ModuleReplicatorMinIO(this),new ModuleReplicatorCouchDB(this),new ModuleReplicator(this),new ModuleFileHandler(this),new ModuleConflictResolver(this),new ModuleRemoteGovernor(this),new ModuleTargetFilter(this),new ModulePeriodicProcess(this),new ModuleKeyValueDB(this),new ModuleInitializerFile(this),new ModuleObsidianAPI(this,this),new ModuleObsidianEvents(this,this),new ModuleFileAccessObsidian(this,this),new ModuleObsidianSettings(this,this),new ModuleResolvingMismatchedTweaks(this),new ModuleObsidianSettingsAsMarkdown(this,this),new ModuleObsidianSettingDialogue(this,this),new ModuleLog(this,this),new ModuleInputUIObsidian(this,this),new ModuleObsidianMenu(this,this),new ModuleRebuilder(this),new ModuleSetupObsidian(this,this),new ModuleObsidianDocumentHistory(this,this),new ModuleMigration(this),new ModuleRedFlag(this),new ModuleInteractiveConflictResolver(this,this),new ModuleObsidianGlobalHistory(this,this),new ModuleCheckRemoteSize(this),new ModuleDev(this,this),new ModuleReplicateTest(this,this),new ModuleIntegratedTest(this,this)];this.injected=function injectModules(target,modules){const allKeys=unique([...Object.keys(Object.getOwnPropertyDescriptors(target)),...Object.keys(Object.getOwnPropertyDescriptors(Object.getPrototypeOf(target)))]).filter((e3=>e3.startsWith("$"))),moduleMap=new Map;for(const module2 of modules)for(const key2 of allKeys)if(isOverridableKey(key2)&&key2 in module2){const list=moduleMap.get(key2)||[];"function"==typeof module2[key2]&&(module2[key2]=module2[key2].bind(module2));list.push(module2);moduleMap.set(key2,list)}Logger(`Injecting modules for ${target.constructor.name}`,LOG_LEVEL_VERBOSE);for(const key2 of allKeys){const modules2=moduleMap.get(key2)||[];if(isInjectableKey(key2)){if(0==modules2.length)throw new Error(`No module injected for ${key2}. This is a fatal error.`);target[key2]=modules2[0][key2];Logger(`[${modules2[0].constructor.name}]: Injected ${key2} `,LOG_LEVEL_VERBOSE)}else if(isAllExecuteKey(key2)){const modules3=moduleMap.get(key2)||[];target[key2]=async(...args)=>{for(const module2 of modules3)try{await module2[key2](...args)}catch(ex){Logger(`[${module2.constructor.name}]: All handler for ${key2} failed`,LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}return!0};for(const module2 of modules3)Logger(`[${module2.constructor.name}]: Injected (All) ${key2} `,LOG_LEVEL_VERBOSE)}else if(isEveryExecuteKey(key2)){target[key2]=async(...args)=>{for(const module2 of modules2)try{const ret=await module2[key2](...args);if(void 0!==ret&&!ret)return ret}catch(ex){Logger(`[${module2.constructor.name}]: Every handler for ${key2} failed`);Logger(ex,LOG_LEVEL_VERBOSE)}return!0};for(const module2 of modules2)Logger(`[${module2.constructor.name}]: Injected (Every) ${key2} `,LOG_LEVEL_VERBOSE)}else if(isAnyExecuteKey(key2)){target[key2]=async(...args)=>{for(const module2 of modules2)try{const ret=await module2[key2](...args);if(ret)return ret}catch(ex){Logger(`[${module2.constructor.name}]: Any handler for ${key2} failed`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1};for(const module2 of modules2)Logger(`[${module2.constructor.name}]: Injected (Any) ${key2} `,LOG_LEVEL_VERBOSE)}else Logger(`No injected handler for ${key2} `,LOG_LEVEL_VERBOSE)}Logger(`Injected modules for ${target.constructor.name}`,LOG_LEVEL_VERBOSE);return!0}(this,[...this.modules,...this.addOns]);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"})}getAddOn(cls){for(const addon of this.addOns)if(addon.constructor.name==cls)return addon}$$isSuspended(){throwShouldBeOverridden()}$$setSuspended(value){throwShouldBeOverridden()}$$isDatabaseReady(){throwShouldBeOverridden()}$$getDeviceAndVaultName(){throwShouldBeOverridden()}$$setDeviceAndVaultName(name){throwShouldBeOverridden()}$$addLog(message,level=LOG_LEVEL_INFO,key2=""){throwShouldBeOverridden()}$$isReady(){throwShouldBeOverridden()}$$markIsReady(){throwShouldBeOverridden()}$$resetIsReady(){throwShouldBeOverridden()}getDatabase(){return this.localDatabase.localDatabase}getSettings(){return this.settings}$$markFileListPossiblyChanged(){throwShouldBeOverridden()}$$customFetchHandler(){throwShouldBeOverridden()}$$getLastPostFailedBySize(){throwShouldBeOverridden()}$$isStorageInsensitive(){throwShouldBeOverridden()}$$shouldCheckCaseInsensitive(){throwShouldBeOverridden()}$$isUnloaded(){throwShouldBeOverridden()}$$isReloadingScheduled(){throwShouldBeOverridden()}$$getReplicator(){throwShouldBeOverridden()}$$connectRemoteCouchDB(uri,auth,disableRequestURI,passphrase,useDynamicIterationCount,performSetup,skipInfo,compression,customHeaders,useRequestAPI){throwShouldBeOverridden()}$$isMobile(){throwShouldBeOverridden()}$$vaultName(){throwShouldBeOverridden()}$$getActiveFilePath(){throwShouldBeOverridden()}$$id2path(id,entry,stripPrefix2){throwShouldBeOverridden()}$$path2id(filename,prefix){throwShouldBeOverridden()}$$createPouchDBInstance(name,options){throwShouldBeOverridden()}$allOnDBUnload(db){}$allOnDBClose(db){}$anyNewReplicator(settingOverride={}){throwShouldBeOverridden()}$everyOnInitializeDatabase(db){return InterceptiveEvery}$everyOnResetDatabase(db){return InterceptiveEvery}$$getVaultName(){throwShouldBeOverridden()}$$getSimpleStore(kind){throwShouldBeOverridden()}$everyOnLayoutReady(){return InterceptiveEvery}$everyOnFirstInitialize(){return InterceptiveEvery}$$onLiveSyncReady(){throwShouldBeOverridden()}$$wireUpEvents(){throwShouldBeOverridden()}$$onLiveSyncLoad(){throwShouldBeOverridden()}$$onLiveSyncUnload(){throwShouldBeOverridden()}$allScanStat(){return InterceptiveAll}$everyOnloadStart(){return InterceptiveEvery}$everyOnloadAfterLoadSettings(){return InterceptiveEvery}$everyOnload(){return InterceptiveEvery}$anyHandlerProcessesFileEvent(item){return InterceptiveAny}$allStartOnUnload(){return InterceptiveAll}$allOnUnload(){return InterceptiveAll}$$openDatabase(){throwShouldBeOverridden()}$$realizeSettingSyncMode(){throwShouldBeOverridden()}$$performRestart(){throwShouldBeOverridden()}$$clearUsedPassphrase(){throwShouldBeOverridden()}$$loadSettings(){throwShouldBeOverridden()}$$saveDeviceAndVaultName(){throwShouldBeOverridden()}$$saveSettingData(){throwShouldBeOverridden()}$anyProcessOptionalFileEvent(path2){return InterceptiveAny}$everyCommitPendingFileEvent(){return InterceptiveEvery}$anyGetOptionalConflictCheckMethod(path2){return InterceptiveAny}$$queueConflictCheckIfOpen(file){throwShouldBeOverridden()}$$queueConflictCheck(file){throwShouldBeOverridden()}$$waitForAllConflictProcessed(){throwShouldBeOverridden()}$anyProcessOptionalSyncFiles(doc){return InterceptiveAny}$anyProcessReplicatedDoc(doc){return InterceptiveAny}$$parseReplicationResult(docs){throwShouldBeOverridden()}$anyModuleParsedReplicationResultItem(docs){return InterceptiveAny}$everyBeforeRealizeSetting(){return InterceptiveEvery}$everyAfterRealizeSetting(){return InterceptiveEvery}$everyRealizeSettingSyncMode(){return InterceptiveEvery}$everyBeforeSuspendProcess(){return InterceptiveEvery}$everyOnResumeProcess(){return InterceptiveEvery}$everyAfterResumeProcess(){return InterceptiveEvery}$$checkAndAskResolvingMismatchedTweaks(preferred){throwShouldBeOverridden()}$$askResolvingMismatchedTweaks(preferredSource){throwShouldBeOverridden()}$$checkAndAskUseRemoteConfiguration(settings){throwShouldBeOverridden()}$$askUseRemoteConfiguration(trialSetting,preferred){throwShouldBeOverridden()}$everyBeforeReplicate(showMessage){return InterceptiveEvery}$$replicate(showMessage=!1){throwShouldBeOverridden()}$$replicateByEvent(showMessage=!1){throwShouldBeOverridden()}$everyOnDatabaseInitialized(showingNotice){throwShouldBeOverridden()}$$initializeDatabase(showingNotice=!1,reopenDatabase=!0){throwShouldBeOverridden()}$anyAfterConnectCheckFailed(){return InterceptiveAny}$$replicateAllToServer(showingNotice=!1,sendChunksInBulkDisabled=!1){throwShouldBeOverridden()}$$replicateAllFromServer(showingNotice=!1){throwShouldBeOverridden()}$$markRemoteLocked(lockByClean=!1){throwShouldBeOverridden()}$$markRemoteUnlocked(){throwShouldBeOverridden()}$$markRemoteResolved(){throwShouldBeOverridden()}$$isFileSizeExceeded(size){throwShouldBeOverridden()}$$performFullScan(showingNotice){throwShouldBeOverridden()}$anyResolveConflictByUI(filename,conflictCheckResult){return InterceptiveAny}$$resolveConflictByDeletingRev(path2,deleteRevision,subTitle=""){throwShouldBeOverridden()}$$resolveConflict(filename){throwShouldBeOverridden()}$anyResolveConflictByNewest(filename){throwShouldBeOverridden()}$$resetLocalDatabase(){throwShouldBeOverridden()}$$tryResetRemoteDatabase(){throwShouldBeOverridden()}$$tryCreateRemoteDatabase(){throwShouldBeOverridden()}$$isIgnoredByIgnoreFiles(file){throwShouldBeOverridden()}$$isTargetFile(file,keepFileCheckList=!1){throwShouldBeOverridden()}$$askReload(message){throwShouldBeOverridden()}$$scheduleAppReload(){throwShouldBeOverridden()}$allSuspendAllSync(){return InterceptiveAll}$allSuspendExtraSync(){return InterceptiveAll}$allAskUsingOptionalSyncFeature(opt){throwShouldBeOverridden()}$anyConfigureOptionalSyncFeature(mode){throwShouldBeOverridden()}$$showView(viewType){throwShouldBeOverridden()}$everyModuleTest(){return InterceptiveEvery}$everyModuleTestMultiDevice(){return InterceptiveEvery}$$addTestResult(name,key2,result,summary,message){throwShouldBeOverridden()}_isThisModuleEnabled(){return!0}$anyGetAppId(){return InterceptiveAny}onload(){this.$$onLiveSyncLoad()}async saveSettings(){await this.$$saveSettingData()}onunload(){this.$$onLiveSyncUnload()}}; +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-livesync/manifest.json b/.obsidian/plugins/obsidian-livesync/manifest.json new file mode 100644 index 00000000..f51a6436 --- /dev/null +++ b/.obsidian/plugins/obsidian-livesync/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-livesync", + "name": "Self-hosted LiveSync", + "version": "0.24.31", + "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/.obsidian/plugins/obsidian-livesync/styles.css b/.obsidian/plugins/obsidian-livesync/styles.css new file mode 100644 index 00000000..62a0eb6f --- /dev/null +++ b/.obsidian/plugins/obsidian-livesync/styles.css @@ -0,0 +1,454 @@ +.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); +} + +.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: 4px 4px 0 0; + padding: 6px 10px; + cursor: pointer; + margin-right: 12px; + 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; + background-color: rgba(var(--background-primary), 0.3); + backdrop-filter: blur(4px); + border-radius: 4px; + 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%; +} + +.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 { + opacity: 0.6; + color: var(--text-on-accent); + background: var(--background-modifier-error); + -webkit-filter: unset; + filter: unset; +} + +.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; +} + +.sls-setting-panel-title { + top: 2em; + background-color: rgba(var(--background-primary), 0.3); + backdrop-filter: blur(4px); + border-radius: 30%; +} + +.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/.obsidian/plugins/obsidian-omnivore/main.js b/.obsidian/plugins/obsidian-omnivore/main.js deleted file mode 100644 index 03915bb6..00000000 --- a/.obsidian/plugins/obsidian-omnivore/main.js +++ /dev/null @@ -1,18905 +0,0 @@ -/* -THIS IS A GENERATED/BUNDLED FILE BY ESBUILD -if you want to view the source, please visit the github repository of this plugin -*/ - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// node_modules/@0no-co/graphql.web/dist/graphql.web.js -var require_graphql_web = __commonJS({ - "node_modules/@0no-co/graphql.web/dist/graphql.web.js"(exports) { - Object.defineProperty(exports, "__esModule", { - value: true - }); - var GraphQLError = class extends Error { - constructor(e2, r2, i2, n3, t2, a2, o2) { - super(e2); - this.name = "GraphQLError"; - this.message = e2; - if (t2) { - this.path = t2; - } - if (r2) { - this.nodes = Array.isArray(r2) ? r2 : [r2]; - } - if (i2) { - this.source = i2; - } - if (n3) { - this.positions = n3; - } - if (a2) { - this.originalError = a2; - } - var l3 = o2; - if (!l3 && a2) { - var u2 = a2.extensions; - if (u2 && typeof u2 == "object") { - l3 = u2; - } - } - this.extensions = l3 || {}; - } - toJSON() { - return { - ...this, - message: this.message - }; - } - toString() { - return this.message; - } - get [Symbol.toStringTag]() { - return "GraphQLError"; - } - }; - var e; - var r; - function error(e2) { - return new GraphQLError(`Syntax Error: Unexpected token at ${r} in ${e2}`); - } - function advance(i2) { - i2.lastIndex = r; - if (i2.test(e)) { - return e.slice(r, r = i2.lastIndex); - } - } - var i = / +(?=[^\s])/y; - function blockString(e2) { - var r2 = e2.split("\n"); - var n3 = ""; - var t2 = 0; - var a2 = 0; - var o2 = r2.length - 1; - for (var l3 = 0; l3 < r2.length; l3++) { - i.lastIndex = 0; - if (i.test(r2[l3])) { - if (l3 && (!t2 || i.lastIndex < t2)) { - t2 = i.lastIndex; - } - a2 = a2 || l3; - o2 = l3; - } - } - for (var u2 = a2; u2 <= o2; u2++) { - if (u2 !== a2) { - n3 += "\n"; - } - n3 += r2[u2].slice(t2).replace(/\\"""/g, '"""'); - } - return n3; - } - function ignored() { - for (var i2 = 0 | e.charCodeAt(r++); i2 === 9 || i2 === 10 || i2 === 13 || i2 === 32 || i2 === 35 || i2 === 44 || i2 === 65279; i2 = 0 | e.charCodeAt(r++)) { - if (i2 === 35) { - while ((i2 = e.charCodeAt(r++)) !== 10 && i2 !== 13) { - } - } - } - r--; - } - var n2 = /[_A-Za-z]\w*/y; - function name() { - var e2; - if (e2 = advance(n2)) { - return { - kind: "Name", - value: e2 - }; - } - } - var t = /(?:null|true|false)/y; - var a = /\$[_A-Za-z]\w*/y; - var o = /-?\d+/y; - var l2 = /(?:\.\d+)?[eE][+-]?\d+|\.\d+/y; - var u = /\\/g; - var v = /"""(?:"""|(?:[\s\S]*?[^\\])""")/y; - var d = /"(?:"|[^\r\n]*?[^\\]")/y; - function value(i2) { - var s3; - var c2; - if (c2 = advance(t)) { - s3 = c2 === "null" ? { - kind: "NullValue" - } : { - kind: "BooleanValue", - value: c2 === "true" - }; - } else if (!i2 && (c2 = advance(a))) { - s3 = { - kind: "Variable", - name: { - kind: "Name", - value: c2.slice(1) - } - }; - } else if (c2 = advance(o)) { - var f2 = c2; - if (c2 = advance(l2)) { - s3 = { - kind: "FloatValue", - value: f2 + c2 - }; - } else { - s3 = { - kind: "IntValue", - value: f2 - }; - } - } else if (c2 = advance(n2)) { - s3 = { - kind: "EnumValue", - value: c2 - }; - } else if (c2 = advance(v)) { - s3 = { - kind: "StringValue", - value: blockString(c2.slice(3, -3)), - block: true - }; - } else if (c2 = advance(d)) { - s3 = { - kind: "StringValue", - value: u.test(c2) ? JSON.parse(c2) : c2.slice(1, -1), - block: false - }; - } else if (s3 = function list(i3) { - var n3; - if (e.charCodeAt(r) === 91) { - r++; - ignored(); - var t2 = []; - while (n3 = value(i3)) { - t2.push(n3); - } - if (e.charCodeAt(r++) !== 93) { - throw error("ListValue"); - } - ignored(); - return { - kind: "ListValue", - values: t2 - }; - } - }(i2) || function object(i3) { - if (e.charCodeAt(r) === 123) { - r++; - ignored(); - var n3 = []; - var t2; - while (t2 = name()) { - ignored(); - if (e.charCodeAt(r++) !== 58) { - throw error("ObjectField"); - } - ignored(); - var a2 = value(i3); - if (!a2) { - throw error("ObjectField"); - } - n3.push({ - kind: "ObjectField", - name: t2, - value: a2 - }); - } - if (e.charCodeAt(r++) !== 125) { - throw error("ObjectValue"); - } - ignored(); - return { - kind: "ObjectValue", - fields: n3 - }; - } - }(i2)) { - return s3; - } - ignored(); - return s3; - } - function arguments_(i2) { - var n3 = []; - ignored(); - if (e.charCodeAt(r) === 40) { - r++; - ignored(); - var t2; - while (t2 = name()) { - ignored(); - if (e.charCodeAt(r++) !== 58) { - throw error("Argument"); - } - ignored(); - var a2 = value(i2); - if (!a2) { - throw error("Argument"); - } - n3.push({ - kind: "Argument", - name: t2, - value: a2 - }); - } - if (!n3.length || e.charCodeAt(r++) !== 41) { - throw error("Argument"); - } - ignored(); - } - return n3; - } - function directives(i2) { - var n3 = []; - ignored(); - while (e.charCodeAt(r) === 64) { - r++; - var t2 = name(); - if (!t2) { - throw error("Directive"); - } - ignored(); - n3.push({ - kind: "Directive", - name: t2, - arguments: arguments_(i2) - }); - } - return n3; - } - function field() { - var i2 = name(); - if (i2) { - ignored(); - var n3; - if (e.charCodeAt(r) === 58) { - r++; - ignored(); - n3 = i2; - if (!(i2 = name())) { - throw error("Field"); - } - ignored(); - } - return { - kind: "Field", - alias: n3, - name: i2, - arguments: arguments_(false), - directives: directives(false), - selectionSet: selectionSet() - }; - } - } - function type() { - var i2; - ignored(); - if (e.charCodeAt(r) === 91) { - r++; - ignored(); - var n3 = type(); - if (!n3 || e.charCodeAt(r++) !== 93) { - throw error("ListType"); - } - i2 = { - kind: "ListType", - type: n3 - }; - } else if (i2 = name()) { - i2 = { - kind: "NamedType", - name: i2 - }; - } else { - throw error("NamedType"); - } - ignored(); - if (e.charCodeAt(r) === 33) { - r++; - ignored(); - return { - kind: "NonNullType", - type: i2 - }; - } else { - return i2; - } - } - var s2 = /on/y; - function typeCondition() { - if (advance(s2)) { - ignored(); - var e2 = name(); - if (!e2) { - throw error("NamedType"); - } - ignored(); - return { - kind: "NamedType", - name: e2 - }; - } - } - var c = /\.\.\./y; - function fragmentSpread() { - if (advance(c)) { - ignored(); - var e2 = r; - var i2; - if ((i2 = name()) && i2.value !== "on") { - return { - kind: "FragmentSpread", - name: i2, - directives: directives(false) - }; - } else { - r = e2; - var n3 = typeCondition(); - var t2 = directives(false); - var a2 = selectionSet(); - if (!a2) { - throw error("InlineFragment"); - } - return { - kind: "InlineFragment", - typeCondition: n3, - directives: t2, - selectionSet: a2 - }; - } - } - } - function selectionSet() { - var i2; - ignored(); - if (e.charCodeAt(r) === 123) { - r++; - ignored(); - var n3 = []; - while (i2 = fragmentSpread() || field()) { - n3.push(i2); - } - if (!n3.length || e.charCodeAt(r++) !== 125) { - throw error("SelectionSet"); - } - ignored(); - return { - kind: "SelectionSet", - selections: n3 - }; - } - } - var f = /fragment/y; - function fragmentDefinition() { - if (advance(f)) { - ignored(); - var e2 = name(); - if (!e2) { - throw error("FragmentDefinition"); - } - ignored(); - var r2 = typeCondition(); - if (!r2) { - throw error("FragmentDefinition"); - } - var i2 = directives(false); - var n3 = selectionSet(); - if (!n3) { - throw error("FragmentDefinition"); - } - return { - kind: "FragmentDefinition", - name: e2, - typeCondition: r2, - directives: i2, - selectionSet: n3 - }; - } - } - var p = /(?:query|mutation|subscription)/y; - function operationDefinition() { - var i2; - var n3; - var t2 = []; - var o2 = []; - if (i2 = advance(p)) { - ignored(); - n3 = name(); - t2 = function variableDefinitions() { - var i3; - var n4 = []; - ignored(); - if (e.charCodeAt(r) === 40) { - r++; - ignored(); - while (i3 = advance(a)) { - ignored(); - if (e.charCodeAt(r++) !== 58) { - throw error("VariableDefinition"); - } - var t3 = type(); - var o3 = void 0; - if (e.charCodeAt(r) === 61) { - r++; - ignored(); - if (!(o3 = value(true))) { - throw error("VariableDefinition"); - } - } - ignored(); - n4.push({ - kind: "VariableDefinition", - variable: { - kind: "Variable", - name: { - kind: "Name", - value: i3.slice(1) - } - }, - type: t3, - defaultValue: o3, - directives: directives(true) - }); - } - if (e.charCodeAt(r++) !== 41) { - throw error("VariableDefinition"); - } - ignored(); - } - return n4; - }(); - o2 = directives(false); - } - var l3 = selectionSet(); - if (l3) { - return { - kind: "OperationDefinition", - operation: i2 || "query", - name: n3, - variableDefinitions: t2, - directives: o2, - selectionSet: l3 - }; - } - } - var m = {}; - function printString(e2) { - return JSON.stringify(e2); - } - function printBlockString(e2) { - return '"""\n' + e2.replace(/"""/g, '\\"""') + '\n"""'; - } - var hasItems = (e2) => !(!e2 || !e2.length); - var g = { - OperationDefinition(e2) { - if (e2.operation === "query" && !e2.name && !hasItems(e2.variableDefinitions) && !hasItems(e2.directives)) { - return g.SelectionSet(e2.selectionSet); - } - var r2 = e2.operation; - if (e2.name) { - r2 += " " + e2.name.value; - } - if (hasItems(e2.variableDefinitions)) { - if (!e2.name) { - r2 += " "; - } - r2 += "(" + e2.variableDefinitions.map(g.VariableDefinition).join(", ") + ")"; - } - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return r2 + " " + g.SelectionSet(e2.selectionSet); - }, - VariableDefinition(e2) { - var r2 = g.Variable(e2.variable) + ": " + print(e2.type); - if (e2.defaultValue) { - r2 += " = " + print(e2.defaultValue); - } - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return r2; - }, - Field(e2) { - var r2 = (e2.alias ? e2.alias.value + ": " : "") + e2.name.value; - if (hasItems(e2.arguments)) { - var i2 = e2.arguments.map(g.Argument); - var n3 = r2 + "(" + i2.join(", ") + ")"; - r2 = n3.length > 80 ? r2 + "(\n " + i2.join("\n").replace(/\n/g, "\n ") + "\n)" : n3; - } - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return e2.selectionSet ? r2 + " " + g.SelectionSet(e2.selectionSet) : r2; - }, - StringValue: (e2) => e2.block ? printBlockString(e2.value) : printString(e2.value), - BooleanValue: (e2) => "" + e2.value, - NullValue: (e2) => "null", - IntValue: (e2) => e2.value, - FloatValue: (e2) => e2.value, - EnumValue: (e2) => e2.value, - Name: (e2) => e2.value, - Variable: (e2) => "$" + e2.name.value, - ListValue: (e2) => "[" + e2.values.map(print).join(", ") + "]", - ObjectValue: (e2) => "{" + e2.fields.map(g.ObjectField).join(", ") + "}", - ObjectField: (e2) => e2.name.value + ": " + print(e2.value), - Document: (e2) => hasItems(e2.definitions) ? e2.definitions.map(print).join("\n\n") : "", - SelectionSet: (e2) => "{\n " + e2.selections.map(print).join("\n").replace(/\n/g, "\n ") + "\n}", - Argument: (e2) => e2.name.value + ": " + print(e2.value), - FragmentSpread(e2) { - var r2 = "..." + e2.name.value; - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return r2; - }, - InlineFragment(e2) { - var r2 = "..."; - if (e2.typeCondition) { - r2 += " on " + e2.typeCondition.name.value; - } - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return r2 + " " + print(e2.selectionSet); - }, - FragmentDefinition(e2) { - var r2 = "fragment " + e2.name.value; - r2 += " on " + e2.typeCondition.name.value; - if (hasItems(e2.directives)) { - r2 += " " + e2.directives.map(g.Directive).join(" "); - } - return r2 + " " + print(e2.selectionSet); - }, - Directive(e2) { - var r2 = "@" + e2.name.value; - if (hasItems(e2.arguments)) { - r2 += "(" + e2.arguments.map(g.Argument).join(", ") + ")"; - } - return r2; - }, - NamedType: (e2) => e2.name.value, - ListType: (e2) => "[" + print(e2.type) + "]", - NonNullType: (e2) => print(e2.type) + "!" - }; - function print(e2) { - return g[e2.kind] ? g[e2.kind](e2) : ""; - } - function valueFromASTUntyped(e2, r2) { - switch (e2.kind) { - case "NullValue": - return null; - case "IntValue": - return parseInt(e2.value, 10); - case "FloatValue": - return parseFloat(e2.value); - case "StringValue": - case "EnumValue": - case "BooleanValue": - return e2.value; - case "ListValue": - var i2 = []; - for (var n3 = 0, t2 = e2.values; n3 < t2.length; n3 += 1) { - i2.push(valueFromASTUntyped(t2[n3], r2)); - } - return i2; - case "ObjectValue": - var a2 = /* @__PURE__ */ Object.create(null); - for (var o2 = 0, l3 = e2.fields; o2 < l3.length; o2 += 1) { - var u2 = l3[o2]; - a2[u2.name.value] = valueFromASTUntyped(u2.value, r2); - } - return a2; - case "Variable": - return r2 && r2[e2.name.value]; - } - } - exports.BREAK = m; - exports.GraphQLError = GraphQLError; - exports.Kind = { - NAME: "Name", - DOCUMENT: "Document", - OPERATION_DEFINITION: "OperationDefinition", - VARIABLE_DEFINITION: "VariableDefinition", - SELECTION_SET: "SelectionSet", - FIELD: "Field", - ARGUMENT: "Argument", - FRAGMENT_SPREAD: "FragmentSpread", - INLINE_FRAGMENT: "InlineFragment", - FRAGMENT_DEFINITION: "FragmentDefinition", - VARIABLE: "Variable", - INT: "IntValue", - FLOAT: "FloatValue", - STRING: "StringValue", - BOOLEAN: "BooleanValue", - NULL: "NullValue", - ENUM: "EnumValue", - LIST: "ListValue", - OBJECT: "ObjectValue", - OBJECT_FIELD: "ObjectField", - DIRECTIVE: "Directive", - NAMED_TYPE: "NamedType", - LIST_TYPE: "ListType", - NON_NULL_TYPE: "NonNullType" - }; - exports.OperationTypeNode = { - QUERY: "query", - MUTATION: "mutation", - SUBSCRIPTION: "subscription" - }; - exports.parse = function parse4(i2, n3) { - e = typeof i2.body == "string" ? i2.body : i2; - r = 0; - return function document2() { - var e2; - ignored(); - var r2 = []; - while (e2 = fragmentDefinition() || operationDefinition()) { - r2.push(e2); - } - return { - kind: "Document", - definitions: r2 - }; - }(); - }; - exports.parseType = function parseType(i2, n3) { - e = typeof i2.body == "string" ? i2.body : i2; - r = 0; - return type(); - }; - exports.parseValue = function parseValue(i2, n3) { - e = typeof i2.body == "string" ? i2.body : i2; - r = 0; - ignored(); - var t2 = value(false); - if (!t2) { - throw error("ValueNode"); - } - return t2; - }; - exports.print = print; - exports.printBlockString = printBlockString; - exports.printString = printString; - exports.valueFromASTUntyped = valueFromASTUntyped; - exports.valueFromTypeNode = function valueFromTypeNode(e2, r2, i2) { - if (e2.kind === "Variable") { - return i2 ? valueFromTypeNode(i2[e2.name.value], r2, i2) : void 0; - } else if (r2.kind === "NonNullType") { - return e2.kind !== "NullValue" ? valueFromTypeNode(e2, r2, i2) : void 0; - } else if (e2.kind === "NullValue") { - return null; - } else if (r2.kind === "ListType") { - if (e2.kind === "ListValue") { - var n3 = []; - for (var t2 = 0, a2 = e2.values; t2 < a2.length; t2 += 1) { - var o2 = valueFromTypeNode(a2[t2], r2.type, i2); - if (o2 === void 0) { - return; - } else { - n3.push(o2); - } - } - return n3; - } - } else if (r2.kind === "NamedType") { - switch (r2.name.value) { - case "Int": - case "Float": - case "String": - case "Bool": - return r2.name.value + "Value" === e2.kind ? valueFromASTUntyped(e2, i2) : void 0; - default: - return valueFromASTUntyped(e2, i2); - } - } - }; - exports.visit = function visit(e2, r2) { - var i2 = []; - var n3 = []; - try { - var t2 = function traverse(e3, t3, a2) { - var o2 = false; - var l3 = r2[e3.kind] && r2[e3.kind].enter || r2[e3.kind] || r2.enter; - var u2 = l3 && l3.call(r2, e3, t3, a2, n3, i2); - if (u2 === false) { - return e3; - } else if (u2 === null) { - return null; - } else if (u2 === m) { - throw m; - } else if (u2 && typeof u2.kind == "string") { - o2 = u2 !== e3; - e3 = u2; - } - if (a2) { - i2.push(a2); - } - var v2; - var d2 = { - ...e3 - }; - for (var s3 in e3) { - n3.push(s3); - var c2 = e3[s3]; - if (Array.isArray(c2)) { - var f2 = []; - for (var p2 = 0; p2 < c2.length; p2++) { - if (c2[p2] != null && typeof c2[p2].kind == "string") { - i2.push(e3); - n3.push(p2); - v2 = traverse(c2[p2], p2, c2); - n3.pop(); - i2.pop(); - if (v2 == null) { - o2 = true; - } else { - o2 = o2 || v2 !== c2[p2]; - f2.push(v2); - } - } - } - c2 = f2; - } else if (c2 != null && typeof c2.kind == "string") { - if ((v2 = traverse(c2, s3, e3)) !== void 0) { - o2 = o2 || c2 !== v2; - c2 = v2; - } - } - n3.pop(); - if (o2) { - d2[s3] = c2; - } - } - if (a2) { - i2.pop(); - } - var g2 = r2[e3.kind] && r2[e3.kind].leave || r2.leave; - var h = g2 && g2.call(r2, e3, t3, a2, n3, i2); - if (h === m) { - throw m; - } else if (h !== void 0) { - return h; - } else if (u2 !== void 0) { - return o2 ? d2 : u2; - } else { - return o2 ? d2 : e3; - } - }(e2); - return t2 !== void 0 && t2 !== false ? t2 : e2; - } catch (r3) { - if (r3 !== m) { - throw r3; - } - return e2; - } - }; - } -}); - -// node_modules/wonka/dist/wonka.js -var require_wonka = __commonJS({ - "node_modules/wonka/dist/wonka.js"(exports) { - Object.defineProperty(exports, "__esModule", { - value: true - }); - var teardownPlaceholder = () => { - }; - var e = teardownPlaceholder; - function start2(e2) { - return { - tag: 0, - 0: e2 - }; - } - function push2(e2) { - return { - tag: 1, - 0: e2 - }; - } - var asyncIteratorSymbol = () => typeof Symbol == "function" && Symbol.asyncIterator || "@@asyncIterator"; - var observableSymbol = () => typeof Symbol == "function" && Symbol.observable || "@@observable"; - var identity = (e2) => e2; - function concatMap(r2) { - return (t2) => (i) => { - var s2 = []; - var a = e; - var f = e; - var n2 = false; - var l2 = false; - var o = false; - var u = false; - function applyInnerSource(e2) { - o = true; - e2((e3) => { - if (e3 === 0) { - if (o) { - o = false; - if (s2.length) { - applyInnerSource(r2(s2.shift())); - } else if (u) { - i(0); - } else if (!n2) { - n2 = true; - a(0); - } - } - } else if (e3.tag === 0) { - l2 = false; - (f = e3[0])(0); - } else if (o) { - i(e3); - if (l2) { - l2 = false; - } else { - f(0); - } - } - }); - } - t2((e2) => { - if (u) { - } else if (e2 === 0) { - u = true; - if (!o && !s2.length) { - i(0); - } - } else if (e2.tag === 0) { - a = e2[0]; - } else { - n2 = false; - if (o) { - s2.push(e2[0]); - } else { - applyInnerSource(r2(e2[0])); - } - } - }); - i(start2((e2) => { - if (e2 === 1) { - if (!u) { - u = true; - a(1); - } - if (o) { - o = false; - f(1); - } - } else { - if (!u && !n2) { - n2 = true; - a(0); - } - if (o && !l2) { - l2 = true; - f(0); - } - } - })); - }; - } - function concatAll(e2) { - return concatMap(identity)(e2); - } - function mergeMap(r2) { - return (t2) => (i) => { - var s2 = []; - var a = e; - var f = false; - var n2 = false; - t2((t3) => { - if (n2) { - } else if (t3 === 0) { - n2 = true; - if (!s2.length) { - i(0); - } - } else if (t3.tag === 0) { - a = t3[0]; - } else { - f = false; - !function applyInnerSource(r3) { - var t4 = e; - r3((e2) => { - if (e2 === 0) { - if (s2.length) { - var r4 = s2.indexOf(t4); - if (r4 > -1) { - (s2 = s2.slice()).splice(r4, 1); - } - if (!s2.length) { - if (n2) { - i(0); - } else if (!f) { - f = true; - a(0); - } - } - } - } else if (e2.tag === 0) { - s2.push(t4 = e2[0]); - t4(0); - } else if (s2.length) { - i(e2); - t4(0); - } - }); - }(r2(t3[0])); - if (!f) { - f = true; - a(0); - } - } - }); - i(start2((e2) => { - if (e2 === 1) { - if (!n2) { - n2 = true; - a(1); - } - for (var r3 = 0, t3 = s2, i2 = s2.length; r3 < i2; r3++) { - t3[r3](1); - } - s2.length = 0; - } else { - if (!n2 && !f) { - f = true; - a(0); - } else { - f = false; - } - for (var l2 = 0, o = s2, u = s2.length; l2 < u; l2++) { - o[l2](0); - } - } - })); - }; - } - function mergeAll(e2) { - return mergeMap(identity)(e2); - } - function onPush(e2) { - return (r2) => (t2) => { - var i = false; - r2((r3) => { - if (i) { - } else if (r3 === 0) { - i = true; - t2(0); - } else if (r3.tag === 0) { - var s2 = r3[0]; - t2(start2((e3) => { - if (e3 === 1) { - i = true; - } - s2(e3); - })); - } else { - e2(r3[0]); - t2(r3); - } - }); - }; - } - function share(r2) { - var t2 = []; - var i = e; - var s2 = false; - return (e2) => { - t2.push(e2); - if (t2.length === 1) { - r2((e3) => { - if (e3 === 0) { - for (var r3 = 0, a = t2, f = t2.length; r3 < f; r3++) { - a[r3](0); - } - t2.length = 0; - } else if (e3.tag === 0) { - i = e3[0]; - } else { - s2 = false; - for (var n2 = 0, l2 = t2, o = t2.length; n2 < o; n2++) { - l2[n2](e3); - } - } - }); - } - e2(start2((r3) => { - if (r3 === 1) { - var a = t2.indexOf(e2); - if (a > -1) { - (t2 = t2.slice()).splice(a, 1); - } - if (!t2.length) { - i(1); - } - } else if (!s2) { - s2 = true; - i(0); - } - })); - }; - } - function switchMap(r2) { - return (t2) => (i) => { - var s2 = e; - var a = e; - var f = false; - var n2 = false; - var l2 = false; - var o = false; - t2((t3) => { - if (o) { - } else if (t3 === 0) { - o = true; - if (!l2) { - i(0); - } - } else if (t3.tag === 0) { - s2 = t3[0]; - } else { - if (l2) { - a(1); - a = e; - } - if (!f) { - f = true; - s2(0); - } else { - f = false; - } - !function applyInnerSource(e2) { - l2 = true; - e2((e3) => { - if (!l2) { - } else if (e3 === 0) { - l2 = false; - if (o) { - i(0); - } else if (!f) { - f = true; - s2(0); - } - } else if (e3.tag === 0) { - n2 = false; - (a = e3[0])(0); - } else { - i(e3); - if (!n2) { - a(0); - } else { - n2 = false; - } - } - }); - }(r2(t3[0])); - } - }); - i(start2((e2) => { - if (e2 === 1) { - if (!o) { - o = true; - s2(1); - } - if (l2) { - l2 = false; - a(1); - } - } else { - if (!o && !f) { - f = true; - s2(0); - } - if (l2 && !n2) { - n2 = true; - a(0); - } - } - })); - }; - } - function fromAsyncIterable(e2) { - return (r2) => { - var t2 = e2[asyncIteratorSymbol()] && e2[asyncIteratorSymbol()]() || e2; - var i = false; - var s2 = false; - var a = false; - var f; - r2(start2(async (e3) => { - if (e3 === 1) { - i = true; - if (t2.return) { - t2.return(); - } - } else if (s2) { - a = true; - } else { - for (a = s2 = true; a && !i; ) { - if ((f = await t2.next()).done) { - i = true; - if (t2.return) { - await t2.return(); - } - r2(0); - } else { - try { - a = false; - r2(push2(f.value)); - } catch (e4) { - if (t2.throw) { - if (i = !!(await t2.throw(e4)).done) { - r2(0); - } - } else { - throw e4; - } - } - } - } - s2 = false; - } - })); - }; - } - function fromIterable(e2) { - if (e2[Symbol.asyncIterator]) { - return fromAsyncIterable(e2); - } - return (r2) => { - var t2 = e2[Symbol.iterator](); - var i = false; - var s2 = false; - var a = false; - var f; - r2(start2((e3) => { - if (e3 === 1) { - i = true; - if (t2.return) { - t2.return(); - } - } else if (s2) { - a = true; - } else { - for (a = s2 = true; a && !i; ) { - if ((f = t2.next()).done) { - i = true; - if (t2.return) { - t2.return(); - } - r2(0); - } else { - try { - a = false; - r2(push2(f.value)); - } catch (e4) { - if (t2.throw) { - if (i = !!t2.throw(e4).done) { - r2(0); - } - } else { - throw e4; - } - } - } - } - s2 = false; - } - })); - }; - } - var r = fromIterable; - function make(e2) { - return (r2) => { - var t2 = false; - var i = e2({ - next(e3) { - if (!t2) { - r2(push2(e3)); - } - }, - complete() { - if (!t2) { - t2 = true; - r2(0); - } - } - }); - r2(start2((e3) => { - if (e3 === 1 && !t2) { - t2 = true; - i(); - } - })); - }; - } - function subscribe(r2) { - return (t2) => { - var i = e; - var s2 = false; - t2((e2) => { - if (e2 === 0) { - s2 = true; - } else if (e2.tag === 0) { - (i = e2[0])(0); - } else if (!s2) { - r2(e2[0]); - i(0); - } - }); - return { - unsubscribe() { - if (!s2) { - s2 = true; - i(1); - } - } - }; - }; - } - var t = { - done: true - }; - function zip(r2) { - var t2 = Object.keys(r2).length; - return (i) => { - var s2 = /* @__PURE__ */ new Set(); - var a = Array.isArray(r2) ? new Array(t2).fill(e) : {}; - var f = Array.isArray(r2) ? new Array(t2) : {}; - var n2 = false; - var l2 = false; - var o = false; - var u = 0; - var loop = function(v2) { - r2[v2]((c) => { - if (c === 0) { - if (u >= t2 - 1) { - o = true; - i(0); - } else { - u++; - } - } else if (c.tag === 0) { - a[v2] = c[0]; - } else if (!o) { - f[v2] = c[0]; - s2.add(v2); - if (!n2 && s2.size < t2) { - if (!l2) { - for (var p in r2) { - if (!s2.has(p)) { - (a[p] || e)(0); - } - } - } else { - l2 = false; - } - } else { - n2 = true; - l2 = false; - i(push2(Array.isArray(f) ? f.slice() : { - ...f - })); - } - } - }); - }; - for (var v in r2) { - loop(v); - } - i(start2((e2) => { - if (o) { - } else if (e2 === 1) { - o = true; - for (var r3 in a) { - a[r3](1); - } - } else if (!l2) { - l2 = true; - for (var t3 in a) { - a[t3](0); - } - } - })); - }; - } - exports.buffer = function buffer(r2) { - return (t2) => (i) => { - var s2 = []; - var a = e; - var f = e; - var n2 = false; - var l2 = false; - t2((e2) => { - if (l2) { - } else if (e2 === 0) { - l2 = true; - f(1); - if (s2.length) { - i(push2(s2)); - } - i(0); - } else if (e2.tag === 0) { - a = e2[0]; - r2((e3) => { - if (l2) { - } else if (e3 === 0) { - l2 = true; - a(1); - if (s2.length) { - i(push2(s2)); - } - i(0); - } else if (e3.tag === 0) { - f = e3[0]; - } else if (s2.length) { - var r3 = push2(s2); - s2 = []; - i(r3); - } - }); - } else { - s2.push(e2[0]); - if (!n2) { - n2 = true; - a(0); - f(0); - } else { - n2 = false; - } - } - }); - i(start2((e2) => { - if (e2 === 1 && !l2) { - l2 = true; - a(1); - f(1); - } else if (!l2 && !n2) { - n2 = true; - a(0); - f(0); - } - })); - }; - }; - exports.combine = function combine(...e2) { - return zip(e2); - }; - exports.concat = function concat(e2) { - return concatAll(r(e2)); - }; - exports.concatAll = concatAll; - exports.concatMap = concatMap; - exports.debounce = function debounce2(e2) { - return (r2) => (t2) => { - var i; - var s2 = false; - var a = false; - r2((r3) => { - if (a) { - } else if (r3 === 0) { - a = true; - if (i) { - s2 = true; - } else { - t2(0); - } - } else if (r3.tag === 0) { - var f = r3[0]; - t2(start2((e3) => { - if (e3 === 1 && !a) { - a = true; - s2 = false; - if (i) { - clearTimeout(i); - } - f(1); - } else if (!a) { - f(0); - } - })); - } else { - if (i) { - clearTimeout(i); - } - i = setTimeout(() => { - i = void 0; - t2(r3); - if (s2) { - t2(0); - } - }, e2(r3[0])); - } - }); - }; - }; - exports.delay = function delay(e2) { - return (r2) => (t2) => { - var i = 0; - r2((r3) => { - if (r3 !== 0 && r3.tag === 0) { - t2(r3); - } else { - i++; - setTimeout(() => { - if (i) { - i--; - t2(r3); - } - }, e2); - } - }); - }; - }; - exports.empty = (e2) => { - var r2 = false; - e2(start2((t2) => { - if (t2 === 1) { - r2 = true; - } else if (!r2) { - r2 = true; - e2(0); - } - })); - }; - exports.filter = function filter(r2) { - return (t2) => (i) => { - var s2 = e; - t2((e2) => { - if (e2 === 0) { - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - i(e2); - } else if (!r2(e2[0])) { - s2(0); - } else { - i(e2); - } - }); - }; - }; - exports.flatten = mergeAll; - exports.forEach = function forEach(e2) { - return (r2) => { - subscribe(e2)(r2); - }; - }; - exports.fromArray = r; - exports.fromAsyncIterable = fromAsyncIterable; - exports.fromCallbag = function fromCallbag(e2) { - return (r2) => { - e2(0, (e3, t2) => { - if (e3 === 0) { - r2(start2((e4) => { - t2(e4 + 1); - })); - } else if (e3 === 1) { - r2(push2(t2)); - } else { - r2(0); - } - }); - }; - }; - exports.fromDomEvent = function fromDomEvent(e2, r2) { - return make((t2) => { - e2.addEventListener(r2, t2.next); - return () => e2.removeEventListener(r2, t2.next); - }); - }; - exports.fromIterable = fromIterable; - exports.fromObservable = function fromObservable(e2) { - return (r2) => { - var t2 = (e2[observableSymbol()] ? e2[observableSymbol()]() : e2).subscribe({ - next(e3) { - r2(push2(e3)); - }, - complete() { - r2(0); - }, - error(e3) { - throw e3; - } - }); - r2(start2((e3) => { - if (e3 === 1) { - t2.unsubscribe(); - } - })); - }; - }; - exports.fromPromise = function fromPromise(e2) { - return make((r2) => { - e2.then((e3) => { - Promise.resolve(e3).then(() => { - r2.next(e3); - r2.complete(); - }); - }); - return teardownPlaceholder; - }); - }; - exports.fromValue = function fromValue(e2) { - return (r2) => { - var t2 = false; - r2(start2((i) => { - if (i === 1) { - t2 = true; - } else if (!t2) { - t2 = true; - r2(push2(e2)); - r2(0); - } - })); - }; - }; - exports.interval = function interval(e2) { - return make((r2) => { - var t2 = 0; - var i = setInterval(() => r2.next(t2++), e2); - return () => clearInterval(i); - }); - }; - exports.lazy = function lazy(e2) { - return (r2) => e2()(r2); - }; - exports.make = make; - exports.makeSubject = function makeSubject() { - var e2; - var r2; - return { - source: share(make((t2) => { - e2 = t2.next; - r2 = t2.complete; - return teardownPlaceholder; - })), - next(r3) { - if (e2) { - e2(r3); - } - }, - complete() { - if (r2) { - r2(); - } - } - }; - }; - exports.map = function map(e2) { - return (r2) => (t2) => r2((r3) => { - if (r3 === 0 || r3.tag === 0) { - t2(r3); - } else { - t2(push2(e2(r3[0]))); - } - }); - }; - exports.merge = function merge(e2) { - return mergeAll(r(e2)); - }; - exports.mergeAll = mergeAll; - exports.mergeMap = mergeMap; - exports.never = (r2) => { - r2(start2(e)); - }; - exports.onEnd = function onEnd(e2) { - return (r2) => (t2) => { - var i = false; - r2((r3) => { - if (i) { - } else if (r3 === 0) { - i = true; - t2(0); - e2(); - } else if (r3.tag === 0) { - var s2 = r3[0]; - t2(start2((r4) => { - if (r4 === 1) { - i = true; - s2(1); - e2(); - } else { - s2(r4); - } - })); - } else { - t2(r3); - } - }); - }; - }; - exports.onPush = onPush; - exports.onStart = function onStart(e2) { - return (r2) => (t2) => r2((r3) => { - if (r3 === 0) { - t2(0); - } else if (r3.tag === 0) { - t2(r3); - e2(); - } else { - t2(r3); - } - }); - }; - exports.pipe = (...e2) => { - var r2 = e2[0]; - for (var t2 = 1, i = e2.length; t2 < i; t2++) { - r2 = e2[t2](r2); - } - return r2; - }; - exports.publish = function publish(e2) { - subscribe((e3) => { - })(e2); - }; - exports.sample = function sample(r2) { - return (t2) => (i) => { - var s2 = e; - var a = e; - var f; - var n2 = false; - var l2 = false; - t2((e2) => { - if (l2) { - } else if (e2 === 0) { - l2 = true; - a(1); - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - } else { - f = e2[0]; - if (!n2) { - n2 = true; - a(0); - s2(0); - } else { - n2 = false; - } - } - }); - r2((e2) => { - if (l2) { - } else if (e2 === 0) { - l2 = true; - s2(1); - i(0); - } else if (e2.tag === 0) { - a = e2[0]; - } else if (f !== void 0) { - var r3 = push2(f); - f = void 0; - i(r3); - } - }); - i(start2((e2) => { - if (e2 === 1 && !l2) { - l2 = true; - s2(1); - a(1); - } else if (!l2 && !n2) { - n2 = true; - s2(0); - a(0); - } - })); - }; - }; - exports.scan = function scan2(e2, r2) { - return (t2) => (i) => { - var s2 = r2; - t2((r3) => { - if (r3 === 0) { - i(0); - } else if (r3.tag === 0) { - i(r3); - } else { - i(push2(s2 = e2(s2, r3[0]))); - } - }); - }; - }; - exports.share = share; - exports.skip = function skip(r2) { - return (t2) => (i) => { - var s2 = e; - var a = r2; - t2((e2) => { - if (e2 === 0) { - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - i(e2); - } else if (a-- > 0) { - s2(0); - } else { - i(e2); - } - }); - }; - }; - exports.skipUntil = function skipUntil(r2) { - return (t2) => (i) => { - var s2 = e; - var a = e; - var f = true; - var n2 = false; - var l2 = false; - t2((e2) => { - if (l2) { - } else if (e2 === 0) { - l2 = true; - if (f) { - a(1); - } - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - r2((e3) => { - if (e3 === 0) { - if (f) { - l2 = true; - s2(1); - } - } else if (e3.tag === 0) { - (a = e3[0])(0); - } else { - f = false; - a(1); - } - }); - } else if (!f) { - n2 = false; - i(e2); - } else if (!n2) { - n2 = true; - s2(0); - a(0); - } else { - n2 = false; - } - }); - i(start2((e2) => { - if (e2 === 1 && !l2) { - l2 = true; - s2(1); - if (f) { - a(1); - } - } else if (!l2 && !n2) { - n2 = true; - if (f) { - a(0); - } - s2(0); - } - })); - }; - }; - exports.skipWhile = function skipWhile(r2) { - return (t2) => (i) => { - var s2 = e; - var a = true; - t2((e2) => { - if (e2 === 0) { - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - i(e2); - } else if (a) { - if (r2(e2[0])) { - s2(0); - } else { - a = false; - i(e2); - } - } else { - i(e2); - } - }); - }; - }; - exports.subscribe = subscribe; - exports.switchAll = function switchAll(e2) { - return switchMap(identity)(e2); - }; - exports.switchMap = switchMap; - exports.take = function take(r2) { - return (t2) => (i) => { - var s2 = e; - var a = false; - var f = 0; - t2((e2) => { - if (a) { - } else if (e2 === 0) { - a = true; - i(0); - } else if (e2.tag === 0) { - if (r2 <= 0) { - a = true; - i(0); - e2[0](1); - } else { - s2 = e2[0]; - } - } else if (f++ < r2) { - i(e2); - if (!a && f >= r2) { - a = true; - i(0); - s2(1); - } - } else { - i(e2); - } - }); - i(start2((e2) => { - if (e2 === 1 && !a) { - a = true; - s2(1); - } else if (e2 === 0 && !a && f < r2) { - s2(0); - } - })); - }; - }; - exports.takeLast = function takeLast(t2) { - return (i) => (s2) => { - var a = []; - var f = e; - i((e2) => { - if (e2 === 0) { - r(a)(s2); - } else if (e2.tag === 0) { - if (t2 <= 0) { - e2[0](1); - r(a)(s2); - } else { - (f = e2[0])(0); - } - } else { - if (a.length >= t2 && t2) { - a.shift(); - } - a.push(e2[0]); - f(0); - } - }); - }; - }; - exports.takeUntil = function takeUntil(r2) { - return (t2) => (i) => { - var s2 = e; - var a = e; - var f = false; - t2((e2) => { - if (f) { - } else if (e2 === 0) { - f = true; - a(1); - i(0); - } else if (e2.tag === 0) { - s2 = e2[0]; - r2((e3) => { - if (e3 === 0) { - } else if (e3.tag === 0) { - (a = e3[0])(0); - } else { - f = true; - a(1); - s2(1); - i(0); - } - }); - } else { - i(e2); - } - }); - i(start2((e2) => { - if (e2 === 1 && !f) { - f = true; - s2(1); - a(1); - } else if (!f) { - s2(0); - } - })); - }; - }; - exports.takeWhile = function takeWhile(r2, t2) { - return (i) => (s2) => { - var a = e; - var f = false; - i((e2) => { - if (f) { - } else if (e2 === 0) { - f = true; - s2(0); - } else if (e2.tag === 0) { - a = e2[0]; - s2(e2); - } else if (!r2(e2[0])) { - f = true; - if (t2) { - s2(e2); - } - s2(0); - a(1); - } else { - s2(e2); - } - }); - }; - }; - exports.tap = onPush; - exports.throttle = function throttle(e2) { - return (r2) => (t2) => { - var i = false; - var s2; - r2((r3) => { - if (r3 === 0) { - if (s2) { - clearTimeout(s2); - } - t2(0); - } else if (r3.tag === 0) { - var a = r3[0]; - t2(start2((e3) => { - if (e3 === 1) { - if (s2) { - clearTimeout(s2); - } - a(1); - } else { - a(0); - } - })); - } else if (!i) { - i = true; - if (s2) { - clearTimeout(s2); - } - s2 = setTimeout(() => { - s2 = void 0; - i = false; - }, e2(r3[0])); - t2(r3); - } - }); - }; - }; - exports.toArray = function toArray(r2) { - var t2 = []; - var i = e; - var s2 = false; - r2((e2) => { - if (e2 === 0) { - s2 = true; - } else if (e2.tag === 0) { - (i = e2[0])(0); - } else { - t2.push(e2[0]); - i(0); - } - }); - if (!s2) { - i(1); - } - return t2; - }; - exports.toAsyncIterable = (r2) => { - var i = []; - var s2 = false; - var a = false; - var f = false; - var n2 = e; - var l2; - return { - async next() { - if (!a) { - a = true; - r2((e2) => { - if (s2) { - } else if (e2 === 0) { - if (l2) { - l2 = l2(t); - } - s2 = true; - } else if (e2.tag === 0) { - f = true; - (n2 = e2[0])(0); - } else { - f = false; - if (l2) { - l2 = l2({ - value: e2[0], - done: false - }); - } else { - i.push(e2[0]); - } - } - }); - } - if (s2 && !i.length) { - return t; - } else if (!s2 && !f && i.length <= 1) { - f = true; - n2(0); - } - return i.length ? { - value: i.shift(), - done: false - } : new Promise((e2) => l2 = e2); - }, - async return() { - if (!s2) { - l2 = n2(1); - } - s2 = true; - return t; - }, - [asyncIteratorSymbol()]() { - return this; - } - }; - }; - exports.toCallbag = function toCallbag(e2) { - return (r2, t2) => { - if (r2 === 0) { - e2((e3) => { - if (e3 === 0) { - t2(2); - } else if (e3.tag === 0) { - t2(0, (r3) => { - if (r3 < 3) { - e3[0](r3 - 1); - } - }); - } else { - t2(1, e3[0]); - } - }); - } - }; - }; - exports.toObservable = function toObservable(r2) { - return { - subscribe(t2, i, s2) { - var a = typeof t2 == "object" ? t2 : { - next: t2, - error: i, - complete: s2 - }; - var f = e; - var n2 = false; - r2((e2) => { - if (n2) { - } else if (e2 === 0) { - n2 = true; - if (a.complete) { - a.complete(); - } - } else if (e2.tag === 0) { - (f = e2[0])(0); - } else { - a.next(e2[0]); - f(0); - } - }); - var l2 = { - closed: false, - unsubscribe() { - l2.closed = true; - n2 = true; - f(1); - } - }; - return l2; - }, - [observableSymbol()]() { - return this; - } - }; - }; - exports.toPromise = function toPromise(r2) { - return new Promise((t2) => { - var i = e; - var s2; - r2((e2) => { - if (e2 === 0) { - Promise.resolve(s2).then(t2); - } else if (e2.tag === 0) { - (i = e2[0])(0); - } else { - s2 = e2[0]; - i(0); - } - }); - }); - }; - exports.zip = zip; - } -}); - -// node_modules/@urql/core/dist/urql-core-chunk.js -var require_urql_core_chunk = __commonJS({ - "node_modules/@urql/core/dist/urql-core-chunk.js"(exports) { - var graphql_web = require_graphql_web(); - var wonka = require_wonka(); - var generateErrorMessage = (networkErr, graphQlErrs) => { - var error = ""; - if (networkErr) - return `[Network] ${networkErr.message}`; - if (graphQlErrs) { - for (var err of graphQlErrs) { - if (error) - error += "\n"; - error += `[GraphQL] ${err.message}`; - } - } - return error; - }; - var rehydrateGraphQlError = (error) => { - if (error && error.message && (error.extensions || error.name === "GraphQLError")) { - return error; - } else if (typeof error === "object" && error.message) { - return new graphql_web.GraphQLError(error.message, error.nodes, error.source, error.positions, error.path, error, error.extensions || {}); - } else { - return new graphql_web.GraphQLError(error); - } - }; - var CombinedError = class extends Error { - constructor(input) { - var normalizedGraphQLErrors = (input.graphQLErrors || []).map(rehydrateGraphQlError); - var message = generateErrorMessage(input.networkError, normalizedGraphQLErrors); - super(message); - this.name = "CombinedError"; - this.message = message; - this.graphQLErrors = normalizedGraphQLErrors; - this.networkError = input.networkError; - this.response = input.response; - } - toString() { - return this.message; - } - }; - var phash = (x, seed) => { - var h = (seed || 5381) | 0; - for (var i = 0, l2 = x.length | 0; i < l2; i++) - h = (h << 5) + h + x.charCodeAt(i); - return h; - }; - var seen = /* @__PURE__ */ new Set(); - var cache = /* @__PURE__ */ new WeakMap(); - var stringify = (x) => { - if (x === null || seen.has(x)) { - return "null"; - } else if (typeof x !== "object") { - return JSON.stringify(x) || ""; - } else if (x.toJSON) { - return stringify(x.toJSON()); - } else if (Array.isArray(x)) { - var _out = "["; - for (var value of x) { - if (_out.length > 1) - _out += ","; - _out += stringify(value) || "null"; - } - _out += "]"; - return _out; - } else if (FileConstructor !== NoopConstructor && x instanceof FileConstructor || BlobConstructor !== NoopConstructor && x instanceof BlobConstructor) { - return "null"; - } - var keys = Object.keys(x).sort(); - if (!keys.length && x.constructor && Object.getPrototypeOf(x).constructor !== Object.prototype.constructor) { - var key = cache.get(x) || Math.random().toString(36).slice(2); - cache.set(x, key); - return stringify({ - __key: key - }); - } - seen.add(x); - var out = "{"; - for (var _key of keys) { - var _value = stringify(x[_key]); - if (_value) { - if (out.length > 1) - out += ","; - out += stringify(_key) + ":" + _value; - } - } - seen.delete(x); - out += "}"; - return out; - }; - var extract = (map, path, x) => { - if (x == null || typeof x !== "object" || x.toJSON || seen.has(x)) - ; - else if (Array.isArray(x)) { - for (var i = 0, l2 = x.length; i < l2; i++) - extract(map, `${path}.${i}`, x[i]); - } else if (x instanceof FileConstructor || x instanceof BlobConstructor) { - map.set(path, x); - } else { - seen.add(x); - for (var key of Object.keys(x)) - extract(map, `${path}.${key}`, x[key]); - } - }; - var stringifyVariables = (x) => { - seen.clear(); - return stringify(x); - }; - var NoopConstructor = class { - }; - var FileConstructor = typeof File !== "undefined" ? File : NoopConstructor; - var BlobConstructor = typeof Blob !== "undefined" ? Blob : NoopConstructor; - var extractFiles = (x) => { - var map = /* @__PURE__ */ new Map(); - if (FileConstructor !== NoopConstructor || BlobConstructor !== NoopConstructor) { - seen.clear(); - extract(map, "variables", x); - } - return map; - }; - var SOURCE_NAME = "gql"; - var GRAPHQL_STRING_RE = /("{3}[\s\S]*"{3}|"(?:\\.|[^"])*")/g; - var REPLACE_CHAR_RE = /(?:#[^\n\r]+)?(?:[\r\n]+|$)/g; - var replaceOutsideStrings = (str, idx) => idx % 2 === 0 ? str.replace(REPLACE_CHAR_RE, "\n") : str; - var sanitizeDocument = (node) => node.split(GRAPHQL_STRING_RE).map(replaceOutsideStrings).join("").trim(); - var prints = /* @__PURE__ */ new Map(); - var docs = /* @__PURE__ */ new Map(); - var stringifyDocument = (node) => { - var printed; - if (typeof node === "string") { - printed = sanitizeDocument(node); - } else if (node.loc && docs.get(node.__key) === node) { - printed = node.loc.source.body; - } else { - printed = prints.get(node) || sanitizeDocument(graphql_web.print(node)); - prints.set(node, printed); - } - if (typeof node !== "string" && !node.loc) { - node.loc = { - start: 0, - end: printed.length, - source: { - body: printed, - name: SOURCE_NAME, - locationOffset: { - line: 1, - column: 1 - } - } - }; - } - return printed; - }; - var hashDocument = (node) => { - var key = phash(stringifyDocument(node)); - if (node.definitions) { - var operationName = getOperationName(node); - if (operationName) - key = phash(` -# ${operationName}`, key); - } - return key; - }; - var keyDocument = (node) => { - var key; - var query; - if (typeof node === "string") { - key = hashDocument(node); - query = docs.get(key) || graphql_web.parse(node, { - noLocation: true - }); - } else { - key = node.__key || hashDocument(node); - query = docs.get(key) || node; - } - if (!query.loc) - stringifyDocument(query); - query.__key = key; - docs.set(key, query); - return query; - }; - var createRequest = (_query, _variables, extensions) => { - var variables = _variables || {}; - var query = keyDocument(_query); - var printedVars = stringifyVariables(variables); - var key = query.__key; - if (printedVars !== "{}") - key = phash(printedVars, key); - return { - key, - query, - variables, - extensions - }; - }; - var getOperationName = (query) => { - for (var node of query.definitions) { - if (node.kind === graphql_web.Kind.OPERATION_DEFINITION) { - return node.name ? node.name.value : void 0; - } - } - }; - var getOperationType = (query) => { - for (var node of query.definitions) { - if (node.kind === graphql_web.Kind.OPERATION_DEFINITION) { - return node.operation; - } - } - }; - var makeResult = (operation, result, response) => { - if (!("data" in result) && (!("errors" in result) || !Array.isArray(result.errors))) { - throw new Error("No Content"); - } - var defaultHasNext = operation.kind === "subscription"; - return { - operation, - data: result.data, - error: Array.isArray(result.errors) ? new CombinedError({ - graphQLErrors: result.errors, - response - }) : void 0, - extensions: result.extensions ? { - ...result.extensions - } : void 0, - hasNext: result.hasNext == null ? defaultHasNext : result.hasNext, - stale: false - }; - }; - var deepMerge = (target, source) => { - if (typeof target === "object" && target != null) { - if (!target.constructor || target.constructor === Object || Array.isArray(target)) { - target = Array.isArray(target) ? [...target] : { - ...target - }; - for (var key of Object.keys(source)) - target[key] = deepMerge(target[key], source[key]); - return target; - } - } - return source; - }; - var mergeResultPatch = (prevResult, nextResult, response, pending) => { - var errors = prevResult.error ? prevResult.error.graphQLErrors : []; - var hasExtensions = !!prevResult.extensions || !!(nextResult.payload || nextResult).extensions; - var extensions = { - ...prevResult.extensions, - ...(nextResult.payload || nextResult).extensions - }; - var incremental = nextResult.incremental; - if ("path" in nextResult) { - incremental = [nextResult]; - } - var withData = { - data: prevResult.data - }; - if (incremental) { - var _loop = function(patch2) { - if (Array.isArray(patch2.errors)) { - errors.push(...patch2.errors); - } - if (patch2.extensions) { - Object.assign(extensions, patch2.extensions); - hasExtensions = true; - } - var prop = "data"; - var part = withData; - var path = []; - if (patch2.path) { - path = patch2.path; - } else if (pending) { - var res = pending.find((pendingRes) => pendingRes.id === patch2.id); - if (patch2.subPath) { - path = [...res.path, ...patch2.subPath]; - } else { - path = res.path; - } - } - for (var i = 0, l2 = path.length; i < l2; prop = path[i++]) { - part = part[prop] = Array.isArray(part[prop]) ? [...part[prop]] : { - ...part[prop] - }; - } - if (patch2.items) { - var startIndex = +prop >= 0 ? prop : 0; - for (var _i = 0, _l = patch2.items.length; _i < _l; _i++) - part[startIndex + _i] = deepMerge(part[startIndex + _i], patch2.items[_i]); - } else if (patch2.data !== void 0) { - part[prop] = deepMerge(part[prop], patch2.data); - } - }; - for (var patch of incremental) { - _loop(patch); - } - } else { - withData.data = (nextResult.payload || nextResult).data || prevResult.data; - errors = nextResult.errors || nextResult.payload && nextResult.payload.errors || errors; - } - return { - operation: prevResult.operation, - data: withData.data, - error: errors.length ? new CombinedError({ - graphQLErrors: errors, - response - }) : void 0, - extensions: hasExtensions ? extensions : void 0, - hasNext: nextResult.hasNext != null ? nextResult.hasNext : prevResult.hasNext, - stale: false - }; - }; - var makeErrorResult = (operation, error, response) => ({ - operation, - data: void 0, - error: new CombinedError({ - networkError: error, - response - }), - extensions: void 0, - hasNext: false, - stale: false - }); - function makeFetchBody(request) { - var body = { - query: void 0, - documentId: void 0, - operationName: getOperationName(request.query), - variables: request.variables || void 0, - extensions: request.extensions - }; - if ("documentId" in request.query && request.query.documentId && (!request.query.definitions || !request.query.definitions.length)) { - body.documentId = request.query.documentId; - } else if (!request.extensions || !request.extensions.persistedQuery || !!request.extensions.persistedQuery.miss) { - body.query = stringifyDocument(request.query); - } - return body; - } - var makeFetchURL = (operation, body) => { - var useGETMethod = operation.kind === "query" && operation.context.preferGetMethod; - if (!useGETMethod || !body) - return operation.context.url; - var urlParts = splitOutSearchParams(operation.context.url); - for (var key in body) { - var value = body[key]; - if (value) { - urlParts[1].set(key, typeof value === "object" ? stringifyVariables(value) : value); - } - } - var finalUrl = urlParts.join("?"); - if (finalUrl.length > 2047 && useGETMethod !== "force") { - operation.context.preferGetMethod = false; - return operation.context.url; - } - return finalUrl; - }; - var splitOutSearchParams = (url) => { - var start2 = url.indexOf("?"); - return start2 > -1 ? [url.slice(0, start2), new URLSearchParams(url.slice(start2 + 1))] : [url, new URLSearchParams()]; - }; - var serializeBody = (operation, body) => { - var omitBody = operation.kind === "query" && !!operation.context.preferGetMethod; - if (body && !omitBody) { - var json = stringifyVariables(body); - var files = extractFiles(body.variables); - if (files.size) { - var form = new FormData(); - form.append("operations", json); - form.append("map", stringifyVariables({ - ...[...files.keys()].map((value) => [value]) - })); - var index = 0; - for (var file of files.values()) - form.append(`${index++}`, file); - return form; - } - return json; - } - }; - var isHeaders = (headers) => "has" in headers && !Object.keys(headers).length; - var makeFetchOptions = (operation, body) => { - var headers = { - accept: operation.kind === "subscription" ? "text/event-stream, multipart/mixed" : "application/graphql-response+json, application/graphql+json, application/json, text/event-stream, multipart/mixed" - }; - var extraOptions = (typeof operation.context.fetchOptions === "function" ? operation.context.fetchOptions() : operation.context.fetchOptions) || {}; - if (extraOptions.headers) { - if (isHeaders(extraOptions.headers)) { - extraOptions.headers.forEach((value, key2) => { - headers[key2] = value; - }); - } else if (Array.isArray(extraOptions.headers)) { - extraOptions.headers.forEach((value, key2) => { - if (Array.isArray(value)) { - if (headers[value[0]]) { - headers[value[0]] = `${headers[value[0]]},${value[1]}`; - } else { - headers[value[0]] = value[1]; - } - } else { - headers[key2] = value; - } - }); - } else { - for (var key in extraOptions.headers) { - headers[key.toLowerCase()] = extraOptions.headers[key]; - } - } - } - var serializedBody = serializeBody(operation, body); - if (typeof serializedBody === "string" && !headers["content-type"]) - headers["content-type"] = "application/json"; - return { - ...extraOptions, - method: serializedBody ? "POST" : "GET", - body: serializedBody, - headers - }; - }; - var decoder = typeof TextDecoder !== "undefined" ? new TextDecoder() : null; - var boundaryHeaderRe = /boundary="?([^=";]+)"?/i; - var eventStreamRe = /data: ?([^\n]+)/; - var toString = (input) => input.constructor.name === "Buffer" ? input.toString() : decoder.decode(input); - async function* streamBody(response) { - if (response.body[Symbol.asyncIterator]) { - for await (var chunk of response.body) - yield toString(chunk); - } else { - var reader = response.body.getReader(); - var result; - try { - while (!(result = await reader.read()).done) - yield toString(result.value); - } finally { - reader.cancel(); - } - } - } - async function* split(chunks, boundary) { - var buffer = ""; - var boundaryIndex; - for await (var chunk of chunks) { - buffer += chunk; - while ((boundaryIndex = buffer.indexOf(boundary)) > -1) { - yield buffer.slice(0, boundaryIndex); - buffer = buffer.slice(boundaryIndex + boundary.length); - } - } - } - async function* parseJSON(response) { - yield JSON.parse(await response.text()); - } - async function* parseEventStream(response) { - var payload; - for await (var chunk of split(streamBody(response), "\n\n")) { - var match3 = chunk.match(eventStreamRe); - if (match3) { - var _chunk = match3[1]; - try { - yield payload = JSON.parse(_chunk); - } catch (error) { - if (!payload) - throw error; - } - if (payload && payload.hasNext === false) - break; - } - } - if (payload && payload.hasNext !== false) { - yield { - hasNext: false - }; - } - } - async function* parseMultipartMixed(contentType, response) { - var boundaryHeader = contentType.match(boundaryHeaderRe); - var boundary = "--" + (boundaryHeader ? boundaryHeader[1] : "-"); - var isPreamble = true; - var payload; - for await (var chunk of split(streamBody(response), "\r\n" + boundary)) { - if (isPreamble) { - isPreamble = false; - var preambleIndex = chunk.indexOf(boundary); - if (preambleIndex > -1) { - chunk = chunk.slice(preambleIndex + boundary.length); - } else { - continue; - } - } - try { - yield payload = JSON.parse(chunk.slice(chunk.indexOf("\r\n\r\n") + 4)); - } catch (error) { - if (!payload) - throw error; - } - if (payload && payload.hasNext === false) - break; - } - if (payload && payload.hasNext !== false) { - yield { - hasNext: false - }; - } - } - async function* parseMaybeJSON(response) { - var text = await response.text(); - try { - var result = JSON.parse(text); - if (true) { - console.warn(`Found response with content-type "text/plain" but it had a valid "application/json" response.`); - } - yield result; - } catch (e) { - throw new Error(text); - } - } - async function* fetchOperation(operation, url, fetchOptions) { - var networkMode = true; - var result = null; - var response; - try { - yield await Promise.resolve(); - response = await (operation.context.fetch || fetch)(url, fetchOptions); - var contentType = response.headers.get("Content-Type") || ""; - var results; - if (/multipart\/mixed/i.test(contentType)) { - results = parseMultipartMixed(contentType, response); - } else if (/text\/event-stream/i.test(contentType)) { - results = parseEventStream(response); - } else if (!/text\//i.test(contentType)) { - results = parseJSON(response); - } else { - results = parseMaybeJSON(response); - } - var pending; - for await (var payload of results) { - if (payload.pending && !result) { - pending = payload.pending; - } else if (payload.pending) { - pending = [...pending, ...payload.pending]; - } - result = result ? mergeResultPatch(result, payload, response, pending) : makeResult(operation, payload, response); - networkMode = false; - yield result; - networkMode = true; - } - if (!result) { - yield result = makeResult(operation, {}, response); - } - } catch (error) { - if (!networkMode) { - throw error; - } - yield makeErrorResult(operation, response && (response.status < 200 || response.status >= 300) && response.statusText ? new Error(response.statusText) : error, response); - } - } - function makeFetchSource(operation, url, fetchOptions) { - var abortController; - if (typeof AbortController !== "undefined") { - fetchOptions.signal = (abortController = new AbortController()).signal; - } - return wonka.onEnd(() => { - if (abortController) - abortController.abort(); - })(wonka.filter((result) => !!result)(wonka.fromAsyncIterable(fetchOperation(operation, url, fetchOptions)))); - } - exports.CombinedError = CombinedError; - exports.createRequest = createRequest; - exports.getOperationType = getOperationType; - exports.keyDocument = keyDocument; - exports.makeErrorResult = makeErrorResult; - exports.makeFetchBody = makeFetchBody; - exports.makeFetchOptions = makeFetchOptions; - exports.makeFetchSource = makeFetchSource; - exports.makeFetchURL = makeFetchURL; - exports.makeResult = makeResult; - exports.mergeResultPatch = mergeResultPatch; - exports.stringifyDocument = stringifyDocument; - exports.stringifyVariables = stringifyVariables; - } -}); - -// node_modules/@urql/core/dist/urql-core.js -var require_urql_core = __commonJS({ - "node_modules/@urql/core/dist/urql-core.js"(exports) { - Object.defineProperty(exports, "__esModule", { value: true }); - var graphql_web = require_graphql_web(); - var fetchSource = require_urql_core_chunk(); - var wonka = require_wonka(); - var collectTypes = (obj, types) => { - if (Array.isArray(obj)) { - for (var item of obj) - collectTypes(item, types); - } else if (typeof obj === "object" && obj !== null) { - for (var _key in obj) { - if (_key === "__typename" && typeof obj[_key] === "string") { - types.add(obj[_key]); - } else { - collectTypes(obj[_key], types); - } - } - } - return types; - }; - var collectTypenames = (response) => [...collectTypes(response, /* @__PURE__ */ new Set())]; - var formatNode = (node) => { - if ("definitions" in node) { - var definitions = []; - for (var definition of node.definitions) { - var newDefinition = formatNode(definition); - definitions.push(newDefinition); - } - return { - ...node, - definitions - }; - } - if ("directives" in node && node.directives && node.directives.length) { - var directives = []; - var _directives = {}; - for (var directive of node.directives) { - var name = directive.name.value; - if (name[0] !== "_") { - directives.push(directive); - } else { - name = name.slice(1); - } - _directives[name] = directive; - } - node = { - ...node, - directives, - _directives - }; - } - if ("selectionSet" in node) { - var selections = []; - var hasTypename = node.kind === graphql_web.Kind.OPERATION_DEFINITION; - if (node.selectionSet) { - for (var selection of node.selectionSet.selections || []) { - hasTypename = hasTypename || selection.kind === graphql_web.Kind.FIELD && selection.name.value === "__typename" && !selection.alias; - var newSelection = formatNode(selection); - selections.push(newSelection); - } - if (!hasTypename) { - selections.push({ - kind: graphql_web.Kind.FIELD, - name: { - kind: graphql_web.Kind.NAME, - value: "__typename" - }, - _generated: true - }); - } - return { - ...node, - selectionSet: { - ...node.selectionSet, - selections - } - }; - } - } - return node; - }; - var formattedDocs = /* @__PURE__ */ new Map(); - var formatDocument = (node) => { - var query = fetchSource.keyDocument(node); - var result = formattedDocs.get(query.__key); - if (!result) { - formattedDocs.set(query.__key, result = formatNode(query)); - Object.defineProperty(result, "__key", { - value: query.__key, - enumerable: false - }); - } - return result; - }; - var maskTypename = (data2, isRoot) => { - if (!data2 || typeof data2 !== "object") { - return data2; - } else if (Array.isArray(data2)) { - return data2.map((d) => maskTypename(d)); - } else if (data2 && typeof data2 === "object" && (isRoot || "__typename" in data2)) { - var acc = {}; - for (var key in data2) { - if (key === "__typename") { - Object.defineProperty(acc, "__typename", { - enumerable: false, - value: data2.__typename - }); - } else { - acc[key] = maskTypename(data2[key]); - } - } - return acc; - } else { - return data2; - } - }; - function withPromise(_source$) { - var source$ = (sink) => _source$(sink); - source$.toPromise = () => wonka.toPromise(wonka.take(1)(wonka.filter((result) => !result.stale && !result.hasNext)(source$))); - source$.then = (onResolve, onReject) => source$.toPromise().then(onResolve, onReject); - source$.subscribe = (onResult) => wonka.subscribe(onResult)(source$); - return source$; - } - function makeOperation(kind, request, context) { - return { - ...request, - kind, - context: request.context ? { - ...request.context, - ...context - } : context || request.context - }; - } - var addMetadata = (operation, meta) => { - return makeOperation(operation.kind, operation, { - meta: { - ...operation.context.meta, - ...meta - } - }); - }; - var noop = () => { - }; - function gql(parts) { - var fragmentNames = /* @__PURE__ */ new Map(); - var definitions = []; - var source = []; - var body = Array.isArray(parts) ? parts[0] : parts || ""; - for (var i = 1; i < arguments.length; i++) { - var value = arguments[i]; - if (value && value.definitions) { - source.push(value); - } else { - body += value; - } - body += arguments[0][i]; - } - source.unshift(fetchSource.keyDocument(body)); - for (var document2 of source) { - for (var definition of document2.definitions) { - if (definition.kind === graphql_web.Kind.FRAGMENT_DEFINITION) { - var name = definition.name.value; - var _value = fetchSource.stringifyDocument(definition); - if (!fragmentNames.has(name)) { - fragmentNames.set(name, _value); - definitions.push(definition); - } else if (fragmentNames.get(name) !== _value) { - console.warn("[WARNING: Duplicate Fragment] A fragment with name `" + name + "` already exists in this document.\nWhile fragment names may not be unique across your source, each name must be unique per document."); - } - } else { - definitions.push(definition); - } - } - } - return fetchSource.keyDocument({ - kind: graphql_web.Kind.DOCUMENT, - definitions - }); - } - var shouldSkip = ({ - kind - }) => kind !== "mutation" && kind !== "query"; - var mapTypeNames = (operation) => { - var query = formatDocument(operation.query); - if (query !== operation.query) { - var formattedOperation = makeOperation(operation.kind, operation); - formattedOperation.query = query; - return formattedOperation; - } else { - return operation; - } - }; - var cacheExchange = ({ - forward, - client, - dispatchDebug - }) => { - var resultCache = /* @__PURE__ */ new Map(); - var operationCache = /* @__PURE__ */ new Map(); - var isOperationCached = (operation) => operation.kind === "query" && operation.context.requestPolicy !== "network-only" && (operation.context.requestPolicy === "cache-only" || resultCache.has(operation.key)); - return (ops$) => { - var cachedOps$ = wonka.map((operation) => { - var cachedResult = resultCache.get(operation.key); - true ? dispatchDebug({ - operation, - ...cachedResult ? { - type: "cacheHit", - message: "The result was successfully retried from the cache" - } : { - type: "cacheMiss", - message: "The result could not be retrieved from the cache" - }, - "source": "cacheExchange" - }) : void 0; - var result = cachedResult || fetchSource.makeResult(operation, { - data: null - }); - result = { - ...result, - operation: true ? addMetadata(operation, { - cacheOutcome: cachedResult ? "hit" : "miss" - }) : operation - }; - if (operation.context.requestPolicy === "cache-and-network") { - result.stale = true; - reexecuteOperation(client, operation); - } - return result; - })(wonka.filter((op) => !shouldSkip(op) && isOperationCached(op))(ops$)); - var forwardedOps$ = wonka.tap((response) => { - var { - operation - } = response; - if (!operation) - return; - var typenames = operation.context.additionalTypenames || []; - if (response.operation.kind !== "subscription") { - typenames = collectTypenames(response.data).concat(typenames); - } - if (response.operation.kind === "mutation" || response.operation.kind === "subscription") { - var pendingOperations = /* @__PURE__ */ new Set(); - true ? dispatchDebug({ - type: "cacheInvalidation", - message: `The following typenames have been invalidated: ${typenames}`, - operation, - data: { - typenames, - response - }, - "source": "cacheExchange" - }) : void 0; - for (var i = 0; i < typenames.length; i++) { - var typeName = typenames[i]; - var operations = operationCache.get(typeName); - if (!operations) - operationCache.set(typeName, operations = /* @__PURE__ */ new Set()); - for (var key of operations.values()) - pendingOperations.add(key); - operations.clear(); - } - for (var _key of pendingOperations.values()) { - if (resultCache.has(_key)) { - operation = resultCache.get(_key).operation; - resultCache.delete(_key); - reexecuteOperation(client, operation); - } - } - } else if (operation.kind === "query" && response.data) { - resultCache.set(operation.key, response); - for (var _i = 0; _i < typenames.length; _i++) { - var _typeName = typenames[_i]; - var _operations = operationCache.get(_typeName); - if (!_operations) - operationCache.set(_typeName, _operations = /* @__PURE__ */ new Set()); - _operations.add(operation.key); - } - } - })(forward(wonka.filter((op) => op.kind !== "query" || op.context.requestPolicy !== "cache-only")(wonka.map((op) => true ? addMetadata(op, { - cacheOutcome: "miss" - }) : op)(wonka.merge([wonka.map(mapTypeNames)(wonka.filter((op) => !shouldSkip(op) && !isOperationCached(op))(ops$)), wonka.filter((op) => shouldSkip(op))(ops$)]))))); - return wonka.merge([cachedOps$, forwardedOps$]); - }; - }; - var reexecuteOperation = (client, operation) => { - return client.reexecuteOperation(makeOperation(operation.kind, operation, { - requestPolicy: "network-only" - })); - }; - var serializeResult = (result, includeExtensions) => { - var serialized = { - data: JSON.stringify(result.data), - hasNext: result.hasNext - }; - if (result.data !== void 0) { - serialized.data = JSON.stringify(result.data); - } - if (includeExtensions && result.extensions !== void 0) { - serialized.extensions = JSON.stringify(result.extensions); - } - if (result.error) { - serialized.error = { - graphQLErrors: result.error.graphQLErrors.map((error) => { - if (!error.path && !error.extensions) - return error.message; - return { - message: error.message, - path: error.path, - extensions: error.extensions - }; - }) - }; - if (result.error.networkError) { - serialized.error.networkError = "" + result.error.networkError; - } - } - return serialized; - }; - var deserializeResult = (operation, result, includeExtensions) => ({ - operation, - data: result.data ? JSON.parse(result.data) : void 0, - extensions: includeExtensions && result.extensions ? JSON.parse(result.extensions) : void 0, - error: result.error ? new fetchSource.CombinedError({ - networkError: result.error.networkError ? new Error(result.error.networkError) : void 0, - graphQLErrors: result.error.graphQLErrors - }) : void 0, - stale: false, - hasNext: !!result.hasNext - }); - var revalidated = /* @__PURE__ */ new Set(); - var ssrExchange = (params = {}) => { - var staleWhileRevalidate = !!params.staleWhileRevalidate; - var includeExtensions = !!params.includeExtensions; - var data2 = {}; - var invalidateQueue = []; - var invalidate = (result) => { - invalidateQueue.push(result.operation.key); - if (invalidateQueue.length === 1) { - Promise.resolve().then(() => { - var key; - while (key = invalidateQueue.shift()) { - data2[key] = null; - } - }); - } - }; - var ssr = ({ - client, - forward - }) => (ops$) => { - var isClient = params && typeof params.isClient === "boolean" ? !!params.isClient : !client.suspense; - var forwardedOps$ = forward(wonka.map(mapTypeNames)(wonka.filter((operation) => operation.kind === "teardown" || !data2[operation.key] || !!data2[operation.key].hasNext || operation.context.requestPolicy === "network-only")(ops$))); - var cachedOps$ = wonka.map((op) => { - var serialized = data2[op.key]; - var cachedResult = deserializeResult(op, serialized, includeExtensions); - if (staleWhileRevalidate && !revalidated.has(op.key)) { - cachedResult.stale = true; - revalidated.add(op.key); - reexecuteOperation(client, op); - } - var result = { - ...cachedResult, - operation: true ? addMetadata(op, { - cacheOutcome: "hit" - }) : op - }; - return result; - })(wonka.filter((operation) => operation.kind !== "teardown" && !!data2[operation.key] && operation.context.requestPolicy !== "network-only")(ops$)); - if (!isClient) { - forwardedOps$ = wonka.tap((result) => { - var { - operation - } = result; - if (operation.kind !== "mutation") { - var serialized = serializeResult(result, includeExtensions); - data2[operation.key] = serialized; - } - })(forwardedOps$); - } else { - cachedOps$ = wonka.tap(invalidate)(cachedOps$); - } - return wonka.merge([forwardedOps$, cachedOps$]); - }; - ssr.restoreData = (restore) => { - for (var _key in restore) { - if (data2[_key] !== null) { - data2[_key] = restore[_key]; - } - } - }; - ssr.extractData = () => { - var result = {}; - for (var _key2 in data2) - if (data2[_key2] != null) - result[_key2] = data2[_key2]; - return result; - }; - if (params && params.initialState) { - ssr.restoreData(params.initialState); - } - return ssr; - }; - var subscriptionExchange = ({ - forwardSubscription, - enableAllOperations, - isSubscriptionOperation - }) => ({ - client, - forward - }) => { - var createSubscriptionSource = (operation) => { - var observableish = forwardSubscription(fetchSource.makeFetchBody(operation), operation); - return wonka.make((observer) => { - var isComplete = false; - var sub; - var result; - function nextResult(value) { - observer.next(result = result ? fetchSource.mergeResultPatch(result, value) : fetchSource.makeResult(operation, value)); - } - Promise.resolve().then(() => { - if (isComplete) - return; - sub = observableish.subscribe({ - next: nextResult, - error(error) { - if (Array.isArray(error)) { - nextResult({ - errors: error - }); - } else { - observer.next(fetchSource.makeErrorResult(operation, error)); - } - observer.complete(); - }, - complete() { - if (!isComplete) { - isComplete = true; - if (operation.kind === "subscription") { - client.reexecuteOperation(makeOperation("teardown", operation, operation.context)); - } - if (result && result.hasNext) { - nextResult({ - hasNext: false - }); - } - observer.complete(); - } - } - }); - }); - return () => { - isComplete = true; - if (sub) - sub.unsubscribe(); - }; - }); - }; - var isSubscriptionOperationFn = isSubscriptionOperation || ((operation) => operation.kind === "subscription" || !!enableAllOperations && (operation.kind === "query" || operation.kind === "mutation")); - return (ops$) => { - var subscriptionResults$ = wonka.mergeMap((operation) => { - var { - key - } = operation; - var teardown$ = wonka.filter((op) => op.kind === "teardown" && op.key === key)(ops$); - return wonka.takeUntil(teardown$)(createSubscriptionSource(operation)); - })(wonka.filter((operation) => operation.kind !== "teardown" && isSubscriptionOperationFn(operation))(ops$)); - var forward$ = forward(wonka.filter((operation) => operation.kind === "teardown" || !isSubscriptionOperationFn(operation))(ops$)); - return wonka.merge([subscriptionResults$, forward$]); - }; - }; - var debugExchange = ({ - forward - }) => { - if (false) { - return (ops$) => forward(ops$); - } else { - return (ops$) => wonka.tap((result) => console.log("[Exchange debug]: Completed operation: ", result))(forward(wonka.tap((op) => console.log("[Exchange debug]: Incoming operation: ", op))(ops$))); - } - }; - var dedupExchange = ({ - forward - }) => (ops$) => forward(ops$); - var fetchExchange = ({ - forward, - dispatchDebug - }) => { - return (ops$) => { - var fetchResults$ = wonka.mergeMap((operation) => { - var body = fetchSource.makeFetchBody(operation); - var url = fetchSource.makeFetchURL(operation, body); - var fetchOptions = fetchSource.makeFetchOptions(operation, body); - true ? dispatchDebug({ - type: "fetchRequest", - message: "A fetch request is being executed.", - operation, - data: { - url, - fetchOptions - }, - "source": "fetchExchange" - }) : void 0; - var source = wonka.takeUntil(wonka.filter((op) => op.kind === "teardown" && op.key === operation.key)(ops$))(fetchSource.makeFetchSource(operation, url, fetchOptions)); - if (true) { - return wonka.onPush((result) => { - var error = !result.data ? result.error : void 0; - true ? dispatchDebug({ - type: error ? "fetchError" : "fetchSuccess", - message: `A ${error ? "failed" : "successful"} fetch response has been returned.`, - operation, - data: { - url, - fetchOptions, - value: error || result - }, - "source": "fetchExchange" - }) : void 0; - })(source); - } - return source; - })(wonka.filter((operation) => { - return operation.kind !== "teardown" && (operation.kind !== "subscription" || !!operation.context.fetchSubscriptions); - })(ops$)); - var forward$ = forward(wonka.filter((operation) => { - return operation.kind === "teardown" || operation.kind === "subscription" && !operation.context.fetchSubscriptions; - })(ops$)); - return wonka.merge([fetchResults$, forward$]); - }; - }; - var composeExchanges = (exchanges) => ({ - client, - forward, - dispatchDebug - }) => exchanges.reduceRight((forward2, exchange) => { - var forwarded = false; - return exchange({ - client, - forward(operations$) { - if (true) { - if (forwarded) - throw new Error("forward() must only be called once in each Exchange."); - forwarded = true; - } - return wonka.share(forward2(wonka.share(operations$))); - }, - dispatchDebug(event) { - true ? dispatchDebug({ - timestamp: Date.now(), - source: exchange.name, - ...event - }) : void 0; - } - }); - }, forward); - var mapExchange = ({ - onOperation, - onResult, - onError - }) => { - return ({ - forward - }) => (ops$) => { - return wonka.mergeMap((result) => { - if (onError && result.error) - onError(result.error, result.operation); - var newResult = onResult && onResult(result) || result; - return "then" in newResult ? wonka.fromPromise(newResult) : wonka.fromValue(newResult); - })(forward(wonka.mergeMap((operation) => { - var newOperation = onOperation && onOperation(operation) || operation; - return "then" in newOperation ? wonka.fromPromise(newOperation) : wonka.fromValue(newOperation); - })(ops$))); - }; - }; - var fallbackExchange = ({ - dispatchDebug - }) => (ops$) => { - if (true) { - ops$ = wonka.tap((operation) => { - if (operation.kind !== "teardown" && true) { - var message = `No exchange has handled operations of kind "${operation.kind}". Check whether you've added an exchange responsible for these operations.`; - true ? dispatchDebug({ - type: "fallbackCatch", - message, - operation, - "source": "fallbackExchange" - }) : void 0; - console.warn(message); - } - })(ops$); - } - return wonka.filter((_x) => false)(ops$); - }; - var Client = function Client2(opts) { - if (!opts.url) { - throw new Error("You are creating an urql-client without a url."); - } - var ids = 0; - var replays = /* @__PURE__ */ new Map(); - var active = /* @__PURE__ */ new Map(); - var dispatched = /* @__PURE__ */ new Set(); - var queue = []; - var baseOpts = { - url: opts.url, - fetchSubscriptions: opts.fetchSubscriptions, - fetchOptions: opts.fetchOptions, - fetch: opts.fetch, - preferGetMethod: opts.preferGetMethod, - requestPolicy: opts.requestPolicy || "cache-first" - }; - var operations = wonka.makeSubject(); - function nextOperation(operation) { - if (operation.kind === "mutation" || operation.kind === "teardown" || !dispatched.has(operation.key)) { - if (operation.kind === "teardown") { - dispatched.delete(operation.key); - } else if (operation.kind !== "mutation") { - dispatched.add(operation.key); - } - operations.next(operation); - } - } - var isOperationBatchActive = false; - function dispatchOperation(operation) { - if (operation) - nextOperation(operation); - if (!isOperationBatchActive) { - isOperationBatchActive = true; - while (isOperationBatchActive && (operation = queue.shift())) - nextOperation(operation); - isOperationBatchActive = false; - } - } - var makeResultSource = (operation) => { - var result$ = wonka.takeUntil(wonka.filter((op) => op.kind === "teardown" && op.key === operation.key)(operations.source))(wonka.filter((res) => res.operation.kind === operation.kind && res.operation.key === operation.key && (!res.operation.context._instance || res.operation.context._instance === operation.context._instance))(results$)); - if (opts.maskTypename) { - result$ = wonka.map((res) => ({ - ...res, - data: maskTypename(res.data, true) - }))(result$); - } - if (operation.kind !== "query") { - result$ = wonka.takeWhile((result) => !!result.hasNext, true)(result$); - } else { - result$ = wonka.switchMap((result) => { - var value$ = wonka.fromValue(result); - return result.stale || result.hasNext ? value$ : wonka.merge([value$, wonka.map(() => { - result.stale = true; - return result; - })(wonka.take(1)(wonka.filter((op) => op.key === operation.key)(operations.source)))]); - })(result$); - } - if (operation.kind !== "mutation") { - result$ = wonka.onEnd(() => { - dispatched.delete(operation.key); - replays.delete(operation.key); - active.delete(operation.key); - isOperationBatchActive = false; - for (var i = queue.length - 1; i >= 0; i--) - if (queue[i].key === operation.key) - queue.splice(i, 1); - nextOperation(makeOperation("teardown", operation, operation.context)); - })(wonka.onPush((result) => { - if (result.stale) { - for (var _operation of queue) { - if (_operation.key === result.operation.key) { - dispatched.delete(_operation.key); - break; - } - } - } else if (!result.hasNext) { - dispatched.delete(operation.key); - } - replays.set(operation.key, result); - })(result$)); - } else { - result$ = wonka.onStart(() => { - nextOperation(operation); - })(result$); - } - return wonka.share(result$); - }; - var instance = this instanceof Client2 ? this : Object.create(Client2.prototype); - var client = Object.assign(instance, { - suspense: !!opts.suspense, - operations$: operations.source, - reexecuteOperation(operation) { - if (operation.kind === "teardown") { - dispatchOperation(operation); - } else if (operation.kind === "mutation" || active.has(operation.key)) { - var queued = false; - for (var i = 0; i < queue.length; i++) - queued = queued || queue[i].key === operation.key; - if (!queued) - dispatched.delete(operation.key); - queue.push(operation); - Promise.resolve().then(dispatchOperation); - } - }, - createRequestOperation(kind, request, opts2) { - if (!opts2) - opts2 = {}; - var requestOperationType; - if (kind !== "teardown" && (requestOperationType = fetchSource.getOperationType(request.query)) !== kind) { - throw new Error(`Expected operation of type "${kind}" but found "${requestOperationType}"`); - } - return makeOperation(kind, request, { - _instance: kind === "mutation" ? ids = ids + 1 | 0 : void 0, - ...baseOpts, - ...opts2, - requestPolicy: opts2.requestPolicy || baseOpts.requestPolicy, - suspense: opts2.suspense || opts2.suspense !== false && client.suspense - }); - }, - executeRequestOperation(operation) { - if (operation.kind === "mutation") { - return withPromise(makeResultSource(operation)); - } - return withPromise(wonka.lazy(() => { - var source2 = active.get(operation.key); - if (!source2) { - active.set(operation.key, source2 = makeResultSource(operation)); - } - source2 = wonka.onStart(() => { - dispatchOperation(operation); - })(source2); - var replay = replays.get(operation.key); - if (operation.kind === "query" && replay && (replay.stale || replay.hasNext)) { - return wonka.switchMap(wonka.fromValue)(wonka.merge([source2, wonka.filter((replay2) => replay2 === replays.get(operation.key))(wonka.fromValue(replay))])); - } else { - return source2; - } - })); - }, - executeQuery(query, opts2) { - var operation = client.createRequestOperation("query", query, opts2); - return client.executeRequestOperation(operation); - }, - executeSubscription(query, opts2) { - var operation = client.createRequestOperation("subscription", query, opts2); - return client.executeRequestOperation(operation); - }, - executeMutation(query, opts2) { - var operation = client.createRequestOperation("mutation", query, opts2); - return client.executeRequestOperation(operation); - }, - readQuery(query, variables, context) { - var result = null; - wonka.subscribe((res) => { - result = res; - })(client.query(query, variables, context)).unsubscribe(); - return result; - }, - query(query, variables, context) { - return client.executeQuery(fetchSource.createRequest(query, variables), context); - }, - subscription(query, variables, context) { - return client.executeSubscription(fetchSource.createRequest(query, variables), context); - }, - mutation(query, variables, context) { - return client.executeMutation(fetchSource.createRequest(query, variables), context); - } - }); - var dispatchDebug = noop; - if (true) { - var { - next, - source - } = wonka.makeSubject(); - client.subscribeToDebugTarget = (onEvent) => wonka.subscribe(onEvent)(source); - dispatchDebug = next; - } - var composedExchange = composeExchanges(opts.exchanges); - var results$ = wonka.share(composedExchange({ - client, - dispatchDebug, - forward: fallbackExchange({ - dispatchDebug - }) - })(operations.source)); - wonka.publish(results$); - return client; - }; - var createClient = Client; - exports.CombinedError = fetchSource.CombinedError; - exports.createRequest = fetchSource.createRequest; - exports.makeErrorResult = fetchSource.makeErrorResult; - exports.makeResult = fetchSource.makeResult; - exports.mergeResultPatch = fetchSource.mergeResultPatch; - exports.stringifyDocument = fetchSource.stringifyDocument; - exports.stringifyVariables = fetchSource.stringifyVariables; - exports.Client = Client; - exports.cacheExchange = cacheExchange; - exports.composeExchanges = composeExchanges; - exports.createClient = createClient; - exports.debugExchange = debugExchange; - exports.dedupExchange = dedupExchange; - exports.errorExchange = mapExchange; - exports.fetchExchange = fetchExchange; - exports.formatDocument = formatDocument; - exports.gql = gql; - exports.makeOperation = makeOperation; - exports.mapExchange = mapExchange; - exports.maskTypename = maskTypename; - exports.ssrExchange = ssrExchange; - exports.subscriptionExchange = subscriptionExchange; - } -}); - -// node_modules/@omnivore-app/api/dist/src/errors.js -var require_errors = __commonJS({ - "node_modules/@omnivore-app/api/dist/src/errors.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isOmnivoreError = exports.buildOmnivoreError = exports.OmnivoreErrorCode = void 0; - var OmnivoreErrorCode; - (function(OmnivoreErrorCode2) { - OmnivoreErrorCode2["GraphQLError"] = "GRAPHQL_ERROR"; - OmnivoreErrorCode2["NetworkError"] = "NETWORK_ERROR"; - OmnivoreErrorCode2["UnknownError"] = "UNKNOWN_ERROR"; - })(OmnivoreErrorCode || (exports.OmnivoreErrorCode = OmnivoreErrorCode = {})); - var OmnivoreErrorBase = class extends Error { - }; - var GraphQLError = class extends OmnivoreErrorBase { - constructor(messages) { - super(messages?.join(", ")); - __publicField(this, "messages"); - __publicField(this, "code", OmnivoreErrorCode.GraphQLError); - this.messages = messages; - } - }; - var NetworkError = class extends OmnivoreErrorBase { - constructor(message) { - super(message); - __publicField(this, "message"); - __publicField(this, "code", OmnivoreErrorCode.NetworkError); - this.message = message; - } - }; - var UnknownError = class extends OmnivoreErrorBase { - constructor(message) { - super(message); - __publicField(this, "message"); - __publicField(this, "code", OmnivoreErrorCode.UnknownError); - this.message = message; - } - }; - var buildOmnivoreError = (data2, error) => { - if (error) { - if (error.graphQLErrors.length > 0) { - return new GraphQLError(error.graphQLErrors.map((e) => e.message)); - } - if (error.networkError) { - return new NetworkError(error.networkError.message); - } - } - if (!data2) { - return new UnknownError("No data returned"); - } - return new GraphQLError(data2.errorCodes); - }; - exports.buildOmnivoreError = buildOmnivoreError; - var isOmnivoreError = (error) => { - return error instanceof GraphQLError || error instanceof NetworkError || error instanceof UnknownError; - }; - exports.isOmnivoreError = isOmnivoreError; - } -}); - -// node_modules/gql.tada/dist/gql-tada.js -var require_gql_tada = __commonJS({ - "node_modules/gql.tada/dist/gql-tada.js"(exports) { - Object.defineProperty(exports, "__esModule", { - value: true - }); - var r = require_graphql_web(); - function initGraphQLTada() { - function graphql(e2, n2) { - var a = r.parse(e2).definitions; - var i = /* @__PURE__ */ new Set(); - for (var t of n2 || []) { - for (var s2 of t.definitions) { - if (s2.kind === r.Kind.FRAGMENT_DEFINITION && !i.has(s2)) { - a.push(s2); - i.add(s2); - } - } - } - if (a[0].kind === r.Kind.FRAGMENT_DEFINITION && a[0].directives) { - a[0].directives = a[0].directives.filter((r2) => r2.name.value !== "_unmask"); - } - return { - kind: r.Kind.DOCUMENT, - definitions: a - }; - } - graphql.scalar = function scalar(r2, e2) { - return e2; - }; - graphql.persisted = function persisted(e2) { - return { - kind: r.Kind.DOCUMENT, - definitions: [], - documentId: e2 - }; - }; - return graphql; - } - var e = initGraphQLTada(); - exports.graphql = e; - exports.initGraphQLTada = initGraphQLTada; - exports.maskFragments = function maskFragments(r2, e2) { - return e2; - }; - exports.parse = function parse4(e2) { - return r.parse(e2); - }; - exports.readFragment = function readFragment(r2, e2) { - return e2; - }; - exports.unsafe_readResult = function unsafe_readResult(r2, e2) { - return e2; - }; - } -}); - -// node_modules/@omnivore-app/api/dist/src/graphql.js -var require_graphql = __commonJS({ - "node_modules/@omnivore-app/api/dist/src/graphql.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.saveByURLMutation = exports.DeleteMutation = exports.UpdatesSinceQuery = exports.SearchQuery = void 0; - var gql_tada_1 = require_gql_tada(); - var graphql = (0, gql_tada_1.initGraphQLTada)(); - var PageInfoFragment = graphql(` - fragment PageInfoFragment on PageInfo @_unmask { - hasNextPage - hasPreviousPage - startCursor - endCursor - totalCount - } -`); - var LabelFragment = graphql(` - fragment LabelFragment on Label @_unmask { - name - color - createdAt - id - internal - source - description - } -`); - var HighlightFragment = graphql(` - fragment HighlightFragment on Highlight @_unmask { - id - quote - annotation - patch - updatedAt - labels { - ...LabelFragment - } - type - highlightPositionPercent - color - highlightPositionAnchorIndex - prefix - suffix - createdAt - } - `, [LabelFragment]); - var SearchItemFragment = graphql(` - fragment SearchItemFragment on SearchItem @_unmask { - id - title - siteName - originalArticleUrl - author - description - slug - labels { - ...LabelFragment - } - highlights { - ...HighlightFragment - } - updatedAt - savedAt - pageType - content - publishedAt - url - image - readAt - wordsCount - readingProgressPercent - isArchived - archivedAt - contentReader - } - `, [LabelFragment, HighlightFragment]); - exports.SearchQuery = graphql(` - query Search( - $after: String - $first: Int - $format: String - $includeContent: Boolean - $query: String - ) { - search( - after: $after - first: $first - format: $format - includeContent: $includeContent - query: $query - ) { - __typename - ... on SearchSuccess { - edges { - node { - ...SearchItemFragment - } - } - pageInfo { - ...PageInfoFragment - } - } - ... on SearchError { - errorCodes - } - } - } - `, [SearchItemFragment, PageInfoFragment]); - exports.UpdatesSinceQuery = graphql(` - query UpdatesSince($since: Date!) { - updatesSince(since: $since) { - __typename - ... on UpdatesSinceSuccess { - edges { - itemID - updateReason - node { - ...SearchItemFragment - } - } - pageInfo { - ...PageInfoFragment - } - } - ... on UpdatesSinceError { - errorCodes - } - } - } - `, [SearchItemFragment, PageInfoFragment]); - exports.DeleteMutation = graphql(` - mutation Delete($input: SetBookmarkArticleInput!) { - setBookmarkArticle(input: $input) { - __typename - ... on SetBookmarkArticleSuccess { - bookmarkedArticle { - id - } - } - ... on SetBookmarkArticleError { - errorCodes - } - } - } -`); - exports.saveByURLMutation = graphql(` - mutation SaveByURL($input: SaveUrlInput!) { - saveUrl(input: $input) { - __typename - ... on SaveSuccess { - clientRequestId - } - ... on SaveError { - errorCodes - } - } - } -`); - } -}); - -// node_modules/@omnivore-app/api/dist/src/client.js -var require_client = __commonJS({ - "node_modules/@omnivore-app/api/dist/src/client.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.Omnivore = void 0; - var core_1 = require_urql_core(); - var errors_1 = require_errors(); - var graphql_1 = require_graphql(); - var Omnivore2 = class { - constructor(clientOptions) { - __publicField(this, "client"); - __publicField(this, "items", { - search: async (params) => { - const { data: data2, error } = await this.client.query(graphql_1.SearchQuery, { - ...params, - after: params.after ? String(params.after) : void 0 - }).toPromise(); - const search = data2?.search; - if (error || !search || search.__typename === "SearchError") { - const err = (0, errors_1.buildOmnivoreError)(search, error); - console.error("Search error", err); - throw err; - } - return search; - }, - updates: async (params) => { - const { data: data2, error } = await this.client.query(graphql_1.UpdatesSinceQuery, params).toPromise(); - const updatesSince = data2?.updatesSince; - if (error || !updatesSince || updatesSince.__typename === "UpdatesSinceError") { - const err = (0, errors_1.buildOmnivoreError)(updatesSince, error); - console.error("UpdatesSince error", err); - throw err; - } - return updatesSince; - }, - delete: async (params) => { - const { data: data2, error } = await this.client.mutation(graphql_1.DeleteMutation, { - input: { articleID: params.id, bookmark: false } - }).toPromise(); - const deleteArticle = data2?.setBookmarkArticle; - if (error || !deleteArticle || deleteArticle.__typename === "SetBookmarkArticleError") { - const err = (0, errors_1.buildOmnivoreError)(deleteArticle, error); - console.error("Delete error", err); - throw err; - } - return { id: deleteArticle.bookmarkedArticle.id }; - }, - saveByUrl: async (params) => { - const { data: data2, error } = await this.client.mutation(graphql_1.saveByURLMutation, { - input: { - ...params, - source: params.source || "API-Client", - clientRequestId: params.clientRequestId || "" - } - }).toPromise(); - const saveUrl = data2?.saveUrl; - if (error || !saveUrl || saveUrl.__typename === "SaveError") { - const err = (0, errors_1.buildOmnivoreError)(saveUrl, error); - console.error("SaveByURL error", err); - throw err; - } - return { id: saveUrl.clientRequestId }; - } - }); - this.client = new core_1.Client({ - url: `${clientOptions.baseUrl || "https://api-prod.omnivore.app"}/api/graphql`, - exchanges: [core_1.fetchExchange], - fetchOptions: () => ({ - headers: { - Authorization: clientOptions.authToken - }, - timeout: clientOptions.timeoutMs || 0 - }) - }); - } - }; - exports.Omnivore = Omnivore2; - } -}); - -// node_modules/@omnivore-app/api/dist/src/index.js -var require_src = __commonJS({ - "node_modules/@omnivore-app/api/dist/src/index.js"(exports) { - "use strict"; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.isOmnivoreError = exports.OmnivoreErrorCode = exports.Omnivore = void 0; - var client_1 = require_client(); - Object.defineProperty(exports, "Omnivore", { enumerable: true, get: function() { - return client_1.Omnivore; - } }); - var errors_1 = require_errors(); - Object.defineProperty(exports, "OmnivoreErrorCode", { enumerable: true, get: function() { - return errors_1.OmnivoreErrorCode; - } }); - Object.defineProperty(exports, "isOmnivoreError", { enumerable: true, get: function() { - return errors_1.isOmnivoreError; - } }); - } -}); - -// node_modules/lodash/lodash.js -var require_lodash = __commonJS({ - "node_modules/lodash/lodash.js"(exports, module2) { - (function() { - var undefined2; - var VERSION = "4.17.21"; - var LARGE_ARRAY_SIZE = 200; - var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var MAX_MEMOIZE_SIZE = 500; - var PLACEHOLDER = "__lodash_placeholder__"; - var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; - var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; - var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; - var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; - var HOT_COUNT = 800, HOT_SPAN = 16; - var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; - var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - var wrapFlags = [ - ["ary", WRAP_ARY_FLAG], - ["bind", WRAP_BIND_FLAG], - ["bindKey", WRAP_BIND_KEY_FLAG], - ["curry", WRAP_CURRY_FLAG], - ["curryRight", WRAP_CURRY_RIGHT_FLAG], - ["flip", WRAP_FLIP_FLAG], - ["partial", WRAP_PARTIAL_FLAG], - ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], - ["rearg", WRAP_REARG_FLAG] - ]; - var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; - var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; - var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); - var reTrimStart = /^\s+/; - var reWhitespace = /\s/; - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - var reEscapeChar = /\\(\\)?/g; - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - var reFlags = /\w*$/; - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var reIsBinary = /^0b[01]+$/i; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsOctal = /^0o[0-7]+$/i; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - var reNoMatch = /($^)/; - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; - var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reApos = RegExp(rsApos, "g"); - var reComboMark = RegExp(rsCombo, "g"); - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reUnicodeWord = RegExp([ - rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", - rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", - rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, - rsUpper + "+" + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join("|"), "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - var contextProps = [ - "Array", - "Buffer", - "DataView", - "Date", - "Error", - "Float32Array", - "Float64Array", - "Function", - "Int8Array", - "Int16Array", - "Int32Array", - "Map", - "Math", - "Object", - "Promise", - "RegExp", - "Set", - "String", - "Symbol", - "TypeError", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "WeakMap", - "_", - "clearTimeout", - "isFinite", - "parseInt", - "setTimeout" - ]; - var templateCounter = -1; - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; - var deburredLetters = { - "\xC0": "A", - "\xC1": "A", - "\xC2": "A", - "\xC3": "A", - "\xC4": "A", - "\xC5": "A", - "\xE0": "a", - "\xE1": "a", - "\xE2": "a", - "\xE3": "a", - "\xE4": "a", - "\xE5": "a", - "\xC7": "C", - "\xE7": "c", - "\xD0": "D", - "\xF0": "d", - "\xC8": "E", - "\xC9": "E", - "\xCA": "E", - "\xCB": "E", - "\xE8": "e", - "\xE9": "e", - "\xEA": "e", - "\xEB": "e", - "\xCC": "I", - "\xCD": "I", - "\xCE": "I", - "\xCF": "I", - "\xEC": "i", - "\xED": "i", - "\xEE": "i", - "\xEF": "i", - "\xD1": "N", - "\xF1": "n", - "\xD2": "O", - "\xD3": "O", - "\xD4": "O", - "\xD5": "O", - "\xD6": "O", - "\xD8": "O", - "\xF2": "o", - "\xF3": "o", - "\xF4": "o", - "\xF5": "o", - "\xF6": "o", - "\xF8": "o", - "\xD9": "U", - "\xDA": "U", - "\xDB": "U", - "\xDC": "U", - "\xF9": "u", - "\xFA": "u", - "\xFB": "u", - "\xFC": "u", - "\xDD": "Y", - "\xFD": "y", - "\xFF": "y", - "\xC6": "Ae", - "\xE6": "ae", - "\xDE": "Th", - "\xFE": "th", - "\xDF": "ss", - "\u0100": "A", - "\u0102": "A", - "\u0104": "A", - "\u0101": "a", - "\u0103": "a", - "\u0105": "a", - "\u0106": "C", - "\u0108": "C", - "\u010A": "C", - "\u010C": "C", - "\u0107": "c", - "\u0109": "c", - "\u010B": "c", - "\u010D": "c", - "\u010E": "D", - "\u0110": "D", - "\u010F": "d", - "\u0111": "d", - "\u0112": "E", - "\u0114": "E", - "\u0116": "E", - "\u0118": "E", - "\u011A": "E", - "\u0113": "e", - "\u0115": "e", - "\u0117": "e", - "\u0119": "e", - "\u011B": "e", - "\u011C": "G", - "\u011E": "G", - "\u0120": "G", - "\u0122": "G", - "\u011D": "g", - "\u011F": "g", - "\u0121": "g", - "\u0123": "g", - "\u0124": "H", - "\u0126": "H", - "\u0125": "h", - "\u0127": "h", - "\u0128": "I", - "\u012A": "I", - "\u012C": "I", - "\u012E": "I", - "\u0130": "I", - "\u0129": "i", - "\u012B": "i", - "\u012D": "i", - "\u012F": "i", - "\u0131": "i", - "\u0134": "J", - "\u0135": "j", - "\u0136": "K", - "\u0137": "k", - "\u0138": "k", - "\u0139": "L", - "\u013B": "L", - "\u013D": "L", - "\u013F": "L", - "\u0141": "L", - "\u013A": "l", - "\u013C": "l", - "\u013E": "l", - "\u0140": "l", - "\u0142": "l", - "\u0143": "N", - "\u0145": "N", - "\u0147": "N", - "\u014A": "N", - "\u0144": "n", - "\u0146": "n", - "\u0148": "n", - "\u014B": "n", - "\u014C": "O", - "\u014E": "O", - "\u0150": "O", - "\u014D": "o", - "\u014F": "o", - "\u0151": "o", - "\u0154": "R", - "\u0156": "R", - "\u0158": "R", - "\u0155": "r", - "\u0157": "r", - "\u0159": "r", - "\u015A": "S", - "\u015C": "S", - "\u015E": "S", - "\u0160": "S", - "\u015B": "s", - "\u015D": "s", - "\u015F": "s", - "\u0161": "s", - "\u0162": "T", - "\u0164": "T", - "\u0166": "T", - "\u0163": "t", - "\u0165": "t", - "\u0167": "t", - "\u0168": "U", - "\u016A": "U", - "\u016C": "U", - "\u016E": "U", - "\u0170": "U", - "\u0172": "U", - "\u0169": "u", - "\u016B": "u", - "\u016D": "u", - "\u016F": "u", - "\u0171": "u", - "\u0173": "u", - "\u0174": "W", - "\u0175": "w", - "\u0176": "Y", - "\u0177": "y", - "\u0178": "Y", - "\u0179": "Z", - "\u017B": "Z", - "\u017D": "Z", - "\u017A": "z", - "\u017C": "z", - "\u017E": "z", - "\u0132": "IJ", - "\u0133": "ij", - "\u0152": "Oe", - "\u0153": "oe", - "\u0149": "'n", - "\u017F": "s" - }; - var htmlEscapes = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - var htmlUnescapes = { - "&": "&", - "<": "<", - ">": ">", - """: '"', - "'": "'" - }; - var stringEscapes = { - "\\": "\\", - "'": "'", - "\n": "n", - "\r": "r", - "\u2028": "u2028", - "\u2029": "u2029" - }; - var freeParseFloat = parseFloat, freeParseInt = parseInt; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; - var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = function() { - try { - var types = freeModule && freeModule.require && freeModule.require("util").types; - if (types) { - return types; - } - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e) { - } - }(); - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function apply(func, thisArg, args) { - switch (args.length) { - case 0: - return func.call(thisArg); - case 1: - return func.call(thisArg, args[0]); - case 2: - return func.call(thisArg, args[0], args[1]); - case 3: - return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); - } - return accumulator; - } - function arrayEach(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - function arrayEvery(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - function arrayFilter(array, predicate) { - var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; - } - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } - function arrayIncludesWith(array, value, comparator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; - } - function arrayMap(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length, result = Array(length); - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - function arrayPush(array, values) { - var index = -1, length = values.length, offset3 = array.length; - while (++index < length) { - array[offset3 + index] = values[index]; - } - return array; - } - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - function arraySome(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - var asciiSize = baseProperty("length"); - function asciiToArray(string) { - return string.split(""); - } - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection2) { - if (predicate(value, key, collection2)) { - result = key; - return false; - } - }); - return result; - } - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, index = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index-- : ++index < length) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - function baseIndexOf(array, value, fromIndex) { - return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); - } - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; - } - function baseIsNaN(value) { - return value !== value; - } - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? baseSum(array, iteratee) / length : NAN; - } - function baseProperty(key) { - return function(object) { - return object == null ? undefined2 : object[key]; - }; - } - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined2 : object[key]; - }; - } - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection2) { - accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2); - }); - return accumulator; - } - function baseSortBy(array, comparer) { - var length = array.length; - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - function baseSum(array, iteratee) { - var result, index = -1, length = array.length; - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined2) { - result = result === undefined2 ? current : result + current; - } - } - return result; - } - function baseTimes(n2, iteratee) { - var index = -1, result = Array(n2); - while (++index < n2) { - result[index] = iteratee(index); - } - return result; - } - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - function baseTrim(string) { - return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; - } - function baseUnary(func) { - return function(value) { - return func(value); - }; - } - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - function cacheHas(cache, key) { - return cache.has(key); - } - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, length = strSymbols.length; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { - } - return index; - } - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { - } - return index; - } - function countHolders(array, placeholder) { - var length = array.length, result = 0; - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - var deburrLetter = basePropertyOf(deburredLetters); - var escapeHtmlChar = basePropertyOf(htmlEscapes); - function escapeStringChar(chr) { - return "\\" + stringEscapes[chr]; - } - function getValue(object, key) { - return object == null ? undefined2 : object[key]; - } - function hasUnicode(string) { - return reHasUnicode.test(string); - } - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - function iteratorToArray(iterator) { - var data2, result = []; - while (!(data2 = iterator.next()).done) { - result.push(data2.value); - } - return result; - } - function mapToArray(map) { - var index = -1, result = Array(map.size); - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - function replaceHolders(array, placeholder) { - var index = -1, length = array.length, resIndex = 0, result = []; - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - function setToArray(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } - function setToPairs(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; - } - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } - function stringSize(string) { - return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); - } - function stringToArray(string) { - return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); - } - function trimmedEndIndex(string) { - var index = string.length; - while (index-- && reWhitespace.test(string.charAt(index))) { - } - return index; - } - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - var runInContext = function runInContext2(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError; - var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; - var coreJsData = context["__core-js_shared__"]; - var funcToString = funcProto.toString; - var hasOwnProperty2 = objectProto.hasOwnProperty; - var idCounter = 0; - var maskSrcKey = function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; - }(); - var nativeObjectToString = objectProto.toString; - var objectCtorString = funcToString.call(Object2); - var oldDash = root._; - var reIsNative = RegExp2("^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); - var Buffer2 = moduleExports ? context.Buffer : undefined2, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : undefined2, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined2, symIterator = Symbol2 ? Symbol2.iterator : undefined2, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined2; - var defineProperty = function() { - try { - var func = getNative(Object2, "defineProperty"); - func({}, "", {}); - return func; - } catch (e) { - } - }(); - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined2, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse; - var DataView = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap2 = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create"); - var metaMap = WeakMap2 && new WeakMap2(); - var realNames = {}; - var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2); - var symbolProto = Symbol2 ? Symbol2.prototype : undefined2, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined2, symbolToString = symbolProto ? symbolProto.toString : undefined2; - function lodash(value) { - if (isObjectLike(value) && !isArray2(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty2.call(value, "__wrapped__")) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - var baseCreate = function() { - function object() { - } - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result2 = new object(); - object.prototype = undefined2; - return result2; - }; - }(); - function baseLodash() { - } - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined2; - } - lodash.templateSettings = { - "escape": reEscape, - "evaluate": reEvaluate, - "interpolate": reInterpolate, - "variable": "", - "imports": { - "_": lodash - } - }; - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - function lazyClone() { - var result2 = new LazyWrapper(this.__wrapped__); - result2.__actions__ = copyArray(this.__actions__); - result2.__dir__ = this.__dir__; - result2.__filtered__ = this.__filtered__; - result2.__iteratees__ = copyArray(this.__iteratees__); - result2.__takeCount__ = this.__takeCount__; - result2.__views__ = copyArray(this.__views__); - return result2; - } - function lazyReverse() { - if (this.__filtered__) { - var result2 = new LazyWrapper(this); - result2.__dir__ = -1; - result2.__filtered__ = true; - } else { - result2 = this.clone(); - result2.__dir__ *= -1; - } - return result2; - } - function lazyValue() { - var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start2 = view.start, end2 = view.end, length = end2 - start2, index = isRight ? end2 : start2 - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); - if (!isArr || !isRight && arrLength == length && takeCount == length) { - return baseWrapperValue(array, this.__actions__); - } - var result2 = []; - outer: - while (length-- && resIndex < takeCount) { - index += dir; - var iterIndex = -1, value = array[index]; - while (++iterIndex < iterLength) { - var data2 = iteratees[iterIndex], iteratee2 = data2.iteratee, type = data2.type, computed = iteratee2(value); - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result2[resIndex++] = value; - } - return result2; - } - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - function Hash(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - function hashDelete(key) { - var result2 = this.has(key) && delete this.__data__[key]; - this.size -= result2 ? 1 : 0; - return result2; - } - function hashGet(key) { - var data2 = this.__data__; - if (nativeCreate) { - var result2 = data2[key]; - return result2 === HASH_UNDEFINED ? undefined2 : result2; - } - return hasOwnProperty2.call(data2, key) ? data2[key] : undefined2; - } - function hashHas(key) { - var data2 = this.__data__; - return nativeCreate ? data2[key] !== undefined2 : hasOwnProperty2.call(data2, key); - } - function hashSet(key, value) { - var data2 = this.__data__; - this.size += this.has(key) ? 0 : 1; - data2[key] = nativeCreate && value === undefined2 ? HASH_UNDEFINED : value; - return this; - } - Hash.prototype.clear = hashClear; - Hash.prototype["delete"] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - function ListCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - function listCacheDelete(key) { - var data2 = this.__data__, index = assocIndexOf(data2, key); - if (index < 0) { - return false; - } - var lastIndex = data2.length - 1; - if (index == lastIndex) { - data2.pop(); - } else { - splice.call(data2, index, 1); - } - --this.size; - return true; - } - function listCacheGet(key) { - var data2 = this.__data__, index = assocIndexOf(data2, key); - return index < 0 ? undefined2 : data2[index][1]; - } - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - function listCacheSet(key, value) { - var data2 = this.__data__, index = assocIndexOf(data2, key); - if (index < 0) { - ++this.size; - data2.push([key, value]); - } else { - data2[index][1] = value; - } - return this; - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - function MapCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function mapCacheClear() { - this.size = 0; - this.__data__ = { - "hash": new Hash(), - "map": new (Map2 || ListCache)(), - "string": new Hash() - }; - } - function mapCacheDelete(key) { - var result2 = getMapData(this, key)["delete"](key); - this.size -= result2 ? 1 : 0; - return result2; - } - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - function mapCacheSet(key, value) { - var data2 = getMapData(this, key), size2 = data2.size; - data2.set(key, value); - this.size += data2.size == size2 ? 0 : 1; - return this; - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - function SetCache(values2) { - var index = -1, length = values2 == null ? 0 : values2.length; - this.__data__ = new MapCache(); - while (++index < length) { - this.add(values2[index]); - } - } - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } - function setCacheHas(value) { - return this.__data__.has(value); - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - function Stack(entries) { - var data2 = this.__data__ = new ListCache(entries); - this.size = data2.size; - } - function stackClear() { - this.__data__ = new ListCache(); - this.size = 0; - } - function stackDelete(key) { - var data2 = this.__data__, result2 = data2["delete"](key); - this.size = data2.size; - return result2; - } - function stackGet(key) { - return this.__data__.get(key); - } - function stackHas(key) { - return this.__data__.has(key); - } - function stackSet(key, value) { - var data2 = this.__data__; - if (data2 instanceof ListCache) { - var pairs = data2.__data__; - if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { - pairs.push([key, value]); - this.size = ++data2.size; - return this; - } - data2 = this.__data__ = new MapCache(pairs); - } - data2.set(key, value); - this.size = data2.size; - return this; - } - Stack.prototype.clear = stackClear; - Stack.prototype["delete"] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - function arrayLikeKeys(value, inherited) { - var isArr = isArray2(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length; - for (var key in value) { - if ((inherited || hasOwnProperty2.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { - result2.push(key); - } - } - return result2; - } - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined2; - } - function arraySampleSize(array, n2) { - return shuffleSelf(copyArray(array), baseClamp(n2, 0, array.length)); - } - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - function assignMergeValue(object, key, value) { - if (value !== undefined2 && !eq(object[key], value) || value === undefined2 && !(key in object)) { - baseAssignValue(object, key, value); - } - } - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty2.call(object, key) && eq(objValue, value)) || value === undefined2 && !(key in object)) { - baseAssignValue(object, key, value); - } - } - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - function baseAggregator(collection, setter, iteratee2, accumulator) { - baseEach(collection, function(value, key, collection2) { - setter(accumulator, value, iteratee2(value), collection2); - }); - return accumulator; - } - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - function baseAssignValue(object, key, value) { - if (key == "__proto__" && defineProperty) { - defineProperty(object, key, { - "configurable": true, - "enumerable": true, - "value": value, - "writable": true - }); - } else { - object[key] = value; - } - } - function baseAt(object, paths) { - var index = -1, length = paths.length, result2 = Array2(length), skip = object == null; - while (++index < length) { - result2[index] = skip ? undefined2 : get(object, paths[index]); - } - return result2; - } - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined2) { - number = number <= upper ? number : upper; - } - if (lower !== undefined2) { - number = number >= lower ? number : lower; - } - } - return number; - } - function baseClone(value, bitmask, customizer, key, object, stack) { - var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; - if (customizer) { - result2 = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result2 !== undefined2) { - return result2; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray2(value); - if (isArr) { - result2 = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result2); - } - } else { - var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || isFunc && !object) { - result2 = isFlat || isFunc ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result2 = initCloneByTag(value, tag, isDeep); - } - } - stack || (stack = new Stack()); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result2); - if (isSet(value)) { - value.forEach(function(subValue) { - result2.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key2) { - result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); - }); - } - var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; - var props = isArr ? undefined2 : keysFunc(value); - arrayEach(props || value, function(subValue, key2) { - if (props) { - key2 = subValue; - subValue = value[key2]; - } - assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); - }); - return result2; - } - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object2(object); - while (length--) { - var key = props[length], predicate = source[key], value = object[key]; - if (value === undefined2 && !(key in object) || !predicate(value)) { - return false; - } - } - return true; - } - function baseDelay(func, wait, args) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return setTimeout2(function() { - func.apply(undefined2, args); - }, wait); - } - function baseDifference(array, values2, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values2.length; - if (!length) { - return result2; - } - if (iteratee2) { - values2 = arrayMap(values2, baseUnary(iteratee2)); - } - if (comparator) { - includes2 = arrayIncludesWith; - isCommon = false; - } else if (values2.length >= LARGE_ARRAY_SIZE) { - includes2 = cacheHas; - isCommon = false; - values2 = new SetCache(values2); - } - outer: - while (++index < length) { - var value = array[index], computed = iteratee2 == null ? value : iteratee2(value); - value = comparator || value !== 0 ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values2[valuesIndex] === computed) { - continue outer; - } - } - result2.push(value); - } else if (!includes2(values2, computed, comparator)) { - result2.push(value); - } - } - return result2; - } - var baseEach = createBaseEach(baseForOwn); - var baseEachRight = createBaseEach(baseForOwnRight, true); - function baseEvery(collection, predicate) { - var result2 = true; - baseEach(collection, function(value, index, collection2) { - result2 = !!predicate(value, index, collection2); - return result2; - }); - return result2; - } - function baseExtremum(array, iteratee2, comparator) { - var index = -1, length = array.length; - while (++index < length) { - var value = array[index], current = iteratee2(value); - if (current != null && (computed === undefined2 ? current === current && !isSymbol(current) : comparator(current, computed))) { - var computed = current, result2 = value; - } - } - return result2; - } - function baseFill(array, value, start2, end2) { - var length = array.length; - start2 = toInteger(start2); - if (start2 < 0) { - start2 = -start2 > length ? 0 : length + start2; - } - end2 = end2 === undefined2 || end2 > length ? length : toInteger(end2); - if (end2 < 0) { - end2 += length; - } - end2 = start2 > end2 ? 0 : toLength(end2); - while (start2 < end2) { - array[start2++] = value; - } - return array; - } - function baseFilter(collection, predicate) { - var result2 = []; - baseEach(collection, function(value, index, collection2) { - if (predicate(value, index, collection2)) { - result2.push(value); - } - }); - return result2; - } - function baseFlatten(array, depth, predicate, isStrict, result2) { - var index = -1, length = array.length; - predicate || (predicate = isFlattenable); - result2 || (result2 = []); - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - baseFlatten(value, depth - 1, predicate, isStrict, result2); - } else { - arrayPush(result2, value); - } - } else if (!isStrict) { - result2[result2.length] = value; - } - } - return result2; - } - var baseFor = createBaseFor(); - var baseForRight = createBaseFor(true); - function baseForOwn(object, iteratee2) { - return object && baseFor(object, iteratee2, keys); - } - function baseForOwnRight(object, iteratee2) { - return object && baseForRight(object, iteratee2, keys); - } - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction2(object[key]); - }); - } - function baseGet(object, path) { - path = castPath(path, object); - var index = 0, length = path.length; - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return index && index == length ? object : undefined2; - } - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result2 = keysFunc(object); - return isArray2(object) ? result2 : arrayPush(result2, symbolsFunc(object)); - } - function baseGetTag(value) { - if (value == null) { - return value === undefined2 ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object2(value) ? getRawTag(value) : objectToString2(value); - } - function baseGt(value, other) { - return value > other; - } - function baseHas(object, key) { - return object != null && hasOwnProperty2.call(object, key); - } - function baseHasIn(object, key) { - return object != null && key in Object2(object); - } - function baseInRange(number, start2, end2) { - return number >= nativeMin(start2, end2) && number < nativeMax(start2, end2); - } - function baseIntersection(arrays, iteratee2, comparator) { - var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee2) { - array = arrayMap(array, baseUnary(iteratee2)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined2; - } - array = arrays[0]; - var index = -1, seen = caches[0]; - outer: - while (++index < length && result2.length < maxLength) { - var value = array[index], computed = iteratee2 ? iteratee2(value) : value; - value = comparator || value !== 0 ? value : 0; - if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache ? cacheHas(cache, computed) : includes2(arrays[othIndex], computed, comparator))) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result2.push(value); - } - } - return result2; - } - function baseInverter(object, setter, iteratee2, accumulator) { - baseForOwn(object, function(value, key, object2) { - setter(accumulator, iteratee2(value), key, object2); - }); - return accumulator; - } - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined2 : apply(func, object, args); - } - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack()); - return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__"); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack()); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack()); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, length = index, noCustomizer = !customizer; - if (object == null) { - return !length; - } - object = Object2(object); - while (index--) { - var data2 = matchData[index]; - if (noCustomizer && data2[2] ? data2[1] !== object[data2[0]] : !(data2[0] in object)) { - return false; - } - } - while (++index < length) { - data2 = matchData[index]; - var key = data2[0], objValue = object[key], srcValue = data2[1]; - if (noCustomizer && data2[2]) { - if (objValue === undefined2 && !(key in object)) { - return false; - } - } else { - var stack = new Stack(); - if (customizer) { - var result2 = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result2 === undefined2 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) { - return false; - } - } - } - return true; - } - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction2(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - function baseIsTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - function baseIteratee(value) { - if (typeof value == "function") { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == "object") { - return isArray2(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); - } - return property(value); - } - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result2 = []; - for (var key in Object2(object)) { - if (hasOwnProperty2.call(object, key) && key != "constructor") { - result2.push(key); - } - } - return result2; - } - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), result2 = []; - for (var key in object) { - if (!(key == "constructor" && (isProto || !hasOwnProperty2.call(object, key)))) { - result2.push(key); - } - } - return result2; - } - function baseLt(value, other) { - return value < other; - } - function baseMap(collection, iteratee2) { - var index = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value, key, collection2) { - result2[++index] = iteratee2(value, key, collection2); - }); - return result2; - } - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return objValue === undefined2 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack()); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } else { - var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source, stack) : undefined2; - if (newValue === undefined2) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined2; - var isCommon = newValue === undefined2; - if (isCommon) { - var isArr = isArray2(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray2(objValue)) { - newValue = objValue; - } else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } else { - newValue = []; - } - } else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } else if (!isObject(objValue) || isFunction2(objValue)) { - newValue = initCloneObject(srcValue); - } - } else { - isCommon = false; - } - } - if (isCommon) { - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack["delete"](srcValue); - } - assignMergeValue(object, key, newValue); - } - function baseNth(array, n2) { - var length = array.length; - if (!length) { - return; - } - n2 += n2 < 0 ? length : 0; - return isIndex(n2, length) ? array[n2] : undefined2; - } - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee2) { - if (isArray2(iteratee2)) { - return function(value) { - return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2); - }; - } - return iteratee2; - }); - } else { - iteratees = [identity]; - } - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - var result2 = baseMap(collection, function(value, key, collection2) { - var criteria = arrayMap(iteratees, function(iteratee2) { - return iteratee2(value); - }); - return { "criteria": criteria, "index": ++index, "value": value }; - }); - return baseSortBy(result2, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } - function basePickBy(object, paths, predicate) { - var index = -1, length = paths.length, result2 = {}; - while (++index < length) { - var path = paths[index], value = baseGet(object, path); - if (predicate(value, path)) { - baseSet(result2, castPath(path, object), value); - } - } - return result2; - } - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - function basePullAll(array, values2, iteratee2, comparator) { - var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values2.length, seen = array; - if (array === values2) { - values2 = copyArray(values2); - } - if (iteratee2) { - seen = arrayMap(array, baseUnary(iteratee2)); - } - while (++index < length) { - var fromIndex = 0, value = values2[index], computed = iteratee2 ? iteratee2(value) : value; - while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, lastIndex = length - 1; - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - function baseRange(start2, end2, step, fromRight) { - var index = -1, length = nativeMax(nativeCeil((end2 - start2) / (step || 1)), 0), result2 = Array2(length); - while (length--) { - result2[fromRight ? length : ++index] = start2; - start2 += step; - } - return result2; - } - function baseRepeat(string, n2) { - var result2 = ""; - if (!string || n2 < 1 || n2 > MAX_SAFE_INTEGER) { - return result2; - } - do { - if (n2 % 2) { - result2 += string; - } - n2 = nativeFloor(n2 / 2); - if (n2) { - string += string; - } - } while (n2); - return result2; - } - function baseRest(func, start2) { - return setToString(overRest(func, start2, identity), func + ""); - } - function baseSample(collection) { - return arraySample(values(collection)); - } - function baseSampleSize(collection, n2) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n2, 0, array.length)); - } - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); - var index = -1, length = path.length, lastIndex = length - 1, nested = object; - while (nested != null && ++index < length) { - var key = toKey(path[index]), newValue = value; - if (key === "__proto__" || key === "constructor" || key === "prototype") { - return object; - } - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined2; - if (newValue === undefined2) { - newValue = isObject(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - var baseSetData = !metaMap ? identity : function(func, data2) { - metaMap.set(func, data2); - return func; - }; - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, "toString", { - "configurable": true, - "enumerable": false, - "value": constant(string), - "writable": true - }); - }; - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - function baseSlice(array, start2, end2) { - var index = -1, length = array.length; - if (start2 < 0) { - start2 = -start2 > length ? 0 : length + start2; - } - end2 = end2 > length ? length : end2; - if (end2 < 0) { - end2 += length; - } - length = start2 > end2 ? 0 : end2 - start2 >>> 0; - start2 >>>= 0; - var result2 = Array2(length); - while (++index < length) { - result2[index] = array[index + start2]; - } - return result2; - } - function baseSome(collection, predicate) { - var result2; - baseEach(collection, function(value, index, collection2) { - result2 = predicate(value, index, collection2); - return !result2; - }); - return !!result2; - } - function baseSortedIndex(array, value, retHighest) { - var low = 0, high = array == null ? low : array.length; - if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = low + high >>> 1, computed = array[mid]; - if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } - function baseSortedIndexBy(array, value, iteratee2, retHighest) { - var low = 0, high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - value = iteratee2(value); - var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined2; - while (low < high) { - var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined2, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? computed <= value : computed < value; - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - function baseSortedUniq(array, iteratee2) { - var index = -1, length = array.length, resIndex = 0, result2 = []; - while (++index < length) { - var value = array[index], computed = iteratee2 ? iteratee2(value) : value; - if (!index || !eq(computed, seen)) { - var seen = computed; - result2[resIndex++] = value === 0 ? 0 : value; - } - } - return result2; - } - function baseToNumber(value) { - if (typeof value == "number") { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - function baseToString(value) { - if (typeof value == "string") { - return value; - } - if (isArray2(value)) { - return arrayMap(value, baseToString) + ""; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ""; - } - var result2 = value + ""; - return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; - } - function baseUniq(array, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2; - if (comparator) { - isCommon = false; - includes2 = arrayIncludesWith; - } else if (length >= LARGE_ARRAY_SIZE) { - var set2 = iteratee2 ? null : createSet(array); - if (set2) { - return setToArray(set2); - } - isCommon = false; - includes2 = cacheHas; - seen = new SetCache(); - } else { - seen = iteratee2 ? [] : result2; - } - outer: - while (++index < length) { - var value = array[index], computed = iteratee2 ? iteratee2(value) : value; - value = comparator || value !== 0 ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee2) { - seen.push(computed); - } - result2.push(value); - } else if (!includes2(seen, computed, comparator)) { - if (seen !== result2) { - seen.push(computed); - } - result2.push(value); - } - } - return result2; - } - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, index = fromRight ? length : -1; - while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) { - } - return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); - } - function baseWrapperValue(value, actions) { - var result2 = value; - if (result2 instanceof LazyWrapper) { - result2 = result2.value(); - } - return arrayReduce(actions, function(result3, action) { - return action.func.apply(action.thisArg, arrayPush([result3], action.args)); - }, result2); - } - function baseXor(arrays, iteratee2, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, result2 = Array2(length); - while (++index < length) { - var array = arrays[index], othIndex = -1; - while (++othIndex < length) { - if (othIndex != index) { - result2[index] = baseDifference(result2[index] || array, arrays[othIndex], iteratee2, comparator); - } - } - } - return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); - } - function baseZipObject(props, values2, assignFunc) { - var index = -1, length = props.length, valsLength = values2.length, result2 = {}; - while (++index < length) { - var value = index < valsLength ? values2[index] : undefined2; - assignFunc(result2, props[index], value); - } - return result2; - } - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - function castFunction(value) { - return typeof value == "function" ? value : identity; - } - function castPath(value, object) { - if (isArray2(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } - var castRest = baseRest; - function castSlice(array, start2, end2) { - var length = array.length; - end2 = end2 === undefined2 ? length : end2; - return !start2 && end2 >= length ? array : baseSlice(array, start2, end2); - } - var clearTimeout2 = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - buffer.copy(result2); - return result2; - } - function cloneArrayBuffer(arrayBuffer) { - var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer)); - return result2; - } - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - function cloneRegExp(regexp) { - var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result2.lastIndex = regexp.lastIndex; - return result2; - } - function cloneSymbol(symbol) { - return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {}; - } - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined2, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); - var othIsDefined = other !== undefined2, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); - if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { - return 1; - } - if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { - return -1; - } - } - return 0; - } - function compareMultiple(object, other, orders) { - var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; - while (++index < length) { - var result2 = compareAscending(objCriteria[index], othCriteria[index]); - if (result2) { - if (index >= ordersLength) { - return result2; - } - var order2 = orders[index]; - return result2 * (order2 == "desc" ? -1 : 1); - } - } - return object.index - other.index; - } - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried; - while (++leftIndex < leftLength) { - result2[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result2[leftIndex++] = args[argsIndex++]; - } - return result2; - } - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried; - while (++argsIndex < rangeLength) { - result2[argsIndex] = args[argsIndex]; - } - var offset3 = argsIndex; - while (++rightIndex < rightLength) { - result2[offset3 + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[offset3 + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result2; - } - function copyArray(source, array) { - var index = -1, length = source.length; - array || (array = Array2(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - var index = -1, length = props.length; - while (++index < length) { - var key = props[index]; - var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined2; - if (newValue === undefined2) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - function createAggregator(setter, initializer) { - return function(collection, iteratee2) { - var func = isArray2(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; - return func(collection, setter, getIteratee(iteratee2, 2), accumulator); - }; - } - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined2, guard = length > 2 ? sources[2] : undefined2; - customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined2; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined2 : customizer; - length = 1; - } - object = Object2(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee2) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee2); - } - var length = collection.length, index = fromRight ? length : -1, iterable = Object2(collection); - while (fromRight ? index-- : ++index < length) { - if (iteratee2(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - function createBaseFor(fromRight) { - return function(object, iteratee2, keysFunc) { - var index = -1, iterable = Object2(object), props = keysFunc(object), length = props.length; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee2(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var fn2 = this && this !== root && this instanceof wrapper ? Ctor : func; - return fn2.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined2; - var chr = strSymbols ? strSymbols[0] : string.charAt(0); - var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); - return chr[methodName]() + trailing; - }; - } - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); - }; - } - function createCtor(Ctor) { - return function() { - var args = arguments; - switch (args.length) { - case 0: - return new Ctor(); - case 1: - return new Ctor(args[0]); - case 2: - return new Ctor(args[0], args[1]); - case 3: - return new Ctor(args[0], args[1], args[2]); - case 4: - return new Ctor(args[0], args[1], args[2], args[3]); - case 5: - return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); - return isObject(result2) ? result2 : thisBinding; - }; - } - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index = length, placeholder = getHolder(wrapper); - while (index--) { - args[index] = arguments[index]; - } - var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); - length -= holders.length; - if (length < arity) { - return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined2, args, holders, undefined2, undefined2, arity - length); - } - var fn2 = this && this !== root && this instanceof wrapper ? Ctor : func; - return apply(fn2, this, args); - } - return wrapper; - } - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object2(collection); - if (!isArrayLike(collection)) { - var iteratee2 = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { - return iteratee2(iterable[key], key, iterable); - }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee2 ? collection[index] : index] : undefined2; - }; - } - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == "wrapper") { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - var funcName = getFuncName(func), data2 = funcName == "wrapper" ? getData(func) : undefined2; - if (data2 && isLaziable(data2[0]) && data2[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data2[4].length && data2[9] == 1) { - wrapper = wrapper[getFuncName(data2[0])].apply(wrapper, data2[3]); - } else { - wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); - } - } - return function() { - var args = arguments, value = args[0]; - if (wrapper && args.length == 1 && isArray2(value)) { - return wrapper.plant(value).value(); - } - var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value; - while (++index2 < length) { - result2 = funcs[index2].call(this, result2); - } - return result2; - }; - }); - } - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined2 : createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index = length; - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary2, arity - length); - } - var thisBinding = isBind ? thisArg : this, fn2 = isBindKey ? thisBinding[func] : func; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary2 < length) { - args.length = ary2; - } - if (this && this !== root && this instanceof wrapper) { - fn2 = Ctor || createCtor(fn2); - } - return fn2.apply(thisBinding, args); - } - return wrapper; - } - function createInverter(setter, toIteratee) { - return function(object, iteratee2) { - return baseInverter(object, setter, toIteratee(iteratee2), {}); - }; - } - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result2; - if (value === undefined2 && other === undefined2) { - return defaultValue; - } - if (value !== undefined2) { - result2 = value; - } - if (other !== undefined2) { - if (result2 === undefined2) { - return other; - } - if (typeof value == "string" || typeof other == "string") { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result2 = operator(value, other); - } - return result2; - }; - } - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee2) { - return apply(iteratee2, thisArg, args); - }); - }); - }); - } - function createPadding(length, chars) { - chars = chars === undefined2 ? " " : baseToString(chars); - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); - } - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn2 = this && this !== root && this instanceof wrapper ? Ctor : func; - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn2, isBind ? thisArg : this, args); - } - return wrapper; - } - function createRange(fromRight) { - return function(start2, end2, step) { - if (step && typeof step != "number" && isIterateeCall(start2, end2, step)) { - end2 = step = undefined2; - } - start2 = toFinite(start2); - if (end2 === undefined2) { - end2 = start2; - start2 = 0; - } else { - end2 = toFinite(end2); - } - step = step === undefined2 ? start2 < end2 ? 1 : -1 : toFinite(step); - return baseRange(start2, end2, step, fromRight); - }; - } - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == "string" && typeof other == "string")) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; - } - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined2, newHoldersRight = isCurry ? undefined2 : holders, newPartials = isCurry ? partials : undefined2, newPartialsRight = isCurry ? undefined2 : partials; - bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, - bitmask, - thisArg, - newPartials, - newHolders, - newPartialsRight, - newHoldersRight, - argPos, - ary2, - arity - ]; - var result2 = wrapFunc.apply(undefined2, newData); - if (isLaziable(func)) { - setData(result2, newData); - } - result2.placeholder = placeholder; - return setWrapToString(result2, func, bitmask); - } - function createRound(methodName) { - var func = Math2[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); - pair = (toString(value) + "e").split("e"); - return +(pair[0] + "e" + (+pair[1] - precision)); - } - return func(number); - }; - } - var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values2) { - return new Set2(values2); - }; - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined2; - } - ary2 = ary2 === undefined2 ? ary2 : nativeMax(toInteger(ary2), 0); - arity = arity === undefined2 ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, holdersRight = holders; - partials = holders = undefined2; - } - var data2 = isBindKey ? undefined2 : getData(func); - var newData = [ - func, - bitmask, - thisArg, - partials, - holders, - partialsRight, - holdersRight, - argPos, - ary2, - arity - ]; - if (data2) { - mergeData(newData, data2); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined2 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result2 = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result2 = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result2 = createPartial(func, bitmask, thisArg, partials); - } else { - result2 = createHybrid.apply(undefined2, newData); - } - var setter = data2 ? baseSetData : setData; - return setWrapToString(setter(result2, newData), func, bitmask); - } - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined2 || eq(objValue, objectProto[key]) && !hasOwnProperty2.call(object, key)) { - return srcValue; - } - return objValue; - } - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined2, customDefaultsMerge, stack); - stack["delete"](srcValue); - } - return objValue; - } - function customOmitClone(value) { - return isPlainObject(value) ? undefined2 : value; - } - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined2; - stack.set(array, other); - stack.set(other, array); - while (++index < arrLength) { - var arrValue = array[index], othValue = other[index]; - if (customizer) { - var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined2) { - if (compared) { - continue; - } - result2 = false; - break; - } - if (seen) { - if (!arraySome(other, function(othValue2, othIndex) { - if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result2 = false; - break; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - result2 = false; - break; - } - } - stack["delete"](array); - stack["delete"](other); - return result2; - } - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { - return false; - } - object = object.buffer; - other = other.buffer; - case arrayBufferTag: - if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) { - return false; - } - return true; - case boolTag: - case dateTag: - case numberTag: - return eq(+object, +other); - case errorTag: - return object.name == other.name && object.message == other.message; - case regexpTag: - case stringTag: - return object == other + ""; - case mapTag: - var convert = mapToArray; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - if (object.size != other.size && !isPartial) { - return false; - } - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - stack.set(object, other); - var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack["delete"](object); - return result2; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) { - return false; - } - } - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result2 = true; - stack.set(object, other); - stack.set(other, object); - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], othValue = other[key]; - if (customizer) { - var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); - } - if (!(compared === undefined2 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { - result2 = false; - break; - } - skipCtor || (skipCtor = key == "constructor"); - } - if (result2 && !skipCtor) { - var objCtor = object.constructor, othCtor = other.constructor; - if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { - result2 = false; - } - } - stack["delete"](object); - stack["delete"](other); - return result2; - } - function flatRest(func) { - return setToString(overRest(func, undefined2, flatten), func + ""); - } - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - function getFuncName(func) { - var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty2.call(realNames, result2) ? array.length : 0; - while (length--) { - var data2 = array[length], otherFunc = data2.func; - if (otherFunc == null || otherFunc == func) { - return data2.name; - } - } - return result2; - } - function getHolder(func) { - var object = hasOwnProperty2.call(lodash, "placeholder") ? lodash : func; - return object.placeholder; - } - function getIteratee() { - var result2 = lodash.iteratee || iteratee; - result2 = result2 === iteratee ? baseIteratee : result2; - return arguments.length ? result2(arguments[0], arguments[1]) : result2; - } - function getMapData(map2, key) { - var data2 = map2.__data__; - return isKeyable(key) ? data2[typeof key == "string" ? "string" : "hash"] : data2.map; - } - function getMatchData(object) { - var result2 = keys(object), length = result2.length; - while (length--) { - var key = result2[length], value = object[key]; - result2[length] = [key, value, isStrictComparable(value)]; - } - return result2; - } - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined2; - } - function getRawTag(value) { - var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag]; - try { - value[symToStringTag] = undefined2; - var unmasked = true; - } catch (e) { - } - var result2 = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result2; - } - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object2(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result2 = []; - while (object) { - arrayPush(result2, getSymbols(object)); - object = getPrototype(object); - } - return result2; - }; - var getTag = baseGetTag; - if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) { - getTag = function(value) { - var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : undefined2, ctorString = Ctor ? toSource(Ctor) : ""; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: - return dataViewTag; - case mapCtorString: - return mapTag; - case promiseCtorString: - return promiseTag; - case setCtorString: - return setTag; - case weakMapCtorString: - return weakMapTag; - } - } - return result2; - }; - } - function getView(start2, end2, transforms) { - var index = -1, length = transforms.length; - while (++index < length) { - var data2 = transforms[index], size2 = data2.size; - switch (data2.type) { - case "drop": - start2 += size2; - break; - case "dropRight": - end2 -= size2; - break; - case "take": - end2 = nativeMin(end2, start2 + size2); - break; - case "takeRight": - start2 = nativeMax(start2, end2 - size2); - break; - } - } - return { "start": start2, "end": end2 }; - } - function getWrapDetails(source) { - var match3 = source.match(reWrapDetails); - return match3 ? match3[1].split(reSplitDetails) : []; - } - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - var index = -1, length = path.length, result2 = false; - while (++index < length) { - var key = toKey(path[index]); - if (!(result2 = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result2 || ++index != length) { - return result2; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && (isArray2(object) || isArguments(object)); - } - function initCloneArray(array) { - var length = array.length, result2 = new array.constructor(length); - if (length && typeof array[0] == "string" && hasOwnProperty2.call(array, "index")) { - result2.index = array.index; - result2.input = array.input; - } - return result2; - } - function initCloneObject(object) { - return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {}; - } - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - case boolTag: - case dateTag: - return new Ctor(+object); - case dataViewTag: - return cloneDataView(object, isDeep); - case float32Tag: - case float64Tag: - case int8Tag: - case int16Tag: - case int32Tag: - case uint8Tag: - case uint8ClampedTag: - case uint16Tag: - case uint32Tag: - return cloneTypedArray(object, isDeep); - case mapTag: - return new Ctor(); - case numberTag: - case stringTag: - return new Ctor(object); - case regexpTag: - return cloneRegExp(object); - case setTag: - return new Ctor(); - case symbolTag: - return cloneSymbol(object); - } - } - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; - details = details.join(length > 2 ? ", " : " "); - return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); - } - function isFlattenable(value) { - return isArray2(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); - } - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); - } - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { - return eq(object[index], value); - } - return false; - } - function isKey(value, object) { - if (isArray2(value)) { - return false; - } - var type = typeof value; - if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object2(object); - } - function isKeyable(value) { - var type = typeof value; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; - } - function isLaziable(func) { - var funcName = getFuncName(func), other = lodash[funcName]; - if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data2 = getData(other); - return !!data2 && func === data2[0]; - } - function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; - } - var isMaskable = coreJsData ? isFunction2 : stubFalse; - function isPrototype(value) { - var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value === proto; - } - function isStrictComparable(value) { - return value === value && !isObject(value); - } - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && (srcValue !== undefined2 || key in Object2(object)); - }; - } - function memoizeCapped(func) { - var result2 = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - var cache = result2.cache; - return result2; - } - function mergeData(data2, source) { - var bitmask = data2[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data2[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; - if (!(isCommon || isCombo)) { - return data2; - } - if (srcBitmask & WRAP_BIND_FLAG) { - data2[2] = source[2]; - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - var value = source[3]; - if (value) { - var partials = data2[3]; - data2[3] = partials ? composeArgs(partials, value, source[4]) : value; - data2[4] = partials ? replaceHolders(data2[3], PLACEHOLDER) : source[4]; - } - value = source[5]; - if (value) { - partials = data2[5]; - data2[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data2[6] = partials ? replaceHolders(data2[5], PLACEHOLDER) : source[6]; - } - value = source[7]; - if (value) { - data2[7] = value; - } - if (srcBitmask & WRAP_ARY_FLAG) { - data2[8] = data2[8] == null ? source[8] : nativeMin(data2[8], source[8]); - } - if (data2[9] == null) { - data2[9] = source[9]; - } - data2[0] = source[0]; - data2[1] = newBitmask; - return data2; - } - function nativeKeysIn(object) { - var result2 = []; - if (object != null) { - for (var key in Object2(object)) { - result2.push(key); - } - } - return result2; - } - function objectToString2(value) { - return nativeObjectToString.call(value); - } - function overRest(func, start2, transform2) { - start2 = nativeMax(start2 === undefined2 ? func.length - 1 : start2, 0); - return function() { - var args = arguments, index = -1, length = nativeMax(args.length - start2, 0), array = Array2(length); - while (++index < length) { - array[index] = args[start2 + index]; - } - index = -1; - var otherArgs = Array2(start2 + 1); - while (++index < start2) { - otherArgs[index] = args[index]; - } - otherArgs[start2] = transform2(array); - return apply(func, this, otherArgs); - }; - } - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - function reorder(array, indexes) { - var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined2; - } - return array; - } - function safeGet(object, key) { - if (key === "constructor" && typeof object[key] === "function") { - return; - } - if (key == "__proto__") { - return; - } - return object[key]; - } - var setData = shortOut(baseSetData); - var setTimeout2 = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - var setToString = shortOut(baseSetToString); - function setWrapToString(wrapper, reference2, bitmask) { - var source = reference2 + ""; - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - function shortOut(func) { - var count = 0, lastCalled = 0; - return function() { - var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined2, arguments); - }; - } - function shuffleSelf(array, size2) { - var index = -1, length = array.length, lastIndex = length - 1; - size2 = size2 === undefined2 ? length : size2; - while (++index < size2) { - var rand = baseRandom(index, lastIndex), value = array[rand]; - array[rand] = array[index]; - array[index] = value; - } - array.length = size2; - return array; - } - var stringToPath = memoizeCapped(function(string) { - var result2 = []; - if (string.charCodeAt(0) === 46) { - result2.push(""); - } - string.replace(rePropName, function(match3, number, quote, subString) { - result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match3); - }); - return result2; - }); - function toKey(value) { - if (typeof value == "string" || isSymbol(value)) { - return value; - } - var result2 = value + ""; - return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; - } - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) { - } - try { - return func + ""; - } catch (e) { - } - } - return ""; - } - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = "_." + pair[0]; - if (bitmask & pair[1] && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result2.__actions__ = copyArray(wrapper.__actions__); - result2.__index__ = wrapper.__index__; - result2.__values__ = wrapper.__values__; - return result2; - } - function chunk(array, size2, guard) { - if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined2) { - size2 = 1; - } else { - size2 = nativeMax(toInteger(size2), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size2 < 1) { - return []; - } - var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); - while (index < length) { - result2[resIndex++] = baseSlice(array, index, index += size2); - } - return result2; - } - function compact(array) { - var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = []; - while (++index < length) { - var value = array[index]; - if (value) { - result2[resIndex++] = value; - } - } - return result2; - } - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array2(length - 1), array = arguments[0], index = length; - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray2(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - var difference = baseRest(function(array, values2) { - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; - }); - var differenceBy = baseRest(function(array, values2) { - var iteratee2 = last(values2); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : []; - }); - var differenceWith = baseRest(function(array, values2) { - var comparator = last(values2); - if (isArrayLikeObject(comparator)) { - comparator = undefined2; - } - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined2, comparator) : []; - }); - function drop(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - return baseSlice(array, n2 < 0 ? 0 : n2, length); - } - function dropRight(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - n2 = length - n2; - return baseSlice(array, 0, n2 < 0 ? 0 : n2); - } - function dropRightWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; - } - function dropWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; - } - function fill(array, value, start2, end2) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start2 && typeof start2 != "number" && isIterateeCall(array, value, start2)) { - start2 = 0; - end2 = length; - } - return baseFill(array, value, start2, end2); - } - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined2) { - index = toInteger(fromIndex); - index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined2 ? 1 : toInteger(depth); - return baseFlatten(array, depth); - } - function fromPairs(pairs) { - var index = -1, length = pairs == null ? 0 : pairs.length, result2 = {}; - while (++index < length) { - var pair = pairs[index]; - result2[pair[0]] = pair[1]; - } - return result2; - } - function head(array) { - return array && array.length ? array[0] : undefined2; - } - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value, index); - } - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; - }); - var intersectionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - if (iteratee2 === last(mapped)) { - iteratee2 = undefined2; - } else { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : []; - }); - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - comparator = typeof comparator == "function" ? comparator : undefined2; - if (comparator) { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined2, comparator) : []; - }); - function join(array, separator) { - return array == null ? "" : nativeJoin.call(array, separator); - } - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined2; - } - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined2) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); - } - function nth(array, n2) { - return array && array.length ? baseNth(array, toInteger(n2)) : undefined2; - } - var pull = baseRest(pullAll); - function pullAll(array, values2) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array; - } - function pullAllBy(array, values2, iteratee2) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array; - } - function pullAllWith(array, values2, comparator) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined2, comparator) : array; - } - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes); - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - return result2; - }); - function remove(array, predicate) { - var result2 = []; - if (!(array && array.length)) { - return result2; - } - var index = -1, indexes = [], length = array.length; - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result2.push(value); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result2; - } - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - function slice(array, start2, end2) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end2 && typeof end2 != "number" && isIterateeCall(array, start2, end2)) { - start2 = 0; - end2 = length; - } else { - start2 = start2 == null ? 0 : toInteger(start2); - end2 = end2 === undefined2 ? length : toInteger(end2); - } - return baseSlice(array, start2, end2); - } - function sortedIndex(array, value) { - return baseSortedIndex(array, value); - } - function sortedIndexBy(array, value, iteratee2) { - return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2)); - } - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } - } - return -1; - } - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); - } - function sortedLastIndexBy(array, value, iteratee2) { - return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2), true); - } - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; - } - } - return -1; - } - function sortedUniq(array) { - return array && array.length ? baseSortedUniq(array) : []; - } - function sortedUniqBy(array, iteratee2) { - return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : []; - } - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - function take(array, n2, guard) { - if (!(array && array.length)) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - return baseSlice(array, 0, n2 < 0 ? 0 : n2); - } - function takeRight(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - n2 = length - n2; - return baseSlice(array, n2 < 0 ? 0 : n2, length); - } - function takeRightWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; - } - function takeWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; - } - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - var unionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)); - }); - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined2; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined2, comparator); - }); - function uniq(array) { - return array && array.length ? baseUniq(array) : []; - } - function uniqBy(array, iteratee2) { - return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : []; - } - function uniqWith(array, comparator) { - comparator = typeof comparator == "function" ? comparator : undefined2; - return array && array.length ? baseUniq(array, undefined2, comparator) : []; - } - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - function unzipWith(array, iteratee2) { - if (!(array && array.length)) { - return []; - } - var result2 = unzip(array); - if (iteratee2 == null) { - return result2; - } - return arrayMap(result2, function(group) { - return apply(iteratee2, undefined2, group); - }); - } - var without = baseRest(function(array, values2) { - return isArrayLikeObject(array) ? baseDifference(array, values2) : []; - }); - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - var xorBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2)); - }); - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined2; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined2, comparator); - }); - var zip = baseRest(unzip); - function zipObject(props, values2) { - return baseZipObject(props || [], values2 || [], assignValue); - } - function zipObjectDeep(props, values2) { - return baseZipObject(props || [], values2 || [], baseSet); - } - var zipWith = baseRest(function(arrays) { - var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined2; - iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined2; - return unzipWith(arrays, iteratee2); - }); - function chain(value) { - var result2 = lodash(value); - result2.__chain__ = true; - return result2; - } - function tap(value, interceptor) { - interceptor(value); - return value; - } - function thru(value, interceptor) { - return interceptor(value); - } - var wrapperAt = flatRest(function(paths) { - var length = paths.length, start2 = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { - return baseAt(object, paths); - }; - if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start2)) { - return this.thru(interceptor); - } - value = value.slice(start2, +start2 + (length ? 1 : 0)); - value.__actions__.push({ - "func": thru, - "args": [interceptor], - "thisArg": undefined2 - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined2); - } - return array; - }); - }); - function wrapperChain() { - return chain(this); - } - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - function wrapperNext() { - if (this.__values__ === undefined2) { - this.__values__ = toArray(this.value()); - } - var done = this.__index__ >= this.__values__.length, value = done ? undefined2 : this.__values__[this.__index__++]; - return { "done": done, "value": value }; - } - function wrapperToIterator() { - return this; - } - function wrapperPlant(value) { - var result2, parent2 = this; - while (parent2 instanceof baseLodash) { - var clone4 = wrapperClone(parent2); - clone4.__index__ = 0; - clone4.__values__ = undefined2; - if (result2) { - previous.__wrapped__ = clone4; - } else { - result2 = clone4; - } - var previous = clone4; - parent2 = parent2.__wrapped__; - } - previous.__wrapped__ = value; - return result2; - } - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - "func": thru, - "args": [reverse], - "thisArg": undefined2 - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - var countBy = createAggregator(function(result2, value, key) { - if (hasOwnProperty2.call(result2, key)) { - ++result2[key]; - } else { - baseAssignValue(result2, key, 1); - } - }); - function every(collection, predicate, guard) { - var func = isArray2(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined2; - } - return func(collection, getIteratee(predicate, 3)); - } - function filter(collection, predicate) { - var func = isArray2(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - var find = createFind(findIndex); - var findLast = createFind(findLastIndex); - function flatMap(collection, iteratee2) { - return baseFlatten(map(collection, iteratee2), 1); - } - function flatMapDeep(collection, iteratee2) { - return baseFlatten(map(collection, iteratee2), INFINITY); - } - function flatMapDepth(collection, iteratee2, depth) { - depth = depth === undefined2 ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee2), depth); - } - function forEach(collection, iteratee2) { - var func = isArray2(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee2, 3)); - } - function forEachRight(collection, iteratee2) { - var func = isArray2(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee2, 3)); - } - var groupBy = createAggregator(function(result2, value, key) { - if (hasOwnProperty2.call(result2, key)) { - result2[key].push(value); - } else { - baseAssignValue(result2, key, [value]); - } - }); - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString2(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; - } - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, isFunc = typeof path == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value) { - result2[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); - return result2; - }); - var keyBy = createAggregator(function(result2, value, key) { - baseAssignValue(result2, key, value); - }); - function map(collection, iteratee2) { - var func = isArray2(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee2, 3)); - } - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray2(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined2 : orders; - if (!isArray2(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - var partition = createAggregator(function(result2, value, key) { - result2[key ? 0 : 1].push(value); - }, function() { - return [[], []]; - }); - function reduce(collection, iteratee2, accumulator) { - var func = isArray2(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); - } - function reduceRight(collection, iteratee2, accumulator) { - var func = isArray2(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); - } - function reject(collection, predicate) { - var func = isArray2(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - function sample(collection) { - var func = isArray2(collection) ? arraySample : baseSample; - return func(collection); - } - function sampleSize(collection, n2, guard) { - if (guard ? isIterateeCall(collection, n2, guard) : n2 === undefined2) { - n2 = 1; - } else { - n2 = toInteger(n2); - } - var func = isArray2(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n2); - } - function shuffle(collection) { - var func = isArray2(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString2(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - function some(collection, predicate, guard) { - var func = isArray2(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined2; - } - return func(collection, getIteratee(predicate, 3)); - } - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - var now2 = ctxNow || function() { - return root.Date.now(); - }; - function after(n2, func) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger(n2); - return function() { - if (--n2 < 1) { - return func.apply(this, arguments); - } - }; - } - function ary(func, n2, guard) { - n2 = guard ? undefined2 : n2; - n2 = func && n2 == null ? func.length : n2; - return createWrap(func, WRAP_ARY_FLAG, undefined2, undefined2, undefined2, undefined2, n2); - } - function before(n2, func) { - var result2; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger(n2); - return function() { - if (--n2 > 0) { - result2 = func.apply(this, arguments); - } - if (n2 <= 1) { - func = undefined2; - } - return result2; - }; - } - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - function curry(func, arity, guard) { - arity = guard ? undefined2 : arity; - var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); - result2.placeholder = curry.placeholder; - return result2; - } - function curryRight(func, arity, guard) { - arity = guard ? undefined2 : arity; - var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); - result2.placeholder = curryRight.placeholder; - return result2; - } - function debounce2(func, wait, options) { - var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = "maxWait" in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - function invokeFunc(time) { - var args = lastArgs, thisArg = lastThis; - lastArgs = lastThis = undefined2; - lastInvokeTime = time; - result2 = func.apply(thisArg, args); - return result2; - } - function leadingEdge(time) { - lastInvokeTime = time; - timerId = setTimeout2(timerExpired, wait); - return leading ? invokeFunc(time) : result2; - } - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; - return lastCallTime === undefined2 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - function timerExpired() { - var time = now2(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - timerId = setTimeout2(timerExpired, remainingWait(time)); - } - function trailingEdge(time) { - timerId = undefined2; - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined2; - return result2; - } - function cancel() { - if (timerId !== undefined2) { - clearTimeout2(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined2; - } - function flush() { - return timerId === undefined2 ? result2 : trailingEdge(now2()); - } - function debounced() { - var time = now2(), isInvoking = shouldInvoke(time); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - if (isInvoking) { - if (timerId === undefined2) { - return leadingEdge(lastCallTime); - } - if (maxing) { - clearTimeout2(timerId); - timerId = setTimeout2(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined2) { - timerId = setTimeout2(timerExpired, wait); - } - return result2; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - function flip2(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - function memoize(func, resolver) { - if (typeof func != "function" || resolver != null && typeof resolver != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; - if (cache.has(key)) { - return cache.get(key); - } - var result2 = func.apply(this, args); - memoized.cache = cache.set(key, result2) || cache; - return result2; - }; - memoized.cache = new (memoize.Cache || MapCache)(); - return memoized; - } - memoize.Cache = MapCache; - function negate(predicate) { - if (typeof predicate != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: - return !predicate.call(this); - case 1: - return !predicate.call(this, args[0]); - case 2: - return !predicate.call(this, args[0], args[1]); - case 3: - return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - function once(func) { - return before(2, func); - } - var overArgs = castRest(function(func, transforms) { - transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, length = nativeMin(args.length, funcsLength); - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply(func, this, args); - }); - }); - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined2, partials, holders); - }); - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined2, partials, holders); - }); - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined2, undefined2, undefined2, indexes); - }); - function rest(func, start2) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start2 = start2 === undefined2 ? start2 : toInteger(start2); - return baseRest(func, start2); - } - function spread(func, start2) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start2 = start2 == null ? 0 : nativeMax(toInteger(start2), 0); - return baseRest(function(args) { - var array = args[start2], otherArgs = castSlice(args, 0, start2); - if (array) { - arrayPush(otherArgs, array); - } - return apply(func, this, otherArgs); - }); - } - function throttle(func, wait, options) { - var leading = true, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (isObject(options)) { - leading = "leading" in options ? !!options.leading : leading; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - return debounce2(func, wait, { - "leading": leading, - "maxWait": wait, - "trailing": trailing - }); - } - function unary(func) { - return ary(func, 1); - } - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray2(value) ? value : [value]; - } - function clone3(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - function cloneWith(value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); - } - function eq(value, other) { - return value === other || value !== value && other !== other; - } - var gt = createRelationalOperation(baseGt); - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); - var isArguments = baseIsArguments(function() { - return arguments; - }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); - }; - var isArray2 = Array2.isArray; - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction2(value); - } - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - function isBoolean(value) { - return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag; - } - var isBuffer = nativeIsBuffer || stubFalse; - var isDate2 = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - function isElement2(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && (isArray2(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty2.call(value, key)) { - return false; - } - } - return true; - } - function isEqual(value, other) { - return baseIsEqual(value, other); - } - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - var result2 = customizer ? customizer(value, other) : undefined2; - return result2 === undefined2 ? baseIsEqual(value, other, undefined2, customizer) : !!result2; - } - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); - } - function isFinite(value) { - return typeof value == "number" && nativeIsFinite(value); - } - function isFunction2(value) { - if (!isObject(value)) { - return false; - } - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - function isInteger2(value) { - return typeof value == "number" && value == toInteger(value); - } - function isLength(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; - } - function isObject(value) { - var type = typeof value; - return value != null && (type == "object" || type == "function"); - } - function isObjectLike(value) { - return value != null && typeof value == "object"; - } - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - function isNaN2(value) { - return isNumber2(value) && value != +value; - } - function isNative(value) { - if (isMaskable(value)) { - throw new Error2(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - function isNull(value) { - return value === null; - } - function isNil(value) { - return value == null; - } - function isNumber2(value) { - return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag; - } - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty2.call(proto, "constructor") && proto.constructor; - return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; - } - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - function isSafeInteger(value) { - return isInteger2(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; - } - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - function isString2(value) { - return typeof value == "string" || !isArray2(value) && isObjectLike(value) && baseGetTag(value) == stringTag; - } - function isSymbol(value) { - return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; - } - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - function isUndefined2(value) { - return value === undefined2; - } - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - var lt = createRelationalOperation(baseLt); - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString2(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; - return func(value); - } - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = value < 0 ? -1 : 1; - return sign * MAX_INTEGER; - } - return value === value ? value : 0; - } - function toInteger(value) { - var result2 = toFinite(value), remainder = result2 % 1; - return result2 === result2 ? remainder ? result2 - remainder : result2 : 0; - } - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - function toNumber(value) { - if (typeof value == "number") { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == "function" ? value.valueOf() : value; - value = isObject(other) ? other + "" : other; - } - if (typeof value != "string") { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; - } - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - function toSafeInteger(value) { - return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0; - } - function toString(value) { - return value == null ? "" : baseToString(value); - } - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty2.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); - var at = flatRest(baseAt); - function create(prototype, properties) { - var result2 = baseCreate(prototype); - return properties == null ? result2 : baseAssign(result2, properties); - } - var defaults = baseRest(function(object, sources) { - object = Object2(object); - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined2; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - if (value === undefined2 || eq(value, objectProto[key]) && !hasOwnProperty2.call(object, key)) { - object[key] = source[key]; - } - } - } - return object; - }); - var defaultsDeep = baseRest(function(args) { - args.push(undefined2, customDefaultsMerge); - return apply(mergeWith, undefined2, args); - }); - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - function forIn(object, iteratee2) { - return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn); - } - function forInRight(object, iteratee2) { - return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn); - } - function forOwn(object, iteratee2) { - return object && baseForOwn(object, getIteratee(iteratee2, 3)); - } - function forOwnRight(object, iteratee2) { - return object && baseForOwnRight(object, getIteratee(iteratee2, 3)); - } - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); - } - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - function get(object, path, defaultValue) { - var result2 = object == null ? undefined2 : baseGet(object, path); - return result2 === undefined2 ? defaultValue : result2; - } - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - var invert = createInverter(function(result2, value, key) { - if (value != null && typeof value.toString != "function") { - value = nativeObjectToString.call(value); - } - result2[value] = key; - }, constant(identity)); - var invertBy = createInverter(function(result2, value, key) { - if (value != null && typeof value.toString != "function") { - value = nativeObjectToString.call(value); - } - if (hasOwnProperty2.call(result2, value)) { - result2[value].push(key); - } else { - result2[value] = [key]; - } - }, getIteratee); - var invoke = baseRest(baseInvoke); - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - function mapKeys(object, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object, function(value, key, object2) { - baseAssignValue(result2, iteratee2(value, key, object2), value); - }); - return result2; - } - function mapValues(object, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object, function(value, key, object2) { - baseAssignValue(result2, key, iteratee2(value, key, object2)); - }); - return result2; - } - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - var omit = flatRest(function(object, paths) { - var result2 = {}; - if (object == null) { - return result2; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result2); - if (isDeep) { - result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result2, paths[length]); - } - return result2; - }); - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - var pick2 = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } - function result(object, path, defaultValue) { - path = castPath(path, object); - var index = -1, length = path.length; - if (!length) { - length = 1; - object = undefined2; - } - while (++index < length) { - var value = object == null ? undefined2 : object[toKey(path[index])]; - if (value === undefined2) { - index = length; - value = defaultValue; - } - object = isFunction2(value) ? value.call(object) : value; - } - return object; - } - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); - } - function setWith(object, path, value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return object == null ? object : baseSet(object, path, value, customizer); - } - var toPairs = createToPairs(keys); - var toPairsIn = createToPairs(keysIn); - function transform(object, iteratee2, accumulator) { - var isArr = isArray2(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); - iteratee2 = getIteratee(iteratee2, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor() : []; - } else if (isObject(object)) { - accumulator = isFunction2(Ctor) ? baseCreate(getPrototype(object)) : {}; - } else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object2) { - return iteratee2(accumulator, value, index, object2); - }); - return accumulator; - } - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); - } - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - function clamp(number, lower, upper) { - if (upper === undefined2) { - upper = lower; - lower = undefined2; - } - if (upper !== undefined2) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined2) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - function inRange(number, start2, end2) { - start2 = toFinite(start2); - if (end2 === undefined2) { - end2 = start2; - start2 = 0; - } else { - end2 = toFinite(end2); - } - number = toNumber(number); - return baseInRange(number, start2, end2); - } - function random(lower, upper, floating) { - if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined2; - } - if (floating === undefined2) { - if (typeof upper == "boolean") { - floating = upper; - upper = undefined2; - } else if (typeof lower == "boolean") { - floating = lower; - lower = undefined2; - } - } - if (lower === undefined2 && upper === undefined2) { - lower = 0; - upper = 1; - } else { - lower = toFinite(lower); - if (upper === undefined2) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); - } - return baseRandom(lower, upper); - } - var camelCase = createCompounder(function(result2, word, index) { - word = word.toLowerCase(); - return result2 + (index ? capitalize(word) : word); - }); - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); - } - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - var length = string.length; - position = position === undefined2 ? length : baseClamp(toInteger(position), 0, length); - var end2 = position; - position -= target.length; - return position >= 0 && string.slice(position, end2) == target; - } - function escape2(string) { - string = toString(string); - return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; - } - function escapeRegExp2(string) { - string = toString(string); - return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; - } - var kebabCase = createCompounder(function(result2, word, index) { - return result2 + (index ? "-" : "") + word.toLowerCase(); - }); - var lowerCase2 = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + word.toLowerCase(); - }); - var lowerFirst = createCaseFirst("toLowerCase"); - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); - } - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? string + createPadding(length - strLength, chars) : string; - } - function padStart2(string, length, chars) { - string = toString(string); - length = toInteger(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? createPadding(length - strLength, chars) + string : string; - } - function parseInt2(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); - } - function repeat(string, n2, guard) { - if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined2) { - n2 = 1; - } else { - n2 = toInteger(n2); - } - return baseRepeat(toString(string), n2); - } - function replace2() { - var args = arguments, string = toString(args[0]); - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - var snakeCase = createCompounder(function(result2, word, index) { - return result2 + (index ? "_" : "") + word.toLowerCase(); - }); - function split(string, separator, limit) { - if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { - separator = limit = undefined2; - } - limit = limit === undefined2 ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - var startCase = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + upperFirst(word); - }); - function startsWith(string, target, position) { - string = toString(string); - position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - function template(string, options, guard) { - var settings = lodash.templateSettings; - if (guard && isIterateeCall(string, options, guard)) { - options = undefined2; - } - string = toString(string); - options = assignInWith({}, options, settings, customDefaultsAssignIn); - var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); - var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; - var reDelimiters = RegExp2((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); - var sourceURL = "//# sourceURL=" + (hasOwnProperty2.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; - string.replace(reDelimiters, function(match3, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset3) { - interpolateValue || (interpolateValue = esTemplateValue); - source += string.slice(index, offset3).replace(reUnescapedString, escapeStringChar); - if (escapeValue) { - isEscaping = true; - source += "' +\n__e(" + escapeValue + ") +\n'"; - } - if (evaluateValue) { - isEvaluating = true; - source += "';\n" + evaluateValue + ";\n__p += '"; - } - if (interpolateValue) { - source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; - } - index = offset3 + match3.length; - return match3; - }); - source += "';\n"; - var variable = hasOwnProperty2.call(options, "variable") && options.variable; - if (!variable) { - source = "with (obj) {\n" + source + "\n}\n"; - } else if (reForbiddenIdentifierChars.test(variable)) { - throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT); - } - source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); - source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; - var result2 = attempt(function() { - return Function2(importsKeys, sourceURL + "return " + source).apply(undefined2, importsValues); - }); - result2.source = source; - if (isError(result2)) { - throw result2; - } - return result2; - } - function toLower(value) { - return toString(value).toLowerCase(); - } - function toUpper(value) { - return toString(value).toUpperCase(); - } - function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined2)) { - return baseTrim(string); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start2 = charsStartIndex(strSymbols, chrSymbols), end2 = charsEndIndex(strSymbols, chrSymbols) + 1; - return castSlice(strSymbols, start2, end2).join(""); - } - function trimEnd(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined2)) { - return string.slice(0, trimmedEndIndex(string) + 1); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), end2 = charsEndIndex(strSymbols, stringToArray(chars)) + 1; - return castSlice(strSymbols, 0, end2).join(""); - } - function trimStart(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined2)) { - return string.replace(reTrimStart, ""); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), start2 = charsStartIndex(strSymbols, stringToArray(chars)); - return castSlice(strSymbols, start2).join(""); - } - function truncate2(string, options) { - var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; - if (isObject(options)) { - var separator = "separator" in options ? options.separator : separator; - length = "length" in options ? toInteger(options.length) : length; - omission = "omission" in options ? baseToString(options.omission) : omission; - } - string = toString(string); - var strLength = string.length; - if (hasUnicode(string)) { - var strSymbols = stringToArray(string); - strLength = strSymbols.length; - } - if (length >= strLength) { - return string; - } - var end2 = length - stringSize(omission); - if (end2 < 1) { - return omission; - } - var result2 = strSymbols ? castSlice(strSymbols, 0, end2).join("") : string.slice(0, end2); - if (separator === undefined2) { - return result2 + omission; - } - if (strSymbols) { - end2 += result2.length - end2; - } - if (isRegExp(separator)) { - if (string.slice(end2).search(separator)) { - var match3, substring = result2; - if (!separator.global) { - separator = RegExp2(separator.source, toString(reFlags.exec(separator)) + "g"); - } - separator.lastIndex = 0; - while (match3 = separator.exec(substring)) { - var newEnd = match3.index; - } - result2 = result2.slice(0, newEnd === undefined2 ? end2 : newEnd); - } - } else if (string.indexOf(baseToString(separator), end2) != end2) { - var index = result2.lastIndexOf(separator); - if (index > -1) { - result2 = result2.slice(0, index); - } - } - return result2 + omission; - } - function unescape(string) { - string = toString(string); - return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; - } - var upperCase2 = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + word.toUpperCase(); - }); - var upperFirst = createCaseFirst("toUpperCase"); - function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined2 : pattern; - if (pattern === undefined2) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; - } - var attempt = baseRest(function(func, args) { - try { - return apply(func, undefined2, args); - } catch (e) { - return isError(e) ? e : new Error2(e); - } - }); - var bindAll = flatRest(function(object, methodNames) { - arrayEach(methodNames, function(key) { - key = toKey(key); - baseAssignValue(object, key, bind(object[key], object)); - }); - return object; - }); - function cond(pairs) { - var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); - pairs = !length ? [] : arrayMap(pairs, function(pair) { - if (typeof pair[1] != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return [toIteratee(pair[0]), pair[1]]; - }); - return baseRest(function(args) { - var index = -1; - while (++index < length) { - var pair = pairs[index]; - if (apply(pair[0], this, args)) { - return apply(pair[1], this, args); - } - } - }); - } - function conforms(source) { - return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); - } - function constant(value) { - return function() { - return value; - }; - } - function defaultTo(value, defaultValue) { - return value == null || value !== value ? defaultValue : value; - } - var flow = createFlow(); - var flowRight = createFlow(true); - function identity(value) { - return value; - } - function iteratee(func) { - return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)); - } - function matches(source) { - return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); - } - function matchesProperty(path, srcValue) { - return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); - } - var method = baseRest(function(path, args) { - return function(object) { - return baseInvoke(object, path, args); - }; - }); - var methodOf = baseRest(function(object, args) { - return function(path) { - return baseInvoke(object, path, args); - }; - }); - function mixin(object, source, options) { - var props = keys(source), methodNames = baseFunctions(source, props); - if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { - options = source; - source = object; - object = this; - methodNames = baseFunctions(source, keys(source)); - } - var chain2 = !(isObject(options) && "chain" in options) || !!options.chain, isFunc = isFunction2(object); - arrayEach(methodNames, function(methodName) { - var func = source[methodName]; - object[methodName] = func; - if (isFunc) { - object.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain2 || chainAll) { - var result2 = object(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__); - actions.push({ "func": func, "args": arguments, "thisArg": object }); - result2.__chain__ = chainAll; - return result2; - } - return func.apply(object, arrayPush([this.value()], arguments)); - }; - } - }); - return object; - } - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } - function noop() { - } - function nthArg(n2) { - n2 = toInteger(n2); - return baseRest(function(args) { - return baseNth(args, n2); - }); - } - var over = createOver(arrayMap); - var overEvery = createOver(arrayEvery); - var overSome = createOver(arraySome); - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - function propertyOf(object) { - return function(path) { - return object == null ? undefined2 : baseGet(object, path); - }; - } - var range = createRange(); - var rangeRight = createRange(true); - function stubArray() { - return []; - } - function stubFalse() { - return false; - } - function stubObject() { - return {}; - } - function stubString() { - return ""; - } - function stubTrue() { - return true; - } - function times(n2, iteratee2) { - n2 = toInteger(n2); - if (n2 < 1 || n2 > MAX_SAFE_INTEGER) { - return []; - } - var index = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH); - iteratee2 = getIteratee(iteratee2); - n2 -= MAX_ARRAY_LENGTH; - var result2 = baseTimes(length, iteratee2); - while (++index < n2) { - iteratee2(index); - } - return result2; - } - function toPath(value) { - if (isArray2(value)) { - return arrayMap(value, toKey); - } - return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); - } - function uniqueId(prefix) { - var id = ++idCounter; - return toString(prefix) + id; - } - var add = createMathOperation(function(augend, addend) { - return augend + addend; - }, 0); - var ceil = createRound("ceil"); - var divide = createMathOperation(function(dividend, divisor) { - return dividend / divisor; - }, 1); - var floor = createRound("floor"); - function max2(array) { - return array && array.length ? baseExtremum(array, identity, baseGt) : undefined2; - } - function maxBy(array, iteratee2) { - return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined2; - } - function mean(array) { - return baseMean(array, identity); - } - function meanBy(array, iteratee2) { - return baseMean(array, getIteratee(iteratee2, 2)); - } - function min2(array) { - return array && array.length ? baseExtremum(array, identity, baseLt) : undefined2; - } - function minBy(array, iteratee2) { - return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined2; - } - var multiply = createMathOperation(function(multiplier, multiplicand) { - return multiplier * multiplicand; - }, 1); - var round2 = createRound("round"); - var subtract = createMathOperation(function(minuend, subtrahend) { - return minuend - subtrahend; - }, 0); - function sum(array) { - return array && array.length ? baseSum(array, identity) : 0; - } - function sumBy(array, iteratee2) { - return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0; - } - lodash.after = after; - lodash.ary = ary; - lodash.assign = assign; - lodash.assignIn = assignIn; - lodash.assignInWith = assignInWith; - lodash.assignWith = assignWith; - lodash.at = at; - lodash.before = before; - lodash.bind = bind; - lodash.bindAll = bindAll; - lodash.bindKey = bindKey; - lodash.castArray = castArray; - lodash.chain = chain; - lodash.chunk = chunk; - lodash.compact = compact; - lodash.concat = concat; - lodash.cond = cond; - lodash.conforms = conforms; - lodash.constant = constant; - lodash.countBy = countBy; - lodash.create = create; - lodash.curry = curry; - lodash.curryRight = curryRight; - lodash.debounce = debounce2; - lodash.defaults = defaults; - lodash.defaultsDeep = defaultsDeep; - lodash.defer = defer; - lodash.delay = delay; - lodash.difference = difference; - lodash.differenceBy = differenceBy; - lodash.differenceWith = differenceWith; - lodash.drop = drop; - lodash.dropRight = dropRight; - lodash.dropRightWhile = dropRightWhile; - lodash.dropWhile = dropWhile; - lodash.fill = fill; - lodash.filter = filter; - lodash.flatMap = flatMap; - lodash.flatMapDeep = flatMapDeep; - lodash.flatMapDepth = flatMapDepth; - lodash.flatten = flatten; - lodash.flattenDeep = flattenDeep; - lodash.flattenDepth = flattenDepth; - lodash.flip = flip2; - lodash.flow = flow; - lodash.flowRight = flowRight; - lodash.fromPairs = fromPairs; - lodash.functions = functions; - lodash.functionsIn = functionsIn; - lodash.groupBy = groupBy; - lodash.initial = initial; - lodash.intersection = intersection; - lodash.intersectionBy = intersectionBy; - lodash.intersectionWith = intersectionWith; - lodash.invert = invert; - lodash.invertBy = invertBy; - lodash.invokeMap = invokeMap; - lodash.iteratee = iteratee; - lodash.keyBy = keyBy; - lodash.keys = keys; - lodash.keysIn = keysIn; - lodash.map = map; - lodash.mapKeys = mapKeys; - lodash.mapValues = mapValues; - lodash.matches = matches; - lodash.matchesProperty = matchesProperty; - lodash.memoize = memoize; - lodash.merge = merge; - lodash.mergeWith = mergeWith; - lodash.method = method; - lodash.methodOf = methodOf; - lodash.mixin = mixin; - lodash.negate = negate; - lodash.nthArg = nthArg; - lodash.omit = omit; - lodash.omitBy = omitBy; - lodash.once = once; - lodash.orderBy = orderBy; - lodash.over = over; - lodash.overArgs = overArgs; - lodash.overEvery = overEvery; - lodash.overSome = overSome; - lodash.partial = partial; - lodash.partialRight = partialRight; - lodash.partition = partition; - lodash.pick = pick2; - lodash.pickBy = pickBy; - lodash.property = property; - lodash.propertyOf = propertyOf; - lodash.pull = pull; - lodash.pullAll = pullAll; - lodash.pullAllBy = pullAllBy; - lodash.pullAllWith = pullAllWith; - lodash.pullAt = pullAt; - lodash.range = range; - lodash.rangeRight = rangeRight; - lodash.rearg = rearg; - lodash.reject = reject; - lodash.remove = remove; - lodash.rest = rest; - lodash.reverse = reverse; - lodash.sampleSize = sampleSize; - lodash.set = set; - lodash.setWith = setWith; - lodash.shuffle = shuffle; - lodash.slice = slice; - lodash.sortBy = sortBy; - lodash.sortedUniq = sortedUniq; - lodash.sortedUniqBy = sortedUniqBy; - lodash.split = split; - lodash.spread = spread; - lodash.tail = tail; - lodash.take = take; - lodash.takeRight = takeRight; - lodash.takeRightWhile = takeRightWhile; - lodash.takeWhile = takeWhile; - lodash.tap = tap; - lodash.throttle = throttle; - lodash.thru = thru; - lodash.toArray = toArray; - lodash.toPairs = toPairs; - lodash.toPairsIn = toPairsIn; - lodash.toPath = toPath; - lodash.toPlainObject = toPlainObject; - lodash.transform = transform; - lodash.unary = unary; - lodash.union = union; - lodash.unionBy = unionBy; - lodash.unionWith = unionWith; - lodash.uniq = uniq; - lodash.uniqBy = uniqBy; - lodash.uniqWith = uniqWith; - lodash.unset = unset; - lodash.unzip = unzip; - lodash.unzipWith = unzipWith; - lodash.update = update; - lodash.updateWith = updateWith; - lodash.values = values; - lodash.valuesIn = valuesIn; - lodash.without = without; - lodash.words = words; - lodash.wrap = wrap; - lodash.xor = xor; - lodash.xorBy = xorBy; - lodash.xorWith = xorWith; - lodash.zip = zip; - lodash.zipObject = zipObject; - lodash.zipObjectDeep = zipObjectDeep; - lodash.zipWith = zipWith; - lodash.entries = toPairs; - lodash.entriesIn = toPairsIn; - lodash.extend = assignIn; - lodash.extendWith = assignInWith; - mixin(lodash, lodash); - lodash.add = add; - lodash.attempt = attempt; - lodash.camelCase = camelCase; - lodash.capitalize = capitalize; - lodash.ceil = ceil; - lodash.clamp = clamp; - lodash.clone = clone3; - lodash.cloneDeep = cloneDeep; - lodash.cloneDeepWith = cloneDeepWith; - lodash.cloneWith = cloneWith; - lodash.conformsTo = conformsTo; - lodash.deburr = deburr; - lodash.defaultTo = defaultTo; - lodash.divide = divide; - lodash.endsWith = endsWith; - lodash.eq = eq; - lodash.escape = escape2; - lodash.escapeRegExp = escapeRegExp2; - lodash.every = every; - lodash.find = find; - lodash.findIndex = findIndex; - lodash.findKey = findKey; - lodash.findLast = findLast; - lodash.findLastIndex = findLastIndex; - lodash.findLastKey = findLastKey; - lodash.floor = floor; - lodash.forEach = forEach; - lodash.forEachRight = forEachRight; - lodash.forIn = forIn; - lodash.forInRight = forInRight; - lodash.forOwn = forOwn; - lodash.forOwnRight = forOwnRight; - lodash.get = get; - lodash.gt = gt; - lodash.gte = gte; - lodash.has = has; - lodash.hasIn = hasIn; - lodash.head = head; - lodash.identity = identity; - lodash.includes = includes; - lodash.indexOf = indexOf; - lodash.inRange = inRange; - lodash.invoke = invoke; - lodash.isArguments = isArguments; - lodash.isArray = isArray2; - lodash.isArrayBuffer = isArrayBuffer; - lodash.isArrayLike = isArrayLike; - lodash.isArrayLikeObject = isArrayLikeObject; - lodash.isBoolean = isBoolean; - lodash.isBuffer = isBuffer; - lodash.isDate = isDate2; - lodash.isElement = isElement2; - lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual; - lodash.isEqualWith = isEqualWith; - lodash.isError = isError; - lodash.isFinite = isFinite; - lodash.isFunction = isFunction2; - lodash.isInteger = isInteger2; - lodash.isLength = isLength; - lodash.isMap = isMap; - lodash.isMatch = isMatch; - lodash.isMatchWith = isMatchWith; - lodash.isNaN = isNaN2; - lodash.isNative = isNative; - lodash.isNil = isNil; - lodash.isNull = isNull; - lodash.isNumber = isNumber2; - lodash.isObject = isObject; - lodash.isObjectLike = isObjectLike; - lodash.isPlainObject = isPlainObject; - lodash.isRegExp = isRegExp; - lodash.isSafeInteger = isSafeInteger; - lodash.isSet = isSet; - lodash.isString = isString2; - lodash.isSymbol = isSymbol; - lodash.isTypedArray = isTypedArray; - lodash.isUndefined = isUndefined2; - lodash.isWeakMap = isWeakMap; - lodash.isWeakSet = isWeakSet; - lodash.join = join; - lodash.kebabCase = kebabCase; - lodash.last = last; - lodash.lastIndexOf = lastIndexOf; - lodash.lowerCase = lowerCase2; - lodash.lowerFirst = lowerFirst; - lodash.lt = lt; - lodash.lte = lte; - lodash.max = max2; - lodash.maxBy = maxBy; - lodash.mean = mean; - lodash.meanBy = meanBy; - lodash.min = min2; - lodash.minBy = minBy; - lodash.stubArray = stubArray; - lodash.stubFalse = stubFalse; - lodash.stubObject = stubObject; - lodash.stubString = stubString; - lodash.stubTrue = stubTrue; - lodash.multiply = multiply; - lodash.nth = nth; - lodash.noConflict = noConflict; - lodash.noop = noop; - lodash.now = now2; - lodash.pad = pad; - lodash.padEnd = padEnd; - lodash.padStart = padStart2; - lodash.parseInt = parseInt2; - lodash.random = random; - lodash.reduce = reduce; - lodash.reduceRight = reduceRight; - lodash.repeat = repeat; - lodash.replace = replace2; - lodash.result = result; - lodash.round = round2; - lodash.runInContext = runInContext2; - lodash.sample = sample; - lodash.size = size; - lodash.snakeCase = snakeCase; - lodash.some = some; - lodash.sortedIndex = sortedIndex; - lodash.sortedIndexBy = sortedIndexBy; - lodash.sortedIndexOf = sortedIndexOf; - lodash.sortedLastIndex = sortedLastIndex; - lodash.sortedLastIndexBy = sortedLastIndexBy; - lodash.sortedLastIndexOf = sortedLastIndexOf; - lodash.startCase = startCase; - lodash.startsWith = startsWith; - lodash.subtract = subtract; - lodash.sum = sum; - lodash.sumBy = sumBy; - lodash.template = template; - lodash.times = times; - lodash.toFinite = toFinite; - lodash.toInteger = toInteger; - lodash.toLength = toLength; - lodash.toLower = toLower; - lodash.toNumber = toNumber; - lodash.toSafeInteger = toSafeInteger; - lodash.toString = toString; - lodash.toUpper = toUpper; - lodash.trim = trim; - lodash.trimEnd = trimEnd; - lodash.trimStart = trimStart; - lodash.truncate = truncate2; - lodash.unescape = unescape; - lodash.uniqueId = uniqueId; - lodash.upperCase = upperCase2; - lodash.upperFirst = upperFirst; - lodash.each = forEach; - lodash.eachRight = forEachRight; - lodash.first = head; - mixin(lodash, function() { - var source = {}; - baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty2.call(lodash.prototype, methodName)) { - source[methodName] = func; - } - }); - return source; - }(), { "chain": false }); - lodash.VERSION = VERSION; - arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { - lodash[methodName].placeholder = lodash; - }); - arrayEach(["drop", "take"], function(methodName, index) { - LazyWrapper.prototype[methodName] = function(n2) { - n2 = n2 === undefined2 ? 1 : nativeMax(toInteger(n2), 0); - var result2 = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone(); - if (result2.__filtered__) { - result2.__takeCount__ = nativeMin(n2, result2.__takeCount__); - } else { - result2.__views__.push({ - "size": nativeMin(n2, MAX_ARRAY_LENGTH), - "type": methodName + (result2.__dir__ < 0 ? "Right" : "") - }); - } - return result2; - }; - LazyWrapper.prototype[methodName + "Right"] = function(n2) { - return this.reverse()[methodName](n2).reverse(); - }; - }); - arrayEach(["filter", "map", "takeWhile"], function(methodName, index) { - var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; - LazyWrapper.prototype[methodName] = function(iteratee2) { - var result2 = this.clone(); - result2.__iteratees__.push({ - "iteratee": getIteratee(iteratee2, 3), - "type": type - }); - result2.__filtered__ = result2.__filtered__ || isFilter; - return result2; - }; - }); - arrayEach(["head", "last"], function(methodName, index) { - var takeName = "take" + (index ? "Right" : ""); - LazyWrapper.prototype[methodName] = function() { - return this[takeName](1).value()[0]; - }; - }); - arrayEach(["initial", "tail"], function(methodName, index) { - var dropName = "drop" + (index ? "" : "Right"); - LazyWrapper.prototype[methodName] = function() { - return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); - }; - }); - LazyWrapper.prototype.compact = function() { - return this.filter(identity); - }; - LazyWrapper.prototype.find = function(predicate) { - return this.filter(predicate).head(); - }; - LazyWrapper.prototype.findLast = function(predicate) { - return this.reverse().find(predicate); - }; - LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { - if (typeof path == "function") { - return new LazyWrapper(this); - } - return this.map(function(value) { - return baseInvoke(value, path, args); - }); - }); - LazyWrapper.prototype.reject = function(predicate) { - return this.filter(negate(getIteratee(predicate))); - }; - LazyWrapper.prototype.slice = function(start2, end2) { - start2 = toInteger(start2); - var result2 = this; - if (result2.__filtered__ && (start2 > 0 || end2 < 0)) { - return new LazyWrapper(result2); - } - if (start2 < 0) { - result2 = result2.takeRight(-start2); - } else if (start2) { - result2 = result2.drop(start2); - } - if (end2 !== undefined2) { - end2 = toInteger(end2); - result2 = end2 < 0 ? result2.dropRight(-end2) : result2.take(end2 - start2); - } - return result2; - }; - LazyWrapper.prototype.takeRightWhile = function(predicate) { - return this.reverse().takeWhile(predicate).reverse(); - }; - LazyWrapper.prototype.toArray = function() { - return this.take(MAX_ARRAY_LENGTH); - }; - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); - if (!lodashFunc) { - return; - } - lodash.prototype[methodName] = function() { - var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray2(value); - var interceptor = function(value2) { - var result3 = lodashFunc.apply(lodash, arrayPush([value2], args)); - return isTaker && chainAll ? result3[0] : result3; - }; - if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) { - isLazy = useLazy = false; - } - var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; - if (!retUnwrapped && useLazy) { - value = onlyLazy ? value : new LazyWrapper(this); - var result2 = func.apply(value, args); - result2.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined2 }); - return new LodashWrapper(result2, chainAll); - } - if (isUnwrapped && onlyLazy) { - return func.apply(this, args); - } - result2 = this.thru(interceptor); - return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2; - }; - }); - arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { - var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); - lodash.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value = this.value(); - return func.apply(isArray2(value) ? value : [], args); - } - return this[chainName](function(value2) { - return func.apply(isArray2(value2) ? value2 : [], args); - }); - }; - }); - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var lodashFunc = lodash[methodName]; - if (lodashFunc) { - var key = lodashFunc.name + ""; - if (!hasOwnProperty2.call(realNames, key)) { - realNames[key] = []; - } - realNames[key].push({ "name": methodName, "func": lodashFunc }); - } - }); - realNames[createHybrid(undefined2, WRAP_BIND_KEY_FLAG).name] = [{ - "name": "wrapper", - "func": undefined2 - }]; - LazyWrapper.prototype.clone = lazyClone; - LazyWrapper.prototype.reverse = lazyReverse; - LazyWrapper.prototype.value = lazyValue; - lodash.prototype.at = wrapperAt; - lodash.prototype.chain = wrapperChain; - lodash.prototype.commit = wrapperCommit; - lodash.prototype.next = wrapperNext; - lodash.prototype.plant = wrapperPlant; - lodash.prototype.reverse = wrapperReverse; - lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - lodash.prototype.first = lodash.prototype.head; - if (symIterator) { - lodash.prototype[symIterator] = wrapperToIterator; - } - return lodash; - }; - var _ = runInContext(); - if (typeof define == "function" && typeof define.amd == "object" && define.amd) { - root._ = _; - define(function() { - return _; - }); - } else if (freeModule) { - (freeModule.exports = _)._ = _; - freeExports._ = _; - } else { - root._ = _; - } - }).call(exports); - } -}); - -// node_modules/diff-match-patch/index.js -var require_diff_match_patch = __commonJS({ - "node_modules/diff-match-patch/index.js"(exports, module2) { - var diff_match_patch2 = function() { - this.Diff_Timeout = 1; - this.Diff_EditCost = 4; - this.Match_Threshold = 0.5; - this.Match_Distance = 1e3; - this.Patch_DeleteThreshold = 0.5; - this.Patch_Margin = 4; - this.Match_MaxBits = 32; - }; - var DIFF_DELETE = -1; - var DIFF_INSERT = 1; - var DIFF_EQUAL = 0; - diff_match_patch2.Diff = function(op, text) { - return [op, text]; - }; - diff_match_patch2.prototype.diff_main = function(text1, text2, opt_checklines, opt_deadline) { - if (typeof opt_deadline == "undefined") { - if (this.Diff_Timeout <= 0) { - opt_deadline = Number.MAX_VALUE; - } else { - opt_deadline = new Date().getTime() + this.Diff_Timeout * 1e3; - } - } - var deadline = opt_deadline; - if (text1 == null || text2 == null) { - throw new Error("Null input. (diff_main)"); - } - if (text1 == text2) { - if (text1) { - return [new diff_match_patch2.Diff(DIFF_EQUAL, text1)]; - } - return []; - } - if (typeof opt_checklines == "undefined") { - opt_checklines = true; - } - var checklines = opt_checklines; - var commonlength = this.diff_commonPrefix(text1, text2); - var commonprefix = text1.substring(0, commonlength); - text1 = text1.substring(commonlength); - text2 = text2.substring(commonlength); - commonlength = this.diff_commonSuffix(text1, text2); - var commonsuffix = text1.substring(text1.length - commonlength); - text1 = text1.substring(0, text1.length - commonlength); - text2 = text2.substring(0, text2.length - commonlength); - var diffs = this.diff_compute_(text1, text2, checklines, deadline); - if (commonprefix) { - diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, commonprefix)); - } - if (commonsuffix) { - diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, commonsuffix)); - } - this.diff_cleanupMerge(diffs); - return diffs; - }; - diff_match_patch2.prototype.diff_compute_ = function(text1, text2, checklines, deadline) { - var diffs; - if (!text1) { - return [new diff_match_patch2.Diff(DIFF_INSERT, text2)]; - } - if (!text2) { - return [new diff_match_patch2.Diff(DIFF_DELETE, text1)]; - } - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - var i = longtext.indexOf(shorttext); - if (i != -1) { - diffs = [ - new diff_match_patch2.Diff(DIFF_INSERT, longtext.substring(0, i)), - new diff_match_patch2.Diff(DIFF_EQUAL, shorttext), - new diff_match_patch2.Diff(DIFF_INSERT, longtext.substring(i + shorttext.length)) - ]; - if (text1.length > text2.length) { - diffs[0][0] = diffs[2][0] = DIFF_DELETE; - } - return diffs; - } - if (shorttext.length == 1) { - return [ - new diff_match_patch2.Diff(DIFF_DELETE, text1), - new diff_match_patch2.Diff(DIFF_INSERT, text2) - ]; - } - var hm = this.diff_halfMatch_(text1, text2); - if (hm) { - var text1_a = hm[0]; - var text1_b = hm[1]; - var text2_a = hm[2]; - var text2_b = hm[3]; - var mid_common = hm[4]; - var diffs_a = this.diff_main(text1_a, text2_a, checklines, deadline); - var diffs_b = this.diff_main(text1_b, text2_b, checklines, deadline); - return diffs_a.concat([new diff_match_patch2.Diff(DIFF_EQUAL, mid_common)], diffs_b); - } - if (checklines && text1.length > 100 && text2.length > 100) { - return this.diff_lineMode_(text1, text2, deadline); - } - return this.diff_bisect_(text1, text2, deadline); - }; - diff_match_patch2.prototype.diff_lineMode_ = function(text1, text2, deadline) { - var a = this.diff_linesToChars_(text1, text2); - text1 = a.chars1; - text2 = a.chars2; - var linearray = a.lineArray; - var diffs = this.diff_main(text1, text2, false, deadline); - this.diff_charsToLines_(diffs, linearray); - this.diff_cleanupSemantic(diffs); - diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, "")); - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ""; - var text_insert = ""; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - break; - case DIFF_EQUAL: - if (count_delete >= 1 && count_insert >= 1) { - diffs.splice(pointer - count_delete - count_insert, count_delete + count_insert); - pointer = pointer - count_delete - count_insert; - var subDiff = this.diff_main(text_delete, text_insert, false, deadline); - for (var j = subDiff.length - 1; j >= 0; j--) { - diffs.splice(pointer, 0, subDiff[j]); - } - pointer = pointer + subDiff.length; - } - count_insert = 0; - count_delete = 0; - text_delete = ""; - text_insert = ""; - break; - } - pointer++; - } - diffs.pop(); - return diffs; - }; - diff_match_patch2.prototype.diff_bisect_ = function(text1, text2, deadline) { - var text1_length = text1.length; - var text2_length = text2.length; - var max_d = Math.ceil((text1_length + text2_length) / 2); - var v_offset = max_d; - var v_length = 2 * max_d; - var v1 = new Array(v_length); - var v2 = new Array(v_length); - for (var x = 0; x < v_length; x++) { - v1[x] = -1; - v2[x] = -1; - } - v1[v_offset + 1] = 0; - v2[v_offset + 1] = 0; - var delta = text1_length - text2_length; - var front = delta % 2 != 0; - var k1start = 0; - var k1end = 0; - var k2start = 0; - var k2end = 0; - for (var d = 0; d < max_d; d++) { - if (new Date().getTime() > deadline) { - break; - } - for (var k1 = -d + k1start; k1 <= d - k1end; k1 += 2) { - var k1_offset = v_offset + k1; - var x1; - if (k1 == -d || k1 != d && v1[k1_offset - 1] < v1[k1_offset + 1]) { - x1 = v1[k1_offset + 1]; - } else { - x1 = v1[k1_offset - 1] + 1; - } - var y1 = x1 - k1; - while (x1 < text1_length && y1 < text2_length && text1.charAt(x1) == text2.charAt(y1)) { - x1++; - y1++; - } - v1[k1_offset] = x1; - if (x1 > text1_length) { - k1end += 2; - } else if (y1 > text2_length) { - k1start += 2; - } else if (front) { - var k2_offset = v_offset + delta - k1; - if (k2_offset >= 0 && k2_offset < v_length && v2[k2_offset] != -1) { - var x2 = text1_length - v2[k2_offset]; - if (x1 >= x2) { - return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); - } - } - } - } - for (var k2 = -d + k2start; k2 <= d - k2end; k2 += 2) { - var k2_offset = v_offset + k2; - var x2; - if (k2 == -d || k2 != d && v2[k2_offset - 1] < v2[k2_offset + 1]) { - x2 = v2[k2_offset + 1]; - } else { - x2 = v2[k2_offset - 1] + 1; - } - var y2 = x2 - k2; - while (x2 < text1_length && y2 < text2_length && text1.charAt(text1_length - x2 - 1) == text2.charAt(text2_length - y2 - 1)) { - x2++; - y2++; - } - v2[k2_offset] = x2; - if (x2 > text1_length) { - k2end += 2; - } else if (y2 > text2_length) { - k2start += 2; - } else if (!front) { - var k1_offset = v_offset + delta - k2; - if (k1_offset >= 0 && k1_offset < v_length && v1[k1_offset] != -1) { - var x1 = v1[k1_offset]; - var y1 = v_offset + x1 - k1_offset; - x2 = text1_length - x2; - if (x1 >= x2) { - return this.diff_bisectSplit_(text1, text2, x1, y1, deadline); - } - } - } - } - } - return [ - new diff_match_patch2.Diff(DIFF_DELETE, text1), - new diff_match_patch2.Diff(DIFF_INSERT, text2) - ]; - }; - diff_match_patch2.prototype.diff_bisectSplit_ = function(text1, text2, x, y, deadline) { - var text1a = text1.substring(0, x); - var text2a = text2.substring(0, y); - var text1b = text1.substring(x); - var text2b = text2.substring(y); - var diffs = this.diff_main(text1a, text2a, false, deadline); - var diffsb = this.diff_main(text1b, text2b, false, deadline); - return diffs.concat(diffsb); - }; - diff_match_patch2.prototype.diff_linesToChars_ = function(text1, text2) { - var lineArray = []; - var lineHash = {}; - lineArray[0] = ""; - function diff_linesToCharsMunge_(text) { - var chars = ""; - var lineStart = 0; - var lineEnd = -1; - var lineArrayLength = lineArray.length; - while (lineEnd < text.length - 1) { - lineEnd = text.indexOf("\n", lineStart); - if (lineEnd == -1) { - lineEnd = text.length - 1; - } - var line = text.substring(lineStart, lineEnd + 1); - if (lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : lineHash[line] !== void 0) { - chars += String.fromCharCode(lineHash[line]); - } else { - if (lineArrayLength == maxLines) { - line = text.substring(lineStart); - lineEnd = text.length; - } - chars += String.fromCharCode(lineArrayLength); - lineHash[line] = lineArrayLength; - lineArray[lineArrayLength++] = line; - } - lineStart = lineEnd + 1; - } - return chars; - } - var maxLines = 4e4; - var chars1 = diff_linesToCharsMunge_(text1); - maxLines = 65535; - var chars2 = diff_linesToCharsMunge_(text2); - return { chars1, chars2, lineArray }; - }; - diff_match_patch2.prototype.diff_charsToLines_ = function(diffs, lineArray) { - for (var i = 0; i < diffs.length; i++) { - var chars = diffs[i][1]; - var text = []; - for (var j = 0; j < chars.length; j++) { - text[j] = lineArray[chars.charCodeAt(j)]; - } - diffs[i][1] = text.join(""); - } - }; - diff_match_patch2.prototype.diff_commonPrefix = function(text1, text2) { - if (!text1 || !text2 || text1.charAt(0) != text2.charAt(0)) { - return 0; - } - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerstart = 0; - while (pointermin < pointermid) { - if (text1.substring(pointerstart, pointermid) == text2.substring(pointerstart, pointermid)) { - pointermin = pointermid; - pointerstart = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; - }; - diff_match_patch2.prototype.diff_commonSuffix = function(text1, text2) { - if (!text1 || !text2 || text1.charAt(text1.length - 1) != text2.charAt(text2.length - 1)) { - return 0; - } - var pointermin = 0; - var pointermax = Math.min(text1.length, text2.length); - var pointermid = pointermax; - var pointerend = 0; - while (pointermin < pointermid) { - if (text1.substring(text1.length - pointermid, text1.length - pointerend) == text2.substring(text2.length - pointermid, text2.length - pointerend)) { - pointermin = pointermid; - pointerend = pointermin; - } else { - pointermax = pointermid; - } - pointermid = Math.floor((pointermax - pointermin) / 2 + pointermin); - } - return pointermid; - }; - diff_match_patch2.prototype.diff_commonOverlap_ = function(text1, text2) { - var text1_length = text1.length; - var text2_length = text2.length; - if (text1_length == 0 || text2_length == 0) { - return 0; - } - if (text1_length > text2_length) { - text1 = text1.substring(text1_length - text2_length); - } else if (text1_length < text2_length) { - text2 = text2.substring(0, text1_length); - } - var text_length = Math.min(text1_length, text2_length); - if (text1 == text2) { - return text_length; - } - var best = 0; - var length = 1; - while (true) { - var pattern = text1.substring(text_length - length); - var found = text2.indexOf(pattern); - if (found == -1) { - return best; - } - length += found; - if (found == 0 || text1.substring(text_length - length) == text2.substring(0, length)) { - best = length; - length++; - } - } - }; - diff_match_patch2.prototype.diff_halfMatch_ = function(text1, text2) { - if (this.Diff_Timeout <= 0) { - return null; - } - var longtext = text1.length > text2.length ? text1 : text2; - var shorttext = text1.length > text2.length ? text2 : text1; - if (longtext.length < 4 || shorttext.length * 2 < longtext.length) { - return null; - } - var dmp = this; - function diff_halfMatchI_(longtext2, shorttext2, i) { - var seed = longtext2.substring(i, i + Math.floor(longtext2.length / 4)); - var j = -1; - var best_common = ""; - var best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b; - while ((j = shorttext2.indexOf(seed, j + 1)) != -1) { - var prefixLength = dmp.diff_commonPrefix(longtext2.substring(i), shorttext2.substring(j)); - var suffixLength = dmp.diff_commonSuffix(longtext2.substring(0, i), shorttext2.substring(0, j)); - if (best_common.length < suffixLength + prefixLength) { - best_common = shorttext2.substring(j - suffixLength, j) + shorttext2.substring(j, j + prefixLength); - best_longtext_a = longtext2.substring(0, i - suffixLength); - best_longtext_b = longtext2.substring(i + prefixLength); - best_shorttext_a = shorttext2.substring(0, j - suffixLength); - best_shorttext_b = shorttext2.substring(j + prefixLength); - } - } - if (best_common.length * 2 >= longtext2.length) { - return [ - best_longtext_a, - best_longtext_b, - best_shorttext_a, - best_shorttext_b, - best_common - ]; - } else { - return null; - } - } - var hm1 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 4)); - var hm2 = diff_halfMatchI_(longtext, shorttext, Math.ceil(longtext.length / 2)); - var hm; - if (!hm1 && !hm2) { - return null; - } else if (!hm2) { - hm = hm1; - } else if (!hm1) { - hm = hm2; - } else { - hm = hm1[4].length > hm2[4].length ? hm1 : hm2; - } - var text1_a, text1_b, text2_a, text2_b; - if (text1.length > text2.length) { - text1_a = hm[0]; - text1_b = hm[1]; - text2_a = hm[2]; - text2_b = hm[3]; - } else { - text2_a = hm[0]; - text2_b = hm[1]; - text1_a = hm[2]; - text1_b = hm[3]; - } - var mid_common = hm[4]; - return [text1_a, text1_b, text2_a, text2_b, mid_common]; - }; - diff_match_patch2.prototype.diff_cleanupSemantic = function(diffs) { - var changes = false; - var equalities = []; - var equalitiesLength = 0; - var lastEquality = null; - var pointer = 0; - var length_insertions1 = 0; - var length_deletions1 = 0; - var length_insertions2 = 0; - var length_deletions2 = 0; - while (pointer < diffs.length) { - if (diffs[pointer][0] == DIFF_EQUAL) { - equalities[equalitiesLength++] = pointer; - length_insertions1 = length_insertions2; - length_deletions1 = length_deletions2; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = diffs[pointer][1]; - } else { - if (diffs[pointer][0] == DIFF_INSERT) { - length_insertions2 += diffs[pointer][1].length; - } else { - length_deletions2 += diffs[pointer][1].length; - } - if (lastEquality && lastEquality.length <= Math.max(length_insertions1, length_deletions1) && lastEquality.length <= Math.max(length_insertions2, length_deletions2)) { - diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch2.Diff(DIFF_DELETE, lastEquality)); - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - equalitiesLength--; - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - length_insertions1 = 0; - length_deletions1 = 0; - length_insertions2 = 0; - length_deletions2 = 0; - lastEquality = null; - changes = true; - } - } - pointer++; - } - if (changes) { - this.diff_cleanupMerge(diffs); - } - this.diff_cleanupSemanticLossless(diffs); - pointer = 1; - while (pointer < diffs.length) { - if (diffs[pointer - 1][0] == DIFF_DELETE && diffs[pointer][0] == DIFF_INSERT) { - var deletion = diffs[pointer - 1][1]; - var insertion = diffs[pointer][1]; - var overlap_length1 = this.diff_commonOverlap_(deletion, insertion); - var overlap_length2 = this.diff_commonOverlap_(insertion, deletion); - if (overlap_length1 >= overlap_length2) { - if (overlap_length1 >= deletion.length / 2 || overlap_length1 >= insertion.length / 2) { - diffs.splice(pointer, 0, new diff_match_patch2.Diff(DIFF_EQUAL, insertion.substring(0, overlap_length1))); - diffs[pointer - 1][1] = deletion.substring(0, deletion.length - overlap_length1); - diffs[pointer + 1][1] = insertion.substring(overlap_length1); - pointer++; - } - } else { - if (overlap_length2 >= deletion.length / 2 || overlap_length2 >= insertion.length / 2) { - diffs.splice(pointer, 0, new diff_match_patch2.Diff(DIFF_EQUAL, deletion.substring(0, overlap_length2))); - diffs[pointer - 1][0] = DIFF_INSERT; - diffs[pointer - 1][1] = insertion.substring(0, insertion.length - overlap_length2); - diffs[pointer + 1][0] = DIFF_DELETE; - diffs[pointer + 1][1] = deletion.substring(overlap_length2); - pointer++; - } - } - pointer++; - } - pointer++; - } - }; - diff_match_patch2.prototype.diff_cleanupSemanticLossless = function(diffs) { - function diff_cleanupSemanticScore_(one, two) { - if (!one || !two) { - return 6; - } - var char1 = one.charAt(one.length - 1); - var char2 = two.charAt(0); - var nonAlphaNumeric1 = char1.match(diff_match_patch2.nonAlphaNumericRegex_); - var nonAlphaNumeric2 = char2.match(diff_match_patch2.nonAlphaNumericRegex_); - var whitespace1 = nonAlphaNumeric1 && char1.match(diff_match_patch2.whitespaceRegex_); - var whitespace2 = nonAlphaNumeric2 && char2.match(diff_match_patch2.whitespaceRegex_); - var lineBreak1 = whitespace1 && char1.match(diff_match_patch2.linebreakRegex_); - var lineBreak2 = whitespace2 && char2.match(diff_match_patch2.linebreakRegex_); - var blankLine1 = lineBreak1 && one.match(diff_match_patch2.blanklineEndRegex_); - var blankLine2 = lineBreak2 && two.match(diff_match_patch2.blanklineStartRegex_); - if (blankLine1 || blankLine2) { - return 5; - } else if (lineBreak1 || lineBreak2) { - return 4; - } else if (nonAlphaNumeric1 && !whitespace1 && whitespace2) { - return 3; - } else if (whitespace1 || whitespace2) { - return 2; - } else if (nonAlphaNumeric1 || nonAlphaNumeric2) { - return 1; - } - return 0; - } - var pointer = 1; - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { - var equality1 = diffs[pointer - 1][1]; - var edit = diffs[pointer][1]; - var equality2 = diffs[pointer + 1][1]; - var commonOffset = this.diff_commonSuffix(equality1, edit); - if (commonOffset) { - var commonString = edit.substring(edit.length - commonOffset); - equality1 = equality1.substring(0, equality1.length - commonOffset); - edit = commonString + edit.substring(0, edit.length - commonOffset); - equality2 = commonString + equality2; - } - var bestEquality1 = equality1; - var bestEdit = edit; - var bestEquality2 = equality2; - var bestScore = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - while (edit.charAt(0) === equality2.charAt(0)) { - equality1 += edit.charAt(0); - edit = edit.substring(1) + equality2.charAt(0); - equality2 = equality2.substring(1); - var score = diff_cleanupSemanticScore_(equality1, edit) + diff_cleanupSemanticScore_(edit, equality2); - if (score >= bestScore) { - bestScore = score; - bestEquality1 = equality1; - bestEdit = edit; - bestEquality2 = equality2; - } - } - if (diffs[pointer - 1][1] != bestEquality1) { - if (bestEquality1) { - diffs[pointer - 1][1] = bestEquality1; - } else { - diffs.splice(pointer - 1, 1); - pointer--; - } - diffs[pointer][1] = bestEdit; - if (bestEquality2) { - diffs[pointer + 1][1] = bestEquality2; - } else { - diffs.splice(pointer + 1, 1); - pointer--; - } - } - } - pointer++; - } - }; - diff_match_patch2.nonAlphaNumericRegex_ = /[^a-zA-Z0-9]/; - diff_match_patch2.whitespaceRegex_ = /\s/; - diff_match_patch2.linebreakRegex_ = /[\r\n]/; - diff_match_patch2.blanklineEndRegex_ = /\n\r?\n$/; - diff_match_patch2.blanklineStartRegex_ = /^\r?\n\r?\n/; - diff_match_patch2.prototype.diff_cleanupEfficiency = function(diffs) { - var changes = false; - var equalities = []; - var equalitiesLength = 0; - var lastEquality = null; - var pointer = 0; - var pre_ins = false; - var pre_del = false; - var post_ins = false; - var post_del = false; - while (pointer < diffs.length) { - if (diffs[pointer][0] == DIFF_EQUAL) { - if (diffs[pointer][1].length < this.Diff_EditCost && (post_ins || post_del)) { - equalities[equalitiesLength++] = pointer; - pre_ins = post_ins; - pre_del = post_del; - lastEquality = diffs[pointer][1]; - } else { - equalitiesLength = 0; - lastEquality = null; - } - post_ins = post_del = false; - } else { - if (diffs[pointer][0] == DIFF_DELETE) { - post_del = true; - } else { - post_ins = true; - } - if (lastEquality && (pre_ins && pre_del && post_ins && post_del || lastEquality.length < this.Diff_EditCost / 2 && pre_ins + pre_del + post_ins + post_del == 3)) { - diffs.splice(equalities[equalitiesLength - 1], 0, new diff_match_patch2.Diff(DIFF_DELETE, lastEquality)); - diffs[equalities[equalitiesLength - 1] + 1][0] = DIFF_INSERT; - equalitiesLength--; - lastEquality = null; - if (pre_ins && pre_del) { - post_ins = post_del = true; - equalitiesLength = 0; - } else { - equalitiesLength--; - pointer = equalitiesLength > 0 ? equalities[equalitiesLength - 1] : -1; - post_ins = post_del = false; - } - changes = true; - } - } - pointer++; - } - if (changes) { - this.diff_cleanupMerge(diffs); - } - }; - diff_match_patch2.prototype.diff_cleanupMerge = function(diffs) { - diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, "")); - var pointer = 0; - var count_delete = 0; - var count_insert = 0; - var text_delete = ""; - var text_insert = ""; - var commonlength; - while (pointer < diffs.length) { - switch (diffs[pointer][0]) { - case DIFF_INSERT: - count_insert++; - text_insert += diffs[pointer][1]; - pointer++; - break; - case DIFF_DELETE: - count_delete++; - text_delete += diffs[pointer][1]; - pointer++; - break; - case DIFF_EQUAL: - if (count_delete + count_insert > 1) { - if (count_delete !== 0 && count_insert !== 0) { - commonlength = this.diff_commonPrefix(text_insert, text_delete); - if (commonlength !== 0) { - if (pointer - count_delete - count_insert > 0 && diffs[pointer - count_delete - count_insert - 1][0] == DIFF_EQUAL) { - diffs[pointer - count_delete - count_insert - 1][1] += text_insert.substring(0, commonlength); - } else { - diffs.splice(0, 0, new diff_match_patch2.Diff(DIFF_EQUAL, text_insert.substring(0, commonlength))); - pointer++; - } - text_insert = text_insert.substring(commonlength); - text_delete = text_delete.substring(commonlength); - } - commonlength = this.diff_commonSuffix(text_insert, text_delete); - if (commonlength !== 0) { - diffs[pointer][1] = text_insert.substring(text_insert.length - commonlength) + diffs[pointer][1]; - text_insert = text_insert.substring(0, text_insert.length - commonlength); - text_delete = text_delete.substring(0, text_delete.length - commonlength); - } - } - pointer -= count_delete + count_insert; - diffs.splice(pointer, count_delete + count_insert); - if (text_delete.length) { - diffs.splice(pointer, 0, new diff_match_patch2.Diff(DIFF_DELETE, text_delete)); - pointer++; - } - if (text_insert.length) { - diffs.splice(pointer, 0, new diff_match_patch2.Diff(DIFF_INSERT, text_insert)); - pointer++; - } - pointer++; - } else if (pointer !== 0 && diffs[pointer - 1][0] == DIFF_EQUAL) { - diffs[pointer - 1][1] += diffs[pointer][1]; - diffs.splice(pointer, 1); - } else { - pointer++; - } - count_insert = 0; - count_delete = 0; - text_delete = ""; - text_insert = ""; - break; - } - } - if (diffs[diffs.length - 1][1] === "") { - diffs.pop(); - } - var changes = false; - pointer = 1; - while (pointer < diffs.length - 1) { - if (diffs[pointer - 1][0] == DIFF_EQUAL && diffs[pointer + 1][0] == DIFF_EQUAL) { - if (diffs[pointer][1].substring(diffs[pointer][1].length - diffs[pointer - 1][1].length) == diffs[pointer - 1][1]) { - diffs[pointer][1] = diffs[pointer - 1][1] + diffs[pointer][1].substring(0, diffs[pointer][1].length - diffs[pointer - 1][1].length); - diffs[pointer + 1][1] = diffs[pointer - 1][1] + diffs[pointer + 1][1]; - diffs.splice(pointer - 1, 1); - changes = true; - } else if (diffs[pointer][1].substring(0, diffs[pointer + 1][1].length) == diffs[pointer + 1][1]) { - diffs[pointer - 1][1] += diffs[pointer + 1][1]; - diffs[pointer][1] = diffs[pointer][1].substring(diffs[pointer + 1][1].length) + diffs[pointer + 1][1]; - diffs.splice(pointer + 1, 1); - changes = true; - } - } - pointer++; - } - if (changes) { - this.diff_cleanupMerge(diffs); - } - }; - diff_match_patch2.prototype.diff_xIndex = function(diffs, loc) { - var chars1 = 0; - var chars2 = 0; - var last_chars1 = 0; - var last_chars2 = 0; - var x; - for (x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_INSERT) { - chars1 += diffs[x][1].length; - } - if (diffs[x][0] !== DIFF_DELETE) { - chars2 += diffs[x][1].length; - } - if (chars1 > loc) { - break; - } - last_chars1 = chars1; - last_chars2 = chars2; - } - if (diffs.length != x && diffs[x][0] === DIFF_DELETE) { - return last_chars2; - } - return last_chars2 + (loc - last_chars1); - }; - diff_match_patch2.prototype.diff_prettyHtml = function(diffs) { - var html = []; - var pattern_amp = /&/g; - var pattern_lt = //g; - var pattern_para = /\n/g; - for (var x = 0; x < diffs.length; x++) { - var op = diffs[x][0]; - var data2 = diffs[x][1]; - var text = data2.replace(pattern_amp, "&").replace(pattern_lt, "<").replace(pattern_gt, ">").replace(pattern_para, "¶
    "); - switch (op) { - case DIFF_INSERT: - html[x] = '' + text + ""; - break; - case DIFF_DELETE: - html[x] = '' + text + ""; - break; - case DIFF_EQUAL: - html[x] = "" + text + ""; - break; - } - } - return html.join(""); - }; - diff_match_patch2.prototype.diff_text1 = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_INSERT) { - text[x] = diffs[x][1]; - } - } - return text.join(""); - }; - diff_match_patch2.prototype.diff_text2 = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - if (diffs[x][0] !== DIFF_DELETE) { - text[x] = diffs[x][1]; - } - } - return text.join(""); - }; - diff_match_patch2.prototype.diff_levenshtein = function(diffs) { - var levenshtein = 0; - var insertions = 0; - var deletions = 0; - for (var x = 0; x < diffs.length; x++) { - var op = diffs[x][0]; - var data2 = diffs[x][1]; - switch (op) { - case DIFF_INSERT: - insertions += data2.length; - break; - case DIFF_DELETE: - deletions += data2.length; - break; - case DIFF_EQUAL: - levenshtein += Math.max(insertions, deletions); - insertions = 0; - deletions = 0; - break; - } - } - levenshtein += Math.max(insertions, deletions); - return levenshtein; - }; - diff_match_patch2.prototype.diff_toDelta = function(diffs) { - var text = []; - for (var x = 0; x < diffs.length; x++) { - switch (diffs[x][0]) { - case DIFF_INSERT: - text[x] = "+" + encodeURI(diffs[x][1]); - break; - case DIFF_DELETE: - text[x] = "-" + diffs[x][1].length; - break; - case DIFF_EQUAL: - text[x] = "=" + diffs[x][1].length; - break; - } - } - return text.join(" ").replace(/%20/g, " "); - }; - diff_match_patch2.prototype.diff_fromDelta = function(text1, delta) { - var diffs = []; - var diffsLength = 0; - var pointer = 0; - var tokens = delta.split(/\t/g); - for (var x = 0; x < tokens.length; x++) { - var param = tokens[x].substring(1); - switch (tokens[x].charAt(0)) { - case "+": - try { - diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_INSERT, decodeURI(param)); - } catch (ex) { - throw new Error("Illegal escape in diff_fromDelta: " + param); - } - break; - case "-": - case "=": - var n2 = parseInt(param, 10); - if (isNaN(n2) || n2 < 0) { - throw new Error("Invalid number in diff_fromDelta: " + param); - } - var text = text1.substring(pointer, pointer += n2); - if (tokens[x].charAt(0) == "=") { - diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_EQUAL, text); - } else { - diffs[diffsLength++] = new diff_match_patch2.Diff(DIFF_DELETE, text); - } - break; - default: - if (tokens[x]) { - throw new Error("Invalid diff operation in diff_fromDelta: " + tokens[x]); - } - } - } - if (pointer != text1.length) { - throw new Error("Delta length (" + pointer + ") does not equal source text length (" + text1.length + ")."); - } - return diffs; - }; - diff_match_patch2.prototype.match_main = function(text, pattern, loc) { - if (text == null || pattern == null || loc == null) { - throw new Error("Null input. (match_main)"); - } - loc = Math.max(0, Math.min(loc, text.length)); - if (text == pattern) { - return 0; - } else if (!text.length) { - return -1; - } else if (text.substring(loc, loc + pattern.length) == pattern) { - return loc; - } else { - return this.match_bitap_(text, pattern, loc); - } - }; - diff_match_patch2.prototype.match_bitap_ = function(text, pattern, loc) { - if (pattern.length > this.Match_MaxBits) { - throw new Error("Pattern too long for this browser."); - } - var s2 = this.match_alphabet_(pattern); - var dmp = this; - function match_bitapScore_(e, x) { - var accuracy = e / pattern.length; - var proximity = Math.abs(loc - x); - if (!dmp.Match_Distance) { - return proximity ? 1 : accuracy; - } - return accuracy + proximity / dmp.Match_Distance; - } - var score_threshold = this.Match_Threshold; - var best_loc = text.indexOf(pattern, loc); - if (best_loc != -1) { - score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); - best_loc = text.lastIndexOf(pattern, loc + pattern.length); - if (best_loc != -1) { - score_threshold = Math.min(match_bitapScore_(0, best_loc), score_threshold); - } - } - var matchmask = 1 << pattern.length - 1; - best_loc = -1; - var bin_min, bin_mid; - var bin_max = pattern.length + text.length; - var last_rd; - for (var d = 0; d < pattern.length; d++) { - bin_min = 0; - bin_mid = bin_max; - while (bin_min < bin_mid) { - if (match_bitapScore_(d, loc + bin_mid) <= score_threshold) { - bin_min = bin_mid; - } else { - bin_max = bin_mid; - } - bin_mid = Math.floor((bin_max - bin_min) / 2 + bin_min); - } - bin_max = bin_mid; - var start2 = Math.max(1, loc - bin_mid + 1); - var finish = Math.min(loc + bin_mid, text.length) + pattern.length; - var rd = Array(finish + 2); - rd[finish + 1] = (1 << d) - 1; - for (var j = finish; j >= start2; j--) { - var charMatch = s2[text.charAt(j - 1)]; - if (d === 0) { - rd[j] = (rd[j + 1] << 1 | 1) & charMatch; - } else { - rd[j] = (rd[j + 1] << 1 | 1) & charMatch | ((last_rd[j + 1] | last_rd[j]) << 1 | 1) | last_rd[j + 1]; - } - if (rd[j] & matchmask) { - var score = match_bitapScore_(d, j - 1); - if (score <= score_threshold) { - score_threshold = score; - best_loc = j - 1; - if (best_loc > loc) { - start2 = Math.max(1, 2 * loc - best_loc); - } else { - break; - } - } - } - } - if (match_bitapScore_(d + 1, loc) > score_threshold) { - break; - } - last_rd = rd; - } - return best_loc; - }; - diff_match_patch2.prototype.match_alphabet_ = function(pattern) { - var s2 = {}; - for (var i = 0; i < pattern.length; i++) { - s2[pattern.charAt(i)] = 0; - } - for (var i = 0; i < pattern.length; i++) { - s2[pattern.charAt(i)] |= 1 << pattern.length - i - 1; - } - return s2; - }; - diff_match_patch2.prototype.patch_addContext_ = function(patch, text) { - if (text.length == 0) { - return; - } - if (patch.start2 === null) { - throw Error("patch not initialized"); - } - var pattern = text.substring(patch.start2, patch.start2 + patch.length1); - var padding = 0; - while (text.indexOf(pattern) != text.lastIndexOf(pattern) && pattern.length < this.Match_MaxBits - this.Patch_Margin - this.Patch_Margin) { - padding += this.Patch_Margin; - pattern = text.substring(patch.start2 - padding, patch.start2 + patch.length1 + padding); - } - padding += this.Patch_Margin; - var prefix = text.substring(patch.start2 - padding, patch.start2); - if (prefix) { - patch.diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, prefix)); - } - var suffix = text.substring(patch.start2 + patch.length1, patch.start2 + patch.length1 + padding); - if (suffix) { - patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, suffix)); - } - patch.start1 -= prefix.length; - patch.start2 -= prefix.length; - patch.length1 += prefix.length + suffix.length; - patch.length2 += prefix.length + suffix.length; - }; - diff_match_patch2.prototype.patch_make = function(a, opt_b, opt_c) { - var text1, diffs; - if (typeof a == "string" && typeof opt_b == "string" && typeof opt_c == "undefined") { - text1 = a; - diffs = this.diff_main(text1, opt_b, true); - if (diffs.length > 2) { - this.diff_cleanupSemantic(diffs); - this.diff_cleanupEfficiency(diffs); - } - } else if (a && typeof a == "object" && typeof opt_b == "undefined" && typeof opt_c == "undefined") { - diffs = a; - text1 = this.diff_text1(diffs); - } else if (typeof a == "string" && opt_b && typeof opt_b == "object" && typeof opt_c == "undefined") { - text1 = a; - diffs = opt_b; - } else if (typeof a == "string" && typeof opt_b == "string" && opt_c && typeof opt_c == "object") { - text1 = a; - diffs = opt_c; - } else { - throw new Error("Unknown call format to patch_make."); - } - if (diffs.length === 0) { - return []; - } - var patches = []; - var patch = new diff_match_patch2.patch_obj(); - var patchDiffLength = 0; - var char_count1 = 0; - var char_count2 = 0; - var prepatch_text = text1; - var postpatch_text = text1; - for (var x = 0; x < diffs.length; x++) { - var diff_type = diffs[x][0]; - var diff_text = diffs[x][1]; - if (!patchDiffLength && diff_type !== DIFF_EQUAL) { - patch.start1 = char_count1; - patch.start2 = char_count2; - } - switch (diff_type) { - case DIFF_INSERT: - patch.diffs[patchDiffLength++] = diffs[x]; - patch.length2 += diff_text.length; - postpatch_text = postpatch_text.substring(0, char_count2) + diff_text + postpatch_text.substring(char_count2); - break; - case DIFF_DELETE: - patch.length1 += diff_text.length; - patch.diffs[patchDiffLength++] = diffs[x]; - postpatch_text = postpatch_text.substring(0, char_count2) + postpatch_text.substring(char_count2 + diff_text.length); - break; - case DIFF_EQUAL: - if (diff_text.length <= 2 * this.Patch_Margin && patchDiffLength && diffs.length != x + 1) { - patch.diffs[patchDiffLength++] = diffs[x]; - patch.length1 += diff_text.length; - patch.length2 += diff_text.length; - } else if (diff_text.length >= 2 * this.Patch_Margin) { - if (patchDiffLength) { - this.patch_addContext_(patch, prepatch_text); - patches.push(patch); - patch = new diff_match_patch2.patch_obj(); - patchDiffLength = 0; - prepatch_text = postpatch_text; - char_count1 = char_count2; - } - } - break; - } - if (diff_type !== DIFF_INSERT) { - char_count1 += diff_text.length; - } - if (diff_type !== DIFF_DELETE) { - char_count2 += diff_text.length; - } - } - if (patchDiffLength) { - this.patch_addContext_(patch, prepatch_text); - patches.push(patch); - } - return patches; - }; - diff_match_patch2.prototype.patch_deepCopy = function(patches) { - var patchesCopy = []; - for (var x = 0; x < patches.length; x++) { - var patch = patches[x]; - var patchCopy = new diff_match_patch2.patch_obj(); - patchCopy.diffs = []; - for (var y = 0; y < patch.diffs.length; y++) { - patchCopy.diffs[y] = new diff_match_patch2.Diff(patch.diffs[y][0], patch.diffs[y][1]); - } - patchCopy.start1 = patch.start1; - patchCopy.start2 = patch.start2; - patchCopy.length1 = patch.length1; - patchCopy.length2 = patch.length2; - patchesCopy[x] = patchCopy; - } - return patchesCopy; - }; - diff_match_patch2.prototype.patch_apply = function(patches, text) { - if (patches.length == 0) { - return [text, []]; - } - patches = this.patch_deepCopy(patches); - var nullPadding = this.patch_addPadding(patches); - text = nullPadding + text + nullPadding; - this.patch_splitMax(patches); - var delta = 0; - var results = []; - for (var x = 0; x < patches.length; x++) { - var expected_loc = patches[x].start2 + delta; - var text1 = this.diff_text1(patches[x].diffs); - var start_loc; - var end_loc = -1; - if (text1.length > this.Match_MaxBits) { - start_loc = this.match_main(text, text1.substring(0, this.Match_MaxBits), expected_loc); - if (start_loc != -1) { - end_loc = this.match_main(text, text1.substring(text1.length - this.Match_MaxBits), expected_loc + text1.length - this.Match_MaxBits); - if (end_loc == -1 || start_loc >= end_loc) { - start_loc = -1; - } - } - } else { - start_loc = this.match_main(text, text1, expected_loc); - } - if (start_loc == -1) { - results[x] = false; - delta -= patches[x].length2 - patches[x].length1; - } else { - results[x] = true; - delta = start_loc - expected_loc; - var text2; - if (end_loc == -1) { - text2 = text.substring(start_loc, start_loc + text1.length); - } else { - text2 = text.substring(start_loc, end_loc + this.Match_MaxBits); - } - if (text1 == text2) { - text = text.substring(0, start_loc) + this.diff_text2(patches[x].diffs) + text.substring(start_loc + text1.length); - } else { - var diffs = this.diff_main(text1, text2, false); - if (text1.length > this.Match_MaxBits && this.diff_levenshtein(diffs) / text1.length > this.Patch_DeleteThreshold) { - results[x] = false; - } else { - this.diff_cleanupSemanticLossless(diffs); - var index1 = 0; - var index2; - for (var y = 0; y < patches[x].diffs.length; y++) { - var mod = patches[x].diffs[y]; - if (mod[0] !== DIFF_EQUAL) { - index2 = this.diff_xIndex(diffs, index1); - } - if (mod[0] === DIFF_INSERT) { - text = text.substring(0, start_loc + index2) + mod[1] + text.substring(start_loc + index2); - } else if (mod[0] === DIFF_DELETE) { - text = text.substring(0, start_loc + index2) + text.substring(start_loc + this.diff_xIndex(diffs, index1 + mod[1].length)); - } - if (mod[0] !== DIFF_DELETE) { - index1 += mod[1].length; - } - } - } - } - } - } - text = text.substring(nullPadding.length, text.length - nullPadding.length); - return [text, results]; - }; - diff_match_patch2.prototype.patch_addPadding = function(patches) { - var paddingLength = this.Patch_Margin; - var nullPadding = ""; - for (var x = 1; x <= paddingLength; x++) { - nullPadding += String.fromCharCode(x); - } - for (var x = 0; x < patches.length; x++) { - patches[x].start1 += paddingLength; - patches[x].start2 += paddingLength; - } - var patch = patches[0]; - var diffs = patch.diffs; - if (diffs.length == 0 || diffs[0][0] != DIFF_EQUAL) { - diffs.unshift(new diff_match_patch2.Diff(DIFF_EQUAL, nullPadding)); - patch.start1 -= paddingLength; - patch.start2 -= paddingLength; - patch.length1 += paddingLength; - patch.length2 += paddingLength; - } else if (paddingLength > diffs[0][1].length) { - var extraLength = paddingLength - diffs[0][1].length; - diffs[0][1] = nullPadding.substring(diffs[0][1].length) + diffs[0][1]; - patch.start1 -= extraLength; - patch.start2 -= extraLength; - patch.length1 += extraLength; - patch.length2 += extraLength; - } - patch = patches[patches.length - 1]; - diffs = patch.diffs; - if (diffs.length == 0 || diffs[diffs.length - 1][0] != DIFF_EQUAL) { - diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, nullPadding)); - patch.length1 += paddingLength; - patch.length2 += paddingLength; - } else if (paddingLength > diffs[diffs.length - 1][1].length) { - var extraLength = paddingLength - diffs[diffs.length - 1][1].length; - diffs[diffs.length - 1][1] += nullPadding.substring(0, extraLength); - patch.length1 += extraLength; - patch.length2 += extraLength; - } - return nullPadding; - }; - diff_match_patch2.prototype.patch_splitMax = function(patches) { - var patch_size = this.Match_MaxBits; - for (var x = 0; x < patches.length; x++) { - if (patches[x].length1 <= patch_size) { - continue; - } - var bigpatch = patches[x]; - patches.splice(x--, 1); - var start1 = bigpatch.start1; - var start2 = bigpatch.start2; - var precontext = ""; - while (bigpatch.diffs.length !== 0) { - var patch = new diff_match_patch2.patch_obj(); - var empty = true; - patch.start1 = start1 - precontext.length; - patch.start2 = start2 - precontext.length; - if (precontext !== "") { - patch.length1 = patch.length2 = precontext.length; - patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, precontext)); - } - while (bigpatch.diffs.length !== 0 && patch.length1 < patch_size - this.Patch_Margin) { - var diff_type = bigpatch.diffs[0][0]; - var diff_text = bigpatch.diffs[0][1]; - if (diff_type === DIFF_INSERT) { - patch.length2 += diff_text.length; - start2 += diff_text.length; - patch.diffs.push(bigpatch.diffs.shift()); - empty = false; - } else if (diff_type === DIFF_DELETE && patch.diffs.length == 1 && patch.diffs[0][0] == DIFF_EQUAL && diff_text.length > 2 * patch_size) { - patch.length1 += diff_text.length; - start1 += diff_text.length; - empty = false; - patch.diffs.push(new diff_match_patch2.Diff(diff_type, diff_text)); - bigpatch.diffs.shift(); - } else { - diff_text = diff_text.substring(0, patch_size - patch.length1 - this.Patch_Margin); - patch.length1 += diff_text.length; - start1 += diff_text.length; - if (diff_type === DIFF_EQUAL) { - patch.length2 += diff_text.length; - start2 += diff_text.length; - } else { - empty = false; - } - patch.diffs.push(new diff_match_patch2.Diff(diff_type, diff_text)); - if (diff_text == bigpatch.diffs[0][1]) { - bigpatch.diffs.shift(); - } else { - bigpatch.diffs[0][1] = bigpatch.diffs[0][1].substring(diff_text.length); - } - } - } - precontext = this.diff_text2(patch.diffs); - precontext = precontext.substring(precontext.length - this.Patch_Margin); - var postcontext = this.diff_text1(bigpatch.diffs).substring(0, this.Patch_Margin); - if (postcontext !== "") { - patch.length1 += postcontext.length; - patch.length2 += postcontext.length; - if (patch.diffs.length !== 0 && patch.diffs[patch.diffs.length - 1][0] === DIFF_EQUAL) { - patch.diffs[patch.diffs.length - 1][1] += postcontext; - } else { - patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, postcontext)); - } - } - if (!empty) { - patches.splice(++x, 0, patch); - } - } - } - }; - diff_match_patch2.prototype.patch_toText = function(patches) { - var text = []; - for (var x = 0; x < patches.length; x++) { - text[x] = patches[x]; - } - return text.join(""); - }; - diff_match_patch2.prototype.patch_fromText = function(textline) { - var patches = []; - if (!textline) { - return patches; - } - var text = textline.split("\n"); - var textPointer = 0; - var patchHeader = /^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/; - while (textPointer < text.length) { - var m = text[textPointer].match(patchHeader); - if (!m) { - throw new Error("Invalid patch string: " + text[textPointer]); - } - var patch = new diff_match_patch2.patch_obj(); - patches.push(patch); - patch.start1 = parseInt(m[1], 10); - if (m[2] === "") { - patch.start1--; - patch.length1 = 1; - } else if (m[2] == "0") { - patch.length1 = 0; - } else { - patch.start1--; - patch.length1 = parseInt(m[2], 10); - } - patch.start2 = parseInt(m[3], 10); - if (m[4] === "") { - patch.start2--; - patch.length2 = 1; - } else if (m[4] == "0") { - patch.length2 = 0; - } else { - patch.start2--; - patch.length2 = parseInt(m[4], 10); - } - textPointer++; - while (textPointer < text.length) { - var sign = text[textPointer].charAt(0); - try { - var line = decodeURI(text[textPointer].substring(1)); - } catch (ex) { - throw new Error("Illegal escape in patch_fromText: " + line); - } - if (sign == "-") { - patch.diffs.push(new diff_match_patch2.Diff(DIFF_DELETE, line)); - } else if (sign == "+") { - patch.diffs.push(new diff_match_patch2.Diff(DIFF_INSERT, line)); - } else if (sign == " ") { - patch.diffs.push(new diff_match_patch2.Diff(DIFF_EQUAL, line)); - } else if (sign == "@") { - break; - } else if (sign === "") { - } else { - throw new Error('Invalid patch mode "' + sign + '" in: ' + line); - } - textPointer++; - } - } - return patches; - }; - diff_match_patch2.patch_obj = function() { - this.diffs = []; - this.start1 = null; - this.start2 = null; - this.length1 = 0; - this.length2 = 0; - }; - diff_match_patch2.patch_obj.prototype.toString = function() { - var coords1, coords2; - if (this.length1 === 0) { - coords1 = this.start1 + ",0"; - } else if (this.length1 == 1) { - coords1 = this.start1 + 1; - } else { - coords1 = this.start1 + 1 + "," + this.length1; - } - if (this.length2 === 0) { - coords2 = this.start2 + ",0"; - } else if (this.length2 == 1) { - coords2 = this.start2 + 1; - } else { - coords2 = this.start2 + 1 + "," + this.length2; - } - var text = ["@@ -" + coords1 + " +" + coords2 + " @@\n"]; - var op; - for (var x = 0; x < this.diffs.length; x++) { - switch (this.diffs[x][0]) { - case DIFF_INSERT: - op = "+"; - break; - case DIFF_DELETE: - op = "-"; - break; - case DIFF_EQUAL: - op = " "; - break; - } - text[x + 1] = op + encodeURI(this.diffs[x][1]) + "\n"; - } - return text.join("").replace(/%20/g, " "); - }; - module2.exports = diff_match_patch2; - module2.exports["diff_match_patch"] = diff_match_patch2; - module2.exports["DIFF_DELETE"] = DIFF_DELETE; - module2.exports["DIFF_INSERT"] = DIFF_INSERT; - module2.exports["DIFF_EQUAL"] = DIFF_EQUAL; - } -}); - -// node_modules/markdown-escape/index.js -var require_markdown_escape = __commonJS({ - "node_modules/markdown-escape/index.js"(exports, module2) { - var replacements = [ - [/\*/g, "\\*", "asterisks"], - [/#/g, "\\#", "number signs"], - [/\//g, "\\/", "slashes"], - [/\(/g, "\\(", "parentheses"], - [/\)/g, "\\)", "parentheses"], - [/\[/g, "\\[", "square brackets"], - [/\]/g, "\\]", "square brackets"], - [//g, ">", "angle brackets"], - [/_/g, "\\_", "underscores"], - [/`/g, "\\`", "codeblocks"] - ]; - module2.exports = function(string, skips) { - skips = skips || []; - return replacements.reduce(function(string2, replacement) { - var name = replacement[2]; - return name && skips.indexOf(name) !== -1 ? string2 : string2.replace(replacement[0], replacement[1]); - }, string); - }; - } -}); - -// src/main.ts -var main_exports = {}; -__export(main_exports, { - default: () => OmnivorePlugin -}); -module.exports = __toCommonJS(main_exports); - -// node_modules/luxon/src/errors.js -var LuxonError = class extends Error { -}; -var InvalidDateTimeError = class extends LuxonError { - constructor(reason) { - super(`Invalid DateTime: ${reason.toMessage()}`); - } -}; -var InvalidIntervalError = class extends LuxonError { - constructor(reason) { - super(`Invalid Interval: ${reason.toMessage()}`); - } -}; -var InvalidDurationError = class extends LuxonError { - constructor(reason) { - super(`Invalid Duration: ${reason.toMessage()}`); - } -}; -var ConflictingSpecificationError = class extends LuxonError { -}; -var InvalidUnitError = class extends LuxonError { - constructor(unit) { - super(`Invalid unit ${unit}`); - } -}; -var InvalidArgumentError = class extends LuxonError { -}; -var ZoneIsAbstractError = class extends LuxonError { - constructor() { - super("Zone is an abstract class"); - } -}; - -// node_modules/luxon/src/impl/formats.js -var n = "numeric"; -var s = "short"; -var l = "long"; -var DATE_SHORT = { - year: n, - month: n, - day: n -}; -var DATE_MED = { - year: n, - month: s, - day: n -}; -var DATE_MED_WITH_WEEKDAY = { - year: n, - month: s, - day: n, - weekday: s -}; -var DATE_FULL = { - year: n, - month: l, - day: n -}; -var DATE_HUGE = { - year: n, - month: l, - day: n, - weekday: l -}; -var TIME_SIMPLE = { - hour: n, - minute: n -}; -var TIME_WITH_SECONDS = { - hour: n, - minute: n, - second: n -}; -var TIME_WITH_SHORT_OFFSET = { - hour: n, - minute: n, - second: n, - timeZoneName: s -}; -var TIME_WITH_LONG_OFFSET = { - hour: n, - minute: n, - second: n, - timeZoneName: l -}; -var TIME_24_SIMPLE = { - hour: n, - minute: n, - hourCycle: "h23" -}; -var TIME_24_WITH_SECONDS = { - hour: n, - minute: n, - second: n, - hourCycle: "h23" -}; -var TIME_24_WITH_SHORT_OFFSET = { - hour: n, - minute: n, - second: n, - hourCycle: "h23", - timeZoneName: s -}; -var TIME_24_WITH_LONG_OFFSET = { - hour: n, - minute: n, - second: n, - hourCycle: "h23", - timeZoneName: l -}; -var DATETIME_SHORT = { - year: n, - month: n, - day: n, - hour: n, - minute: n -}; -var DATETIME_SHORT_WITH_SECONDS = { - year: n, - month: n, - day: n, - hour: n, - minute: n, - second: n -}; -var DATETIME_MED = { - year: n, - month: s, - day: n, - hour: n, - minute: n -}; -var DATETIME_MED_WITH_SECONDS = { - year: n, - month: s, - day: n, - hour: n, - minute: n, - second: n -}; -var DATETIME_MED_WITH_WEEKDAY = { - year: n, - month: s, - day: n, - weekday: s, - hour: n, - minute: n -}; -var DATETIME_FULL = { - year: n, - month: l, - day: n, - hour: n, - minute: n, - timeZoneName: s -}; -var DATETIME_FULL_WITH_SECONDS = { - year: n, - month: l, - day: n, - hour: n, - minute: n, - second: n, - timeZoneName: s -}; -var DATETIME_HUGE = { - year: n, - month: l, - day: n, - weekday: l, - hour: n, - minute: n, - timeZoneName: l -}; -var DATETIME_HUGE_WITH_SECONDS = { - year: n, - month: l, - day: n, - weekday: l, - hour: n, - minute: n, - second: n, - timeZoneName: l -}; - -// node_modules/luxon/src/zone.js -var Zone = class { - get type() { - throw new ZoneIsAbstractError(); - } - get name() { - throw new ZoneIsAbstractError(); - } - get ianaName() { - return this.name; - } - get isUniversal() { - throw new ZoneIsAbstractError(); - } - offsetName(ts, opts) { - throw new ZoneIsAbstractError(); - } - formatOffset(ts, format) { - throw new ZoneIsAbstractError(); - } - offset(ts) { - throw new ZoneIsAbstractError(); - } - equals(otherZone) { - throw new ZoneIsAbstractError(); - } - get isValid() { - throw new ZoneIsAbstractError(); - } -}; - -// node_modules/luxon/src/zones/systemZone.js -var singleton = null; -var SystemZone = class extends Zone { - static get instance() { - if (singleton === null) { - singleton = new SystemZone(); - } - return singleton; - } - get type() { - return "system"; - } - get name() { - return new Intl.DateTimeFormat().resolvedOptions().timeZone; - } - get isUniversal() { - return false; - } - offsetName(ts, { format, locale }) { - return parseZoneInfo(ts, format, locale); - } - formatOffset(ts, format) { - return formatOffset(this.offset(ts), format); - } - offset(ts) { - return -new Date(ts).getTimezoneOffset(); - } - equals(otherZone) { - return otherZone.type === "system"; - } - get isValid() { - return true; - } -}; - -// node_modules/luxon/src/zones/IANAZone.js -var dtfCache = {}; -function makeDTF(zone) { - if (!dtfCache[zone]) { - dtfCache[zone] = new Intl.DateTimeFormat("en-US", { - hour12: false, - timeZone: zone, - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - era: "short" - }); - } - return dtfCache[zone]; -} -var typeToPos = { - year: 0, - month: 1, - day: 2, - era: 3, - hour: 4, - minute: 5, - second: 6 -}; -function hackyOffset(dtf, date) { - const formatted = dtf.format(date).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; - return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; -} -function partsOffset(dtf, date) { - const formatted = dtf.formatToParts(date); - const filled = []; - for (let i = 0; i < formatted.length; i++) { - const { type, value } = formatted[i]; - const pos = typeToPos[type]; - if (type === "era") { - filled[pos] = value; - } else if (!isUndefined(pos)) { - filled[pos] = parseInt(value, 10); - } - } - return filled; -} -var ianaZoneCache = {}; -var IANAZone = class extends Zone { - static create(name) { - if (!ianaZoneCache[name]) { - ianaZoneCache[name] = new IANAZone(name); - } - return ianaZoneCache[name]; - } - static resetCache() { - ianaZoneCache = {}; - dtfCache = {}; - } - static isValidSpecifier(s2) { - return this.isValidZone(s2); - } - static isValidZone(zone) { - if (!zone) { - return false; - } - try { - new Intl.DateTimeFormat("en-US", { timeZone: zone }).format(); - return true; - } catch (e) { - return false; - } - } - constructor(name) { - super(); - this.zoneName = name; - this.valid = IANAZone.isValidZone(name); - } - get type() { - return "iana"; - } - get name() { - return this.zoneName; - } - get isUniversal() { - return false; - } - offsetName(ts, { format, locale }) { - return parseZoneInfo(ts, format, locale, this.name); - } - formatOffset(ts, format) { - return formatOffset(this.offset(ts), format); - } - offset(ts) { - const date = new Date(ts); - if (isNaN(date)) - return NaN; - const dtf = makeDTF(this.name); - let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date); - if (adOrBc === "BC") { - year = -Math.abs(year) + 1; - } - const adjustedHour = hour === 24 ? 0 : hour; - const asUTC = objToLocalTS({ - year, - month, - day, - hour: adjustedHour, - minute, - second, - millisecond: 0 - }); - let asTS = +date; - const over = asTS % 1e3; - asTS -= over >= 0 ? over : 1e3 + over; - return (asUTC - asTS) / (60 * 1e3); - } - equals(otherZone) { - return otherZone.type === "iana" && otherZone.name === this.name; - } - get isValid() { - return this.valid; - } -}; - -// node_modules/luxon/src/impl/locale.js -var intlLFCache = {}; -function getCachedLF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlLFCache[key]; - if (!dtf) { - dtf = new Intl.ListFormat(locString, opts); - intlLFCache[key] = dtf; - } - return dtf; -} -var intlDTCache = {}; -function getCachedDTF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlDTCache[key]; - if (!dtf) { - dtf = new Intl.DateTimeFormat(locString, opts); - intlDTCache[key] = dtf; - } - return dtf; -} -var intlNumCache = {}; -function getCachedINF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let inf = intlNumCache[key]; - if (!inf) { - inf = new Intl.NumberFormat(locString, opts); - intlNumCache[key] = inf; - } - return inf; -} -var intlRelCache = {}; -function getCachedRTF(locString, opts = {}) { - const { base, ...cacheKeyOpts } = opts; - const key = JSON.stringify([locString, cacheKeyOpts]); - let inf = intlRelCache[key]; - if (!inf) { - inf = new Intl.RelativeTimeFormat(locString, opts); - intlRelCache[key] = inf; - } - return inf; -} -var sysLocaleCache = null; -function systemLocale() { - if (sysLocaleCache) { - return sysLocaleCache; - } else { - sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; - return sysLocaleCache; - } -} -var weekInfoCache = {}; -function getCachedWeekInfo(locString) { - let data2 = weekInfoCache[locString]; - if (!data2) { - const locale = new Intl.Locale(locString); - data2 = "getWeekInfo" in locale ? locale.getWeekInfo() : locale.weekInfo; - weekInfoCache[locString] = data2; - } - return data2; -} -function parseLocaleString(localeStr) { - const xIndex = localeStr.indexOf("-x-"); - if (xIndex !== -1) { - localeStr = localeStr.substring(0, xIndex); - } - const uIndex = localeStr.indexOf("-u-"); - if (uIndex === -1) { - return [localeStr]; - } else { - let options; - let selectedStr; - try { - options = getCachedDTF(localeStr).resolvedOptions(); - selectedStr = localeStr; - } catch (e) { - const smaller = localeStr.substring(0, uIndex); - options = getCachedDTF(smaller).resolvedOptions(); - selectedStr = smaller; - } - const { numberingSystem, calendar } = options; - return [selectedStr, numberingSystem, calendar]; - } -} -function intlConfigString(localeStr, numberingSystem, outputCalendar) { - if (outputCalendar || numberingSystem) { - if (!localeStr.includes("-u-")) { - localeStr += "-u"; - } - if (outputCalendar) { - localeStr += `-ca-${outputCalendar}`; - } - if (numberingSystem) { - localeStr += `-nu-${numberingSystem}`; - } - return localeStr; - } else { - return localeStr; - } -} -function mapMonths(f) { - const ms = []; - for (let i = 1; i <= 12; i++) { - const dt = DateTime.utc(2009, i, 1); - ms.push(f(dt)); - } - return ms; -} -function mapWeekdays(f) { - const ms = []; - for (let i = 1; i <= 7; i++) { - const dt = DateTime.utc(2016, 11, 13 + i); - ms.push(f(dt)); - } - return ms; -} -function listStuff(loc, length, englishFn, intlFn) { - const mode = loc.listingMode(); - if (mode === "error") { - return null; - } else if (mode === "en") { - return englishFn(length); - } else { - return intlFn(length); - } -} -function supportsFastNumbers(loc) { - if (loc.numberingSystem && loc.numberingSystem !== "latn") { - return false; - } else { - return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || new Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === "latn"; - } -} -var PolyNumberFormatter = class { - constructor(intl, forceSimple, opts) { - this.padTo = opts.padTo || 0; - this.floor = opts.floor || false; - const { padTo, floor, ...otherOpts } = opts; - if (!forceSimple || Object.keys(otherOpts).length > 0) { - const intlOpts = { useGrouping: false, ...opts }; - if (opts.padTo > 0) - intlOpts.minimumIntegerDigits = opts.padTo; - this.inf = getCachedINF(intl, intlOpts); - } - } - format(i) { - if (this.inf) { - const fixed = this.floor ? Math.floor(i) : i; - return this.inf.format(fixed); - } else { - const fixed = this.floor ? Math.floor(i) : roundTo(i, 3); - return padStart(fixed, this.padTo); - } - } -}; -var PolyDateFormatter = class { - constructor(dt, intl, opts) { - this.opts = opts; - this.originalZone = void 0; - let z = void 0; - if (this.opts.timeZone) { - this.dt = dt; - } else if (dt.zone.type === "fixed") { - const gmtOffset = -1 * (dt.offset / 60); - const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; - if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { - z = offsetZ; - this.dt = dt; - } else { - z = "UTC"; - this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ minutes: dt.offset }); - this.originalZone = dt.zone; - } - } else if (dt.zone.type === "system") { - this.dt = dt; - } else if (dt.zone.type === "iana") { - this.dt = dt; - z = dt.zone.name; - } else { - z = "UTC"; - this.dt = dt.setZone("UTC").plus({ minutes: dt.offset }); - this.originalZone = dt.zone; - } - const intlOpts = { ...this.opts }; - intlOpts.timeZone = intlOpts.timeZone || z; - this.dtf = getCachedDTF(intl, intlOpts); - } - format() { - if (this.originalZone) { - return this.formatToParts().map(({ value }) => value).join(""); - } - return this.dtf.format(this.dt.toJSDate()); - } - formatToParts() { - const parts = this.dtf.formatToParts(this.dt.toJSDate()); - if (this.originalZone) { - return parts.map((part) => { - if (part.type === "timeZoneName") { - const offsetName = this.originalZone.offsetName(this.dt.ts, { - locale: this.dt.locale, - format: this.opts.timeZoneName - }); - return { - ...part, - value: offsetName - }; - } else { - return part; - } - }); - } - return parts; - } - resolvedOptions() { - return this.dtf.resolvedOptions(); - } -}; -var PolyRelFormatter = class { - constructor(intl, isEnglish, opts) { - this.opts = { style: "long", ...opts }; - if (!isEnglish && hasRelative()) { - this.rtf = getCachedRTF(intl, opts); - } - } - format(count, unit) { - if (this.rtf) { - return this.rtf.format(count, unit); - } else { - return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); - } - } - formatToParts(count, unit) { - if (this.rtf) { - return this.rtf.formatToParts(count, unit); - } else { - return []; - } - } -}; -var fallbackWeekSettings = { - firstDay: 1, - minimalDays: 4, - weekend: [6, 7] -}; -var Locale = class { - static fromOpts(opts) { - return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); - } - static create(locale, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { - const specifiedLocale = locale || Settings.defaultLocale; - const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); - const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; - const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; - const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; - return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); - } - static resetCache() { - sysLocaleCache = null; - intlDTCache = {}; - intlNumCache = {}; - intlRelCache = {}; - } - static fromObject({ locale, numberingSystem, outputCalendar, weekSettings } = {}) { - return Locale.create(locale, numberingSystem, outputCalendar, weekSettings); - } - constructor(locale, numbering, outputCalendar, weekSettings, specifiedLocale) { - const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale); - this.locale = parsedLocale; - this.numberingSystem = numbering || parsedNumberingSystem || null; - this.outputCalendar = outputCalendar || parsedOutputCalendar || null; - this.weekSettings = weekSettings; - this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); - this.weekdaysCache = { format: {}, standalone: {} }; - this.monthsCache = { format: {}, standalone: {} }; - this.meridiemCache = null; - this.eraCache = {}; - this.specifiedLocale = specifiedLocale; - this.fastNumbersCached = null; - } - get fastNumbers() { - if (this.fastNumbersCached == null) { - this.fastNumbersCached = supportsFastNumbers(this); - } - return this.fastNumbersCached; - } - listingMode() { - const isActuallyEn = this.isEnglish(); - const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); - return isActuallyEn && hasNoWeirdness ? "en" : "intl"; - } - clone(alts) { - if (!alts || Object.getOwnPropertyNames(alts).length === 0) { - return this; - } else { - return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false); - } - } - redefaultToEN(alts = {}) { - return this.clone({ ...alts, defaultToEN: true }); - } - redefaultToSystem(alts = {}) { - return this.clone({ ...alts, defaultToEN: false }); - } - months(length, format = false) { - return listStuff(this, length, months, () => { - const intl = format ? { month: length, day: "numeric" } : { month: length }, formatStr = format ? "format" : "standalone"; - if (!this.monthsCache[formatStr][length]) { - this.monthsCache[formatStr][length] = mapMonths((dt) => this.extract(dt, intl, "month")); - } - return this.monthsCache[formatStr][length]; - }); - } - weekdays(length, format = false) { - return listStuff(this, length, weekdays, () => { - const intl = format ? { weekday: length, year: "numeric", month: "long", day: "numeric" } : { weekday: length }, formatStr = format ? "format" : "standalone"; - if (!this.weekdaysCache[formatStr][length]) { - this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => this.extract(dt, intl, "weekday")); - } - return this.weekdaysCache[formatStr][length]; - }); - } - meridiems() { - return listStuff(this, void 0, () => meridiems, () => { - if (!this.meridiemCache) { - const intl = { hour: "numeric", hourCycle: "h12" }; - this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map((dt) => this.extract(dt, intl, "dayperiod")); - } - return this.meridiemCache; - }); - } - eras(length) { - return listStuff(this, length, eras, () => { - const intl = { era: length }; - if (!this.eraCache[length]) { - this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => this.extract(dt, intl, "era")); - } - return this.eraCache[length]; - }); - } - extract(dt, intlOpts, field) { - const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m) => m.type.toLowerCase() === field); - return matching ? matching.value : null; - } - numberFormatter(opts = {}) { - return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); - } - dtFormatter(dt, intlOpts = {}) { - return new PolyDateFormatter(dt, this.intl, intlOpts); - } - relFormatter(opts = {}) { - return new PolyRelFormatter(this.intl, this.isEnglish(), opts); - } - listFormatter(opts = {}) { - return getCachedLF(this.intl, opts); - } - isEnglish() { - return this.locale === "en" || this.locale.toLowerCase() === "en-us" || new Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith("en-us"); - } - getWeekSettings() { - if (this.weekSettings) { - return this.weekSettings; - } else if (!hasLocaleWeekInfo()) { - return fallbackWeekSettings; - } else { - return getCachedWeekInfo(this.locale); - } - } - getStartOfWeek() { - return this.getWeekSettings().firstDay; - } - getMinDaysInFirstWeek() { - return this.getWeekSettings().minimalDays; - } - getWeekendDays() { - return this.getWeekSettings().weekend; - } - equals(other) { - return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; - } -}; - -// node_modules/luxon/src/zones/fixedOffsetZone.js -var singleton2 = null; -var FixedOffsetZone = class extends Zone { - static get utcInstance() { - if (singleton2 === null) { - singleton2 = new FixedOffsetZone(0); - } - return singleton2; - } - static instance(offset3) { - return offset3 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset3); - } - static parseSpecifier(s2) { - if (s2) { - const r = s2.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); - if (r) { - return new FixedOffsetZone(signedOffset(r[1], r[2])); - } - } - return null; - } - constructor(offset3) { - super(); - this.fixed = offset3; - } - get type() { - return "fixed"; - } - get name() { - return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; - } - get ianaName() { - if (this.fixed === 0) { - return "Etc/UTC"; - } else { - return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; - } - } - offsetName() { - return this.name; - } - formatOffset(ts, format) { - return formatOffset(this.fixed, format); - } - get isUniversal() { - return true; - } - offset() { - return this.fixed; - } - equals(otherZone) { - return otherZone.type === "fixed" && otherZone.fixed === this.fixed; - } - get isValid() { - return true; - } -}; - -// node_modules/luxon/src/zones/invalidZone.js -var InvalidZone = class extends Zone { - constructor(zoneName) { - super(); - this.zoneName = zoneName; - } - get type() { - return "invalid"; - } - get name() { - return this.zoneName; - } - get isUniversal() { - return false; - } - offsetName() { - return null; - } - formatOffset() { - return ""; - } - offset() { - return NaN; - } - equals() { - return false; - } - get isValid() { - return false; - } -}; - -// node_modules/luxon/src/impl/zoneUtil.js -function normalizeZone(input, defaultZone2) { - let offset3; - if (isUndefined(input) || input === null) { - return defaultZone2; - } else if (input instanceof Zone) { - return input; - } else if (isString(input)) { - const lowered = input.toLowerCase(); - if (lowered === "default") - return defaultZone2; - else if (lowered === "local" || lowered === "system") - return SystemZone.instance; - else if (lowered === "utc" || lowered === "gmt") - return FixedOffsetZone.utcInstance; - else - return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); - } else if (isNumber(input)) { - return FixedOffsetZone.instance(input); - } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { - return input; - } else { - return new InvalidZone(input); - } -} - -// node_modules/luxon/src/settings.js -var now = () => Date.now(); -var defaultZone = "system"; -var defaultLocale = null; -var defaultNumberingSystem = null; -var defaultOutputCalendar = null; -var twoDigitCutoffYear = 60; -var throwOnInvalid; -var defaultWeekSettings = null; -var Settings = class { - static get now() { - return now; - } - static set now(n2) { - now = n2; - } - static set defaultZone(zone) { - defaultZone = zone; - } - static get defaultZone() { - return normalizeZone(defaultZone, SystemZone.instance); - } - static get defaultLocale() { - return defaultLocale; - } - static set defaultLocale(locale) { - defaultLocale = locale; - } - static get defaultNumberingSystem() { - return defaultNumberingSystem; - } - static set defaultNumberingSystem(numberingSystem) { - defaultNumberingSystem = numberingSystem; - } - static get defaultOutputCalendar() { - return defaultOutputCalendar; - } - static set defaultOutputCalendar(outputCalendar) { - defaultOutputCalendar = outputCalendar; - } - static get defaultWeekSettings() { - return defaultWeekSettings; - } - static set defaultWeekSettings(weekSettings) { - defaultWeekSettings = validateWeekSettings(weekSettings); - } - static get twoDigitCutoffYear() { - return twoDigitCutoffYear; - } - static set twoDigitCutoffYear(cutoffYear) { - twoDigitCutoffYear = cutoffYear % 100; - } - static get throwOnInvalid() { - return throwOnInvalid; - } - static set throwOnInvalid(t) { - throwOnInvalid = t; - } - static resetCaches() { - Locale.resetCache(); - IANAZone.resetCache(); - } -}; - -// node_modules/luxon/src/impl/invalid.js -var Invalid = class { - constructor(reason, explanation) { - this.reason = reason; - this.explanation = explanation; - } - toMessage() { - if (this.explanation) { - return `${this.reason}: ${this.explanation}`; - } else { - return this.reason; - } - } -}; - -// node_modules/luxon/src/impl/conversions.js -var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; -var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; -function unitOutOfRange(unit, value) { - return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`); -} -function dayOfWeek(year, month, day) { - const d = new Date(Date.UTC(year, month - 1, day)); - if (year < 100 && year >= 0) { - d.setUTCFullYear(d.getUTCFullYear() - 1900); - } - const js = d.getUTCDay(); - return js === 0 ? 7 : js; -} -function computeOrdinal(year, month, day) { - return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; -} -function uncomputeOrdinal(year, ordinal) { - const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i) => i < ordinal), day = ordinal - table[month0]; - return { month: month0 + 1, day }; -} -function isoWeekdayToLocal(isoWeekday, startOfWeek) { - return (isoWeekday - startOfWeek + 7) % 7 + 1; -} -function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { year, month, day } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); - let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; - if (weekNumber < 1) { - weekYear = year - 1; - weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); - } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) { - weekYear = year + 1; - weekNumber = 1; - } else { - weekYear = year; - } - return { weekYear, weekNumber, weekday, ...timeObject(gregObj) }; -} -function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { weekYear, weekNumber, weekday } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); - let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year; - if (ordinal < 1) { - year = weekYear - 1; - ordinal += daysInYear(year); - } else if (ordinal > yearInDays) { - year = weekYear + 1; - ordinal -= daysInYear(weekYear); - } else { - year = weekYear; - } - const { month, day } = uncomputeOrdinal(year, ordinal); - return { year, month, day, ...timeObject(weekData) }; -} -function gregorianToOrdinal(gregData) { - const { year, month, day } = gregData; - const ordinal = computeOrdinal(year, month, day); - return { year, ordinal, ...timeObject(gregData) }; -} -function ordinalToGregorian(ordinalData) { - const { year, ordinal } = ordinalData; - const { month, day } = uncomputeOrdinal(year, ordinal); - return { year, month, day, ...timeObject(ordinalData) }; -} -function usesLocalWeekValues(obj, loc) { - const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); - if (hasLocaleWeekData) { - const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); - if (hasIsoWeekData) { - throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields"); - } - if (!isUndefined(obj.localWeekday)) - obj.weekday = obj.localWeekday; - if (!isUndefined(obj.localWeekNumber)) - obj.weekNumber = obj.localWeekNumber; - if (!isUndefined(obj.localWeekYear)) - obj.weekYear = obj.localWeekYear; - delete obj.localWeekday; - delete obj.localWeekNumber; - delete obj.localWeekYear; - return { - minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), - startOfWeek: loc.getStartOfWeek() - }; - } else { - return { minDaysInFirstWeek: 4, startOfWeek: 1 }; - } -} -function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)), validWeekday = integerBetween(obj.weekday, 1, 7); - if (!validYear) { - return unitOutOfRange("weekYear", obj.weekYear); - } else if (!validWeek) { - return unitOutOfRange("week", obj.weekNumber); - } else if (!validWeekday) { - return unitOutOfRange("weekday", obj.weekday); - } else - return false; -} -function hasInvalidOrdinalData(obj) { - const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); - if (!validYear) { - return unitOutOfRange("year", obj.year); - } else if (!validOrdinal) { - return unitOutOfRange("ordinal", obj.ordinal); - } else - return false; -} -function hasInvalidGregorianData(obj) { - const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); - if (!validYear) { - return unitOutOfRange("year", obj.year); - } else if (!validMonth) { - return unitOutOfRange("month", obj.month); - } else if (!validDay) { - return unitOutOfRange("day", obj.day); - } else - return false; -} -function hasInvalidTimeData(obj) { - const { hour, minute, second, millisecond } = obj; - const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); - if (!validHour) { - return unitOutOfRange("hour", hour); - } else if (!validMinute) { - return unitOutOfRange("minute", minute); - } else if (!validSecond) { - return unitOutOfRange("second", second); - } else if (!validMillisecond) { - return unitOutOfRange("millisecond", millisecond); - } else - return false; -} - -// node_modules/luxon/src/impl/util.js -function isUndefined(o) { - return typeof o === "undefined"; -} -function isNumber(o) { - return typeof o === "number"; -} -function isInteger(o) { - return typeof o === "number" && o % 1 === 0; -} -function isString(o) { - return typeof o === "string"; -} -function isDate(o) { - return Object.prototype.toString.call(o) === "[object Date]"; -} -function hasRelative() { - try { - return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; - } catch (e) { - return false; - } -} -function hasLocaleWeekInfo() { - try { - return typeof Intl !== "undefined" && !!Intl.Locale && ("weekInfo" in Intl.Locale.prototype || "getWeekInfo" in Intl.Locale.prototype); - } catch (e) { - return false; - } -} -function maybeArray(thing) { - return Array.isArray(thing) ? thing : [thing]; -} -function bestBy(arr, by, compare) { - if (arr.length === 0) { - return void 0; - } - return arr.reduce((best, next) => { - const pair = [by(next), next]; - if (!best) { - return pair; - } else if (compare(best[0], pair[0]) === best[0]) { - return best; - } else { - return pair; - } - }, null)[1]; -} -function pick(obj, keys) { - return keys.reduce((a, k) => { - a[k] = obj[k]; - return a; - }, {}); -} -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} -function validateWeekSettings(settings) { - if (settings == null) { - return null; - } else if (typeof settings !== "object") { - throw new InvalidArgumentError("Week settings must be an object"); - } else { - if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v) => !integerBetween(v, 1, 7))) { - throw new InvalidArgumentError("Invalid week settings"); - } - return { - firstDay: settings.firstDay, - minimalDays: settings.minimalDays, - weekend: Array.from(settings.weekend) - }; - } -} -function integerBetween(thing, bottom2, top2) { - return isInteger(thing) && thing >= bottom2 && thing <= top2; -} -function floorMod(x, n2) { - return x - n2 * Math.floor(x / n2); -} -function padStart(input, n2 = 2) { - const isNeg = input < 0; - let padded; - if (isNeg) { - padded = "-" + ("" + -input).padStart(n2, "0"); - } else { - padded = ("" + input).padStart(n2, "0"); - } - return padded; -} -function parseInteger(string) { - if (isUndefined(string) || string === null || string === "") { - return void 0; - } else { - return parseInt(string, 10); - } -} -function parseFloating(string) { - if (isUndefined(string) || string === null || string === "") { - return void 0; - } else { - return parseFloat(string); - } -} -function parseMillis(fraction) { - if (isUndefined(fraction) || fraction === null || fraction === "") { - return void 0; - } else { - const f = parseFloat("0." + fraction) * 1e3; - return Math.floor(f); - } -} -function roundTo(number, digits, towardZero = false) { - const factor = 10 ** digits, rounder = towardZero ? Math.trunc : Math.round; - return rounder(number * factor) / factor; -} -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; -} -function daysInMonth(year, month) { - const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; - if (modMonth === 2) { - return isLeapYear(modYear) ? 29 : 28; - } else { - return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; - } -} -function objToLocalTS(obj) { - let d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); - if (obj.year < 100 && obj.year >= 0) { - d = new Date(d); - d.setUTCFullYear(obj.year, obj.month - 1, obj.day); - } - return +d; -} -function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { - const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); - return -fwdlw + minDaysInFirstWeek - 1; -} -function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { - const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); - const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); - return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; -} -function untruncateYear(year) { - if (year > 99) { - return year; - } else - return year > Settings.twoDigitCutoffYear ? 1900 + year : 2e3 + year; -} -function parseZoneInfo(ts, offsetFormat, locale, timeZone = null) { - const date = new Date(ts), intlOpts = { - hourCycle: "h23", - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit" - }; - if (timeZone) { - intlOpts.timeZone = timeZone; - } - const modified = { timeZoneName: offsetFormat, ...intlOpts }; - const parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find((m) => m.type.toLowerCase() === "timezonename"); - return parsed ? parsed.value : null; -} -function signedOffset(offHourStr, offMinuteStr) { - let offHour = parseInt(offHourStr, 10); - if (Number.isNaN(offHour)) { - offHour = 0; - } - const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; - return offHour * 60 + offMinSigned; -} -function asNumber(value) { - const numericValue = Number(value); - if (typeof value === "boolean" || value === "" || Number.isNaN(numericValue)) - throw new InvalidArgumentError(`Invalid unit value ${value}`); - return numericValue; -} -function normalizeObject(obj, normalizer) { - const normalized = {}; - for (const u in obj) { - if (hasOwnProperty(obj, u)) { - const v = obj[u]; - if (v === void 0 || v === null) - continue; - normalized[normalizer(u)] = asNumber(v); - } - } - return normalized; -} -function formatOffset(offset3, format) { - const hours = Math.trunc(Math.abs(offset3 / 60)), minutes = Math.trunc(Math.abs(offset3 % 60)), sign = offset3 >= 0 ? "+" : "-"; - switch (format) { - case "short": - return `${sign}${padStart(hours, 2)}:${padStart(minutes, 2)}`; - case "narrow": - return `${sign}${hours}${minutes > 0 ? `:${minutes}` : ""}`; - case "techie": - return `${sign}${padStart(hours, 2)}${padStart(minutes, 2)}`; - default: - throw new RangeError(`Value format ${format} is out of range for property format`); - } -} -function timeObject(obj) { - return pick(obj, ["hour", "minute", "second", "millisecond"]); -} - -// node_modules/luxon/src/impl/english.js -var monthsLong = [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" -]; -var monthsShort = [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" -]; -var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; -function months(length) { - switch (length) { - case "narrow": - return [...monthsNarrow]; - case "short": - return [...monthsShort]; - case "long": - return [...monthsLong]; - case "numeric": - return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; - case "2-digit": - return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; - default: - return null; - } -} -var weekdaysLong = [ - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - "Sunday" -]; -var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; -var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; -function weekdays(length) { - switch (length) { - case "narrow": - return [...weekdaysNarrow]; - case "short": - return [...weekdaysShort]; - case "long": - return [...weekdaysLong]; - case "numeric": - return ["1", "2", "3", "4", "5", "6", "7"]; - default: - return null; - } -} -var meridiems = ["AM", "PM"]; -var erasLong = ["Before Christ", "Anno Domini"]; -var erasShort = ["BC", "AD"]; -var erasNarrow = ["B", "A"]; -function eras(length) { - switch (length) { - case "narrow": - return [...erasNarrow]; - case "short": - return [...erasShort]; - case "long": - return [...erasLong]; - default: - return null; - } -} -function meridiemForDateTime(dt) { - return meridiems[dt.hour < 12 ? 0 : 1]; -} -function weekdayForDateTime(dt, length) { - return weekdays(length)[dt.weekday - 1]; -} -function monthForDateTime(dt, length) { - return months(length)[dt.month - 1]; -} -function eraForDateTime(dt, length) { - return eras(length)[dt.year < 0 ? 0 : 1]; -} -function formatRelativeTime(unit, count, numeric = "always", narrow = false) { - const units = { - years: ["year", "yr."], - quarters: ["quarter", "qtr."], - months: ["month", "mo."], - weeks: ["week", "wk."], - days: ["day", "day", "days"], - hours: ["hour", "hr."], - minutes: ["minute", "min."], - seconds: ["second", "sec."] - }; - const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; - if (numeric === "auto" && lastable) { - const isDay = unit === "days"; - switch (count) { - case 1: - return isDay ? "tomorrow" : `next ${units[unit][0]}`; - case -1: - return isDay ? "yesterday" : `last ${units[unit][0]}`; - case 0: - return isDay ? "today" : `this ${units[unit][0]}`; - default: - } - } - const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; - return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; -} - -// node_modules/luxon/src/impl/formatter.js -function stringifyTokens(splits, tokenToString) { - let s2 = ""; - for (const token of splits) { - if (token.literal) { - s2 += token.val; - } else { - s2 += tokenToString(token.val); - } - } - return s2; -} -var macroTokenToFormatOpts = { - D: DATE_SHORT, - DD: DATE_MED, - DDD: DATE_FULL, - DDDD: DATE_HUGE, - t: TIME_SIMPLE, - tt: TIME_WITH_SECONDS, - ttt: TIME_WITH_SHORT_OFFSET, - tttt: TIME_WITH_LONG_OFFSET, - T: TIME_24_SIMPLE, - TT: TIME_24_WITH_SECONDS, - TTT: TIME_24_WITH_SHORT_OFFSET, - TTTT: TIME_24_WITH_LONG_OFFSET, - f: DATETIME_SHORT, - ff: DATETIME_MED, - fff: DATETIME_FULL, - ffff: DATETIME_HUGE, - F: DATETIME_SHORT_WITH_SECONDS, - FF: DATETIME_MED_WITH_SECONDS, - FFF: DATETIME_FULL_WITH_SECONDS, - FFFF: DATETIME_HUGE_WITH_SECONDS -}; -var Formatter = class { - static create(locale, opts = {}) { - return new Formatter(locale, opts); - } - static parseFormat(fmt) { - let current = null, currentFull = "", bracketed = false; - const splits = []; - for (let i = 0; i < fmt.length; i++) { - const c = fmt.charAt(i); - if (c === "'") { - if (currentFull.length > 0) { - splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); - } - current = null; - currentFull = ""; - bracketed = !bracketed; - } else if (bracketed) { - currentFull += c; - } else if (c === current) { - currentFull += c; - } else { - if (currentFull.length > 0) { - splits.push({ literal: /^\s+$/.test(currentFull), val: currentFull }); - } - currentFull = c; - current = c; - } - } - if (currentFull.length > 0) { - splits.push({ literal: bracketed || /^\s+$/.test(currentFull), val: currentFull }); - } - return splits; - } - static macroTokenToFormatOpts(token) { - return macroTokenToFormatOpts[token]; - } - constructor(locale, formatOpts) { - this.opts = formatOpts; - this.loc = locale; - this.systemLoc = null; - } - formatWithSystemDefault(dt, opts) { - if (this.systemLoc === null) { - this.systemLoc = this.loc.redefaultToSystem(); - } - const df = this.systemLoc.dtFormatter(dt, { ...this.opts, ...opts }); - return df.format(); - } - dtFormatter(dt, opts = {}) { - return this.loc.dtFormatter(dt, { ...this.opts, ...opts }); - } - formatDateTime(dt, opts) { - return this.dtFormatter(dt, opts).format(); - } - formatDateTimeParts(dt, opts) { - return this.dtFormatter(dt, opts).formatToParts(); - } - formatInterval(interval, opts) { - const df = this.dtFormatter(interval.start, opts); - return df.dtf.formatRange(interval.start.toJSDate(), interval.end.toJSDate()); - } - resolvedOptions(dt, opts) { - return this.dtFormatter(dt, opts).resolvedOptions(); - } - num(n2, p = 0) { - if (this.opts.forceSimple) { - return padStart(n2, p); - } - const opts = { ...this.opts }; - if (p > 0) { - opts.padTo = p; - } - return this.loc.numberFormatter(opts).format(n2); - } - formatDateTimeFromString(dt, fmt) { - const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => { - if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { - return "Z"; - } - return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; - }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string({ hour: "numeric", hourCycle: "h12" }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: "numeric" }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { weekday: length } : { weekday: length, month: "long", day: "numeric" }, "weekday"), maybeMacro = (token) => { - const formatOpts = Formatter.macroTokenToFormatOpts(token); - if (formatOpts) { - return this.formatWithSystemDefault(dt, formatOpts); - } else { - return token; - } - }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, "era"), tokenToString = (token) => { - switch (token) { - case "S": - return this.num(dt.millisecond); - case "u": - case "SSS": - return this.num(dt.millisecond, 3); - case "s": - return this.num(dt.second); - case "ss": - return this.num(dt.second, 2); - case "uu": - return this.num(Math.floor(dt.millisecond / 10), 2); - case "uuu": - return this.num(Math.floor(dt.millisecond / 100)); - case "m": - return this.num(dt.minute); - case "mm": - return this.num(dt.minute, 2); - case "h": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); - case "hh": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); - case "H": - return this.num(dt.hour); - case "HH": - return this.num(dt.hour, 2); - case "Z": - return formatOffset2({ format: "narrow", allowZ: this.opts.allowZ }); - case "ZZ": - return formatOffset2({ format: "short", allowZ: this.opts.allowZ }); - case "ZZZ": - return formatOffset2({ format: "techie", allowZ: this.opts.allowZ }); - case "ZZZZ": - return dt.zone.offsetName(dt.ts, { format: "short", locale: this.loc.locale }); - case "ZZZZZ": - return dt.zone.offsetName(dt.ts, { format: "long", locale: this.loc.locale }); - case "z": - return dt.zoneName; - case "a": - return meridiem(); - case "d": - return useDateTimeFormatter ? string({ day: "numeric" }, "day") : this.num(dt.day); - case "dd": - return useDateTimeFormatter ? string({ day: "2-digit" }, "day") : this.num(dt.day, 2); - case "c": - return this.num(dt.weekday); - case "ccc": - return weekday("short", true); - case "cccc": - return weekday("long", true); - case "ccccc": - return weekday("narrow", true); - case "E": - return this.num(dt.weekday); - case "EEE": - return weekday("short", false); - case "EEEE": - return weekday("long", false); - case "EEEEE": - return weekday("narrow", false); - case "L": - return useDateTimeFormatter ? string({ month: "numeric", day: "numeric" }, "month") : this.num(dt.month); - case "LL": - return useDateTimeFormatter ? string({ month: "2-digit", day: "numeric" }, "month") : this.num(dt.month, 2); - case "LLL": - return month("short", true); - case "LLLL": - return month("long", true); - case "LLLLL": - return month("narrow", true); - case "M": - return useDateTimeFormatter ? string({ month: "numeric" }, "month") : this.num(dt.month); - case "MM": - return useDateTimeFormatter ? string({ month: "2-digit" }, "month") : this.num(dt.month, 2); - case "MMM": - return month("short", false); - case "MMMM": - return month("long", false); - case "MMMMM": - return month("narrow", false); - case "y": - return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year); - case "yy": - return useDateTimeFormatter ? string({ year: "2-digit" }, "year") : this.num(dt.year.toString().slice(-2), 2); - case "yyyy": - return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 4); - case "yyyyyy": - return useDateTimeFormatter ? string({ year: "numeric" }, "year") : this.num(dt.year, 6); - case "G": - return era("short"); - case "GG": - return era("long"); - case "GGGGG": - return era("narrow"); - case "kk": - return this.num(dt.weekYear.toString().slice(-2), 2); - case "kkkk": - return this.num(dt.weekYear, 4); - case "W": - return this.num(dt.weekNumber); - case "WW": - return this.num(dt.weekNumber, 2); - case "n": - return this.num(dt.localWeekNumber); - case "nn": - return this.num(dt.localWeekNumber, 2); - case "ii": - return this.num(dt.localWeekYear.toString().slice(-2), 2); - case "iiii": - return this.num(dt.localWeekYear, 4); - case "o": - return this.num(dt.ordinal); - case "ooo": - return this.num(dt.ordinal, 3); - case "q": - return this.num(dt.quarter); - case "qq": - return this.num(dt.quarter, 2); - case "X": - return this.num(Math.floor(dt.ts / 1e3)); - case "x": - return this.num(dt.ts); - default: - return maybeMacro(token); - } - }; - return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); - } - formatDurationFromString(dur, fmt) { - const tokenToField = (token) => { - switch (token[0]) { - case "S": - return "millisecond"; - case "s": - return "second"; - case "m": - return "minute"; - case "h": - return "hour"; - case "d": - return "day"; - case "w": - return "week"; - case "M": - return "month"; - case "y": - return "year"; - default: - return null; - } - }, tokenToString = (lildur) => (token) => { - const mapped = tokenToField(token); - if (mapped) { - return this.num(lildur.get(mapped), token.length); - } else { - return token; - } - }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, { literal, val }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t) => t)); - return stringifyTokens(tokens, tokenToString(collapsed)); - } -}; - -// node_modules/luxon/src/impl/regexParser.js -var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; -function combineRegexes(...regexes) { - const full = regexes.reduce((f, r) => f + r.source, ""); - return RegExp(`^${full}$`); -} -function combineExtractors(...extractors) { - return (m) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => { - const [val, zone, next] = ex(m, cursor); - return [{ ...mergedVals, ...val }, zone || mergedZone, next]; - }, [{}, null, 1]).slice(0, 2); -} -function parse(s2, ...patterns) { - if (s2 == null) { - return [null, null]; - } - for (const [regex, extractor] of patterns) { - const m = regex.exec(s2); - if (m) { - return extractor(m); - } - } - return [null, null]; -} -function simpleParse(...keys) { - return (match3, cursor) => { - const ret = {}; - let i; - for (i = 0; i < keys.length; i++) { - ret[keys[i]] = parseInteger(match3[cursor + i]); - } - return [ret, null, cursor + i]; - }; -} -var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; -var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; -var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; -var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); -var isoTimeExtensionRegex = RegExp(`(?:T${isoTimeRegex.source})?`); -var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; -var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; -var isoOrdinalRegex = /(\d{4})-?(\d{3})/; -var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); -var extractISOOrdinalData = simpleParse("year", "ordinal"); -var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; -var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`); -var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); -function int(match3, pos, fallback) { - const m = match3[pos]; - return isUndefined(m) ? fallback : parseInteger(m); -} -function extractISOYmd(match3, cursor) { - const item = { - year: int(match3, cursor), - month: int(match3, cursor + 1, 1), - day: int(match3, cursor + 2, 1) - }; - return [item, null, cursor + 3]; -} -function extractISOTime(match3, cursor) { - const item = { - hours: int(match3, cursor, 0), - minutes: int(match3, cursor + 1, 0), - seconds: int(match3, cursor + 2, 0), - milliseconds: parseMillis(match3[cursor + 3]) - }; - return [item, null, cursor + 4]; -} -function extractISOOffset(match3, cursor) { - const local = !match3[cursor] && !match3[cursor + 1], fullOffset = signedOffset(match3[cursor + 1], match3[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); - return [{}, zone, cursor + 3]; -} -function extractIANAZone(match3, cursor) { - const zone = match3[cursor] ? IANAZone.create(match3[cursor]) : null; - return [{}, zone, cursor + 1]; -} -var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); -var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; -function extractISODuration(match3) { - const [s2, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match3; - const hasNegativePrefix = s2[0] === "-"; - const negativeSeconds = secondStr && secondStr[0] === "-"; - const maybeNegate = (num, force = false) => num !== void 0 && (force || num && hasNegativePrefix) ? -num : num; - return [ - { - years: maybeNegate(parseFloating(yearStr)), - months: maybeNegate(parseFloating(monthStr)), - weeks: maybeNegate(parseFloating(weekStr)), - days: maybeNegate(parseFloating(dayStr)), - hours: maybeNegate(parseFloating(hourStr)), - minutes: maybeNegate(parseFloating(minuteStr)), - seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), - milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) - } - ]; -} -var obsOffsets = { - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60 -}; -function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - const result = { - year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), - month: monthsShort.indexOf(monthStr) + 1, - day: parseInteger(dayStr), - hour: parseInteger(hourStr), - minute: parseInteger(minuteStr) - }; - if (secondStr) - result.second = parseInteger(secondStr); - if (weekdayStr) { - result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; - } - return result; -} -var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; -function extractRFC2822(match3) { - const [ - , - weekdayStr, - dayStr, - monthStr, - yearStr, - hourStr, - minuteStr, - secondStr, - obsOffset, - milOffset, - offHourStr, - offMinuteStr - ] = match3, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - let offset3; - if (obsOffset) { - offset3 = obsOffsets[obsOffset]; - } else if (milOffset) { - offset3 = 0; - } else { - offset3 = signedOffset(offHourStr, offMinuteStr); - } - return [result, new FixedOffsetZone(offset3)]; -} -function preprocessRFC2822(s2) { - return s2.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); -} -var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; -var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; -var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; -function extractRFC1123Or850(match3) { - const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match3, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - return [result, FixedOffsetZone.utcInstance]; -} -function extractASCII(match3) { - const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match3, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - return [result, FixedOffsetZone.utcInstance]; -} -var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); -var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); -var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); -var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); -var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); -var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); -var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); -var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); -function parseISODate(s2) { - return parse(s2, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); -} -function parseRFC2822Date(s2) { - return parse(preprocessRFC2822(s2), [rfc2822, extractRFC2822]); -} -function parseHTTPDate(s2) { - return parse(s2, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); -} -function parseISODuration(s2) { - return parse(s2, [isoDuration, extractISODuration]); -} -var extractISOTimeOnly = combineExtractors(extractISOTime); -function parseISOTimeOnly(s2) { - return parse(s2, [isoTimeOnly, extractISOTimeOnly]); -} -var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); -var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); -var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); -function parseSQL(s2) { - return parse(s2, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); -} - -// node_modules/luxon/src/duration.js -var INVALID = "Invalid Duration"; -var lowOrderMatrix = { - weeks: { - days: 7, - hours: 7 * 24, - minutes: 7 * 24 * 60, - seconds: 7 * 24 * 60 * 60, - milliseconds: 7 * 24 * 60 * 60 * 1e3 - }, - days: { - hours: 24, - minutes: 24 * 60, - seconds: 24 * 60 * 60, - milliseconds: 24 * 60 * 60 * 1e3 - }, - hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1e3 }, - minutes: { seconds: 60, milliseconds: 60 * 1e3 }, - seconds: { milliseconds: 1e3 } -}; -var casualMatrix = { - years: { - quarters: 4, - months: 12, - weeks: 52, - days: 365, - hours: 365 * 24, - minutes: 365 * 24 * 60, - seconds: 365 * 24 * 60 * 60, - milliseconds: 365 * 24 * 60 * 60 * 1e3 - }, - quarters: { - months: 3, - weeks: 13, - days: 91, - hours: 91 * 24, - minutes: 91 * 24 * 60, - seconds: 91 * 24 * 60 * 60, - milliseconds: 91 * 24 * 60 * 60 * 1e3 - }, - months: { - weeks: 4, - days: 30, - hours: 30 * 24, - minutes: 30 * 24 * 60, - seconds: 30 * 24 * 60 * 60, - milliseconds: 30 * 24 * 60 * 60 * 1e3 - }, - ...lowOrderMatrix -}; -var daysInYearAccurate = 146097 / 400; -var daysInMonthAccurate = 146097 / 4800; -var accurateMatrix = { - years: { - quarters: 4, - months: 12, - weeks: daysInYearAccurate / 7, - days: daysInYearAccurate, - hours: daysInYearAccurate * 24, - minutes: daysInYearAccurate * 24 * 60, - seconds: daysInYearAccurate * 24 * 60 * 60, - milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 - }, - quarters: { - months: 3, - weeks: daysInYearAccurate / 28, - days: daysInYearAccurate / 4, - hours: daysInYearAccurate * 24 / 4, - minutes: daysInYearAccurate * 24 * 60 / 4, - seconds: daysInYearAccurate * 24 * 60 * 60 / 4, - milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1e3 / 4 - }, - months: { - weeks: daysInMonthAccurate / 7, - days: daysInMonthAccurate, - hours: daysInMonthAccurate * 24, - minutes: daysInMonthAccurate * 24 * 60, - seconds: daysInMonthAccurate * 24 * 60 * 60, - milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1e3 - }, - ...lowOrderMatrix -}; -var orderedUnits = [ - "years", - "quarters", - "months", - "weeks", - "days", - "hours", - "minutes", - "seconds", - "milliseconds" -]; -var reverseUnits = orderedUnits.slice(0).reverse(); -function clone(dur, alts, clear = false) { - const conf = { - values: clear ? alts.values : { ...dur.values, ...alts.values || {} }, - loc: dur.loc.clone(alts.loc), - conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, - matrix: alts.matrix || dur.matrix - }; - return new Duration(conf); -} -function durationToMillis(matrix, vals) { - let sum = vals.milliseconds ?? 0; - for (const unit of reverseUnits.slice(1)) { - if (vals[unit]) { - sum += vals[unit] * matrix[unit]["milliseconds"]; - } - } - return sum; -} -function normalizeValues(matrix, vals) { - const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; - orderedUnits.reduceRight((previous, current) => { - if (!isUndefined(vals[current])) { - if (previous) { - const previousVal = vals[previous] * factor; - const conv = matrix[current][previous]; - const rollUp = Math.floor(previousVal / conv); - vals[current] += rollUp * factor; - vals[previous] -= rollUp * conv * factor; - } - return current; - } else { - return previous; - } - }, null); - orderedUnits.reduce((previous, current) => { - if (!isUndefined(vals[current])) { - if (previous) { - const fraction = vals[previous] % 1; - vals[previous] -= fraction; - vals[current] += fraction * matrix[previous][current]; - } - return current; - } else { - return previous; - } - }, null); -} -function removeZeroes(vals) { - const newVals = {}; - for (const [key, value] of Object.entries(vals)) { - if (value !== 0) { - newVals[key] = value; - } - } - return newVals; -} -var Duration = class { - constructor(config) { - const accurate = config.conversionAccuracy === "longterm" || false; - let matrix = accurate ? accurateMatrix : casualMatrix; - if (config.matrix) { - matrix = config.matrix; - } - this.values = config.values; - this.loc = config.loc || Locale.create(); - this.conversionAccuracy = accurate ? "longterm" : "casual"; - this.invalid = config.invalid || null; - this.matrix = matrix; - this.isLuxonDuration = true; - } - static fromMillis(count, opts) { - return Duration.fromObject({ milliseconds: count }, opts); - } - static fromObject(obj, opts = {}) { - if (obj == null || typeof obj !== "object") { - throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`); - } - return new Duration({ - values: normalizeObject(obj, Duration.normalizeUnit), - loc: Locale.fromObject(opts), - conversionAccuracy: opts.conversionAccuracy, - matrix: opts.matrix - }); - } - static fromDurationLike(durationLike) { - if (isNumber(durationLike)) { - return Duration.fromMillis(durationLike); - } else if (Duration.isDuration(durationLike)) { - return durationLike; - } else if (typeof durationLike === "object") { - return Duration.fromObject(durationLike); - } else { - throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`); - } - } - static fromISO(text, opts) { - const [parsed] = parseISODuration(text); - if (parsed) { - return Duration.fromObject(parsed, opts); - } else { - return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); - } - } - static fromISOTime(text, opts) { - const [parsed] = parseISOTimeOnly(text); - if (parsed) { - return Duration.fromObject(parsed, opts); - } else { - return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); - } - } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); - } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidDurationError(invalid); - } else { - return new Duration({ invalid }); - } - } - static normalizeUnit(unit) { - const normalized = { - year: "years", - years: "years", - quarter: "quarters", - quarters: "quarters", - month: "months", - months: "months", - week: "weeks", - weeks: "weeks", - day: "days", - days: "days", - hour: "hours", - hours: "hours", - minute: "minutes", - minutes: "minutes", - second: "seconds", - seconds: "seconds", - millisecond: "milliseconds", - milliseconds: "milliseconds" - }[unit ? unit.toLowerCase() : unit]; - if (!normalized) - throw new InvalidUnitError(unit); - return normalized; - } - static isDuration(o) { - return o && o.isLuxonDuration || false; - } - get locale() { - return this.isValid ? this.loc.locale : null; - } - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; - } - toFormat(fmt, opts = {}) { - const fmtOpts = { - ...opts, - floor: opts.round !== false && opts.floor !== false - }; - return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID; - } - toHuman(opts = {}) { - if (!this.isValid) - return INVALID; - const l2 = orderedUnits.map((unit) => { - const val = this.values[unit]; - if (isUndefined(val)) { - return null; - } - return this.loc.numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) }).format(val); - }).filter((n2) => n2); - return this.loc.listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts }).format(l2); - } - toObject() { - if (!this.isValid) - return {}; - return { ...this.values }; - } - toISO() { - if (!this.isValid) - return null; - let s2 = "P"; - if (this.years !== 0) - s2 += this.years + "Y"; - if (this.months !== 0 || this.quarters !== 0) - s2 += this.months + this.quarters * 3 + "M"; - if (this.weeks !== 0) - s2 += this.weeks + "W"; - if (this.days !== 0) - s2 += this.days + "D"; - if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) - s2 += "T"; - if (this.hours !== 0) - s2 += this.hours + "H"; - if (this.minutes !== 0) - s2 += this.minutes + "M"; - if (this.seconds !== 0 || this.milliseconds !== 0) - s2 += roundTo(this.seconds + this.milliseconds / 1e3, 3) + "S"; - if (s2 === "P") - s2 += "T0S"; - return s2; - } - toISOTime(opts = {}) { - if (!this.isValid) - return null; - const millis = this.toMillis(); - if (millis < 0 || millis >= 864e5) - return null; - opts = { - suppressMilliseconds: false, - suppressSeconds: false, - includePrefix: false, - format: "extended", - ...opts, - includeOffset: false - }; - const dateTime = DateTime.fromMillis(millis, { zone: "UTC" }); - return dateTime.toISOTime(opts); - } - toJSON() { - return this.toISO(); - } - toString() { - return this.toISO(); - } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `Duration { values: ${JSON.stringify(this.values)} }`; - } else { - return `Duration { Invalid, reason: ${this.invalidReason} }`; - } - } - toMillis() { - if (!this.isValid) - return NaN; - return durationToMillis(this.matrix, this.values); - } - valueOf() { - return this.toMillis(); - } - plus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration), result = {}; - for (const k of orderedUnits) { - if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) { - result[k] = dur.get(k) + this.get(k); - } - } - return clone(this, { values: result }, true); - } - minus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration); - return this.plus(dur.negate()); - } - mapUnits(fn2) { - if (!this.isValid) - return this; - const result = {}; - for (const k of Object.keys(this.values)) { - result[k] = asNumber(fn2(this.values[k], k)); - } - return clone(this, { values: result }, true); - } - get(unit) { - return this[Duration.normalizeUnit(unit)]; - } - set(values) { - if (!this.isValid) - return this; - const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) }; - return clone(this, { values: mixed }); - } - reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) { - const loc = this.loc.clone({ locale, numberingSystem }); - const opts = { loc, matrix, conversionAccuracy }; - return clone(this, opts); - } - as(unit) { - return this.isValid ? this.shiftTo(unit).get(unit) : NaN; - } - normalize() { - if (!this.isValid) - return this; - const vals = this.toObject(); - normalizeValues(this.matrix, vals); - return clone(this, { values: vals }, true); - } - rescale() { - if (!this.isValid) - return this; - const vals = removeZeroes(this.normalize().shiftToAll().toObject()); - return clone(this, { values: vals }, true); - } - shiftTo(...units) { - if (!this.isValid) - return this; - if (units.length === 0) { - return this; - } - units = units.map((u) => Duration.normalizeUnit(u)); - const built = {}, accumulated = {}, vals = this.toObject(); - let lastUnit; - for (const k of orderedUnits) { - if (units.indexOf(k) >= 0) { - lastUnit = k; - let own = 0; - for (const ak in accumulated) { - own += this.matrix[ak][k] * accumulated[ak]; - accumulated[ak] = 0; - } - if (isNumber(vals[k])) { - own += vals[k]; - } - const i = Math.trunc(own); - built[k] = i; - accumulated[k] = (own * 1e3 - i * 1e3) / 1e3; - } else if (isNumber(vals[k])) { - accumulated[k] = vals[k]; - } - } - for (const key in accumulated) { - if (accumulated[key] !== 0) { - built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; - } - } - normalizeValues(this.matrix, built); - return clone(this, { values: built }, true); - } - shiftToAll() { - if (!this.isValid) - return this; - return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"); - } - negate() { - if (!this.isValid) - return this; - const negated = {}; - for (const k of Object.keys(this.values)) { - negated[k] = this.values[k] === 0 ? 0 : -this.values[k]; - } - return clone(this, { values: negated }, true); - } - get years() { - return this.isValid ? this.values.years || 0 : NaN; - } - get quarters() { - return this.isValid ? this.values.quarters || 0 : NaN; - } - get months() { - return this.isValid ? this.values.months || 0 : NaN; - } - get weeks() { - return this.isValid ? this.values.weeks || 0 : NaN; - } - get days() { - return this.isValid ? this.values.days || 0 : NaN; - } - get hours() { - return this.isValid ? this.values.hours || 0 : NaN; - } - get minutes() { - return this.isValid ? this.values.minutes || 0 : NaN; - } - get seconds() { - return this.isValid ? this.values.seconds || 0 : NaN; - } - get milliseconds() { - return this.isValid ? this.values.milliseconds || 0 : NaN; - } - get isValid() { - return this.invalid === null; - } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - equals(other) { - if (!this.isValid || !other.isValid) { - return false; - } - if (!this.loc.equals(other.loc)) { - return false; - } - function eq(v1, v2) { - if (v1 === void 0 || v1 === 0) - return v2 === void 0 || v2 === 0; - return v1 === v2; - } - for (const u of orderedUnits) { - if (!eq(this.values[u], other.values[u])) { - return false; - } - } - return true; - } -}; - -// node_modules/luxon/src/interval.js -var INVALID2 = "Invalid Interval"; -function validateStartEnd(start2, end2) { - if (!start2 || !start2.isValid) { - return Interval.invalid("missing or invalid start"); - } else if (!end2 || !end2.isValid) { - return Interval.invalid("missing or invalid end"); - } else if (end2 < start2) { - return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start2.toISO()} and end=${end2.toISO()}`); - } else { - return null; - } -} -var Interval = class { - constructor(config) { - this.s = config.start; - this.e = config.end; - this.invalid = config.invalid || null; - this.isLuxonInterval = true; - } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); - } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidIntervalError(invalid); - } else { - return new Interval({ invalid }); - } - } - static fromDateTimes(start2, end2) { - const builtStart = friendlyDateTime(start2), builtEnd = friendlyDateTime(end2); - const validateError = validateStartEnd(builtStart, builtEnd); - if (validateError == null) { - return new Interval({ - start: builtStart, - end: builtEnd - }); - } else { - return validateError; - } - } - static after(start2, duration) { - const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start2); - return Interval.fromDateTimes(dt, dt.plus(dur)); - } - static before(end2, duration) { - const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end2); - return Interval.fromDateTimes(dt.minus(dur), dt); - } - static fromISO(text, opts) { - const [s2, e] = (text || "").split("/", 2); - if (s2 && e) { - let start2, startIsValid; - try { - start2 = DateTime.fromISO(s2, opts); - startIsValid = start2.isValid; - } catch (e2) { - startIsValid = false; - } - let end2, endIsValid; - try { - end2 = DateTime.fromISO(e, opts); - endIsValid = end2.isValid; - } catch (e2) { - endIsValid = false; - } - if (startIsValid && endIsValid) { - return Interval.fromDateTimes(start2, end2); - } - if (startIsValid) { - const dur = Duration.fromISO(e, opts); - if (dur.isValid) { - return Interval.after(start2, dur); - } - } else if (endIsValid) { - const dur = Duration.fromISO(s2, opts); - if (dur.isValid) { - return Interval.before(end2, dur); - } - } - } - return Interval.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`); - } - static isInterval(o) { - return o && o.isLuxonInterval || false; - } - get start() { - return this.isValid ? this.s : null; - } - get end() { - return this.isValid ? this.e : null; - } - get isValid() { - return this.invalidReason === null; - } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - length(unit = "milliseconds") { - return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; - } - count(unit = "milliseconds", opts) { - if (!this.isValid) - return NaN; - const start2 = this.start.startOf(unit, opts); - let end2; - if (opts?.useLocaleWeeks) { - end2 = this.end.reconfigure({ locale: start2.locale }); - } else { - end2 = this.end; - } - end2 = end2.startOf(unit, opts); - return Math.floor(end2.diff(start2, unit).get(unit)) + (end2.valueOf() !== this.end.valueOf()); - } - hasSame(unit) { - return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; - } - isEmpty() { - return this.s.valueOf() === this.e.valueOf(); - } - isAfter(dateTime) { - if (!this.isValid) - return false; - return this.s > dateTime; - } - isBefore(dateTime) { - if (!this.isValid) - return false; - return this.e <= dateTime; - } - contains(dateTime) { - if (!this.isValid) - return false; - return this.s <= dateTime && this.e > dateTime; - } - set({ start: start2, end: end2 } = {}) { - if (!this.isValid) - return this; - return Interval.fromDateTimes(start2 || this.s, end2 || this.e); - } - splitAt(...dateTimes) { - if (!this.isValid) - return []; - const sorted = dateTimes.map(friendlyDateTime).filter((d) => this.contains(d)).sort((a, b) => a.toMillis() - b.toMillis()), results = []; - let { s: s2 } = this, i = 0; - while (s2 < this.e) { - const added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; - results.push(Interval.fromDateTimes(s2, next)); - s2 = next; - i += 1; - } - return results; - } - splitBy(duration) { - const dur = Duration.fromDurationLike(duration); - if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { - return []; - } - let { s: s2 } = this, idx = 1, next; - const results = []; - while (s2 < this.e) { - const added = this.start.plus(dur.mapUnits((x) => x * idx)); - next = +added > +this.e ? this.e : added; - results.push(Interval.fromDateTimes(s2, next)); - s2 = next; - idx += 1; - } - return results; - } - divideEqually(numberOfParts) { - if (!this.isValid) - return []; - return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); - } - overlaps(other) { - return this.e > other.s && this.s < other.e; - } - abutsStart(other) { - if (!this.isValid) - return false; - return +this.e === +other.s; - } - abutsEnd(other) { - if (!this.isValid) - return false; - return +other.e === +this.s; - } - engulfs(other) { - if (!this.isValid) - return false; - return this.s <= other.s && this.e >= other.e; - } - equals(other) { - if (!this.isValid || !other.isValid) { - return false; - } - return this.s.equals(other.s) && this.e.equals(other.e); - } - intersection(other) { - if (!this.isValid) - return this; - const s2 = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; - if (s2 >= e) { - return null; - } else { - return Interval.fromDateTimes(s2, e); - } - } - union(other) { - if (!this.isValid) - return this; - const s2 = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; - return Interval.fromDateTimes(s2, e); - } - static merge(intervals) { - const [found, final] = intervals.sort((a, b) => a.s - b.s).reduce(([sofar, current], item) => { - if (!current) { - return [sofar, item]; - } else if (current.overlaps(item) || current.abutsStart(item)) { - return [sofar, current.union(item)]; - } else { - return [sofar.concat([current]), item]; - } - }, [[], null]); - if (final) { - found.push(final); - } - return found; - } - static xor(intervals) { - let start2 = null, currentCount = 0; - const results = [], ends = intervals.map((i) => [ - { time: i.s, type: "s" }, - { time: i.e, type: "e" } - ]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a, b) => a.time - b.time); - for (const i of arr) { - currentCount += i.type === "s" ? 1 : -1; - if (currentCount === 1) { - start2 = i.time; - } else { - if (start2 && +start2 !== +i.time) { - results.push(Interval.fromDateTimes(start2, i.time)); - } - start2 = null; - } - } - return Interval.merge(results); - } - difference(...intervals) { - return Interval.xor([this].concat(intervals)).map((i) => this.intersection(i)).filter((i) => i && !i.isEmpty()); - } - toString() { - if (!this.isValid) - return INVALID2; - return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; - } else { - return `Interval { Invalid, reason: ${this.invalidReason} }`; - } - } - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID2; - } - toISO(opts) { - if (!this.isValid) - return INVALID2; - return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; - } - toISODate() { - if (!this.isValid) - return INVALID2; - return `${this.s.toISODate()}/${this.e.toISODate()}`; - } - toISOTime(opts) { - if (!this.isValid) - return INVALID2; - return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; - } - toFormat(dateFormat, { separator = " \u2013 " } = {}) { - if (!this.isValid) - return INVALID2; - return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; - } - toDuration(unit, opts) { - if (!this.isValid) { - return Duration.invalid(this.invalidReason); - } - return this.e.diff(this.s, unit, opts); - } - mapEndpoints(mapFn) { - return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); - } -}; - -// node_modules/luxon/src/info.js -var Info = class { - static hasDST(zone = Settings.defaultZone) { - const proto = DateTime.now().setZone(zone).set({ month: 12 }); - return !zone.isUniversal && proto.offset !== proto.set({ month: 6 }).offset; - } - static isValidIANAZone(zone) { - return IANAZone.isValidZone(zone); - } - static normalizeZone(input) { - return normalizeZone(input, Settings.defaultZone); - } - static getStartOfWeek({ locale = null, locObj = null } = {}) { - return (locObj || Locale.create(locale)).getStartOfWeek(); - } - static getMinimumDaysInFirstWeek({ locale = null, locObj = null } = {}) { - return (locObj || Locale.create(locale)).getMinDaysInFirstWeek(); - } - static getWeekendWeekdays({ locale = null, locObj = null } = {}) { - return (locObj || Locale.create(locale)).getWeekendDays().slice(); - } - static months(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { - return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length); - } - static monthsFormat(length = "long", { locale = null, numberingSystem = null, locObj = null, outputCalendar = "gregory" } = {}) { - return (locObj || Locale.create(locale, numberingSystem, outputCalendar)).months(length, true); - } - static weekdays(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { - return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length); - } - static weekdaysFormat(length = "long", { locale = null, numberingSystem = null, locObj = null } = {}) { - return (locObj || Locale.create(locale, numberingSystem, null)).weekdays(length, true); - } - static meridiems({ locale = null } = {}) { - return Locale.create(locale).meridiems(); - } - static eras(length = "short", { locale = null } = {}) { - return Locale.create(locale, null, "gregory").eras(length); - } - static features() { - return { relative: hasRelative(), localeWeek: hasLocaleWeekInfo() }; - } -}; - -// node_modules/luxon/src/impl/diff.js -function dayDiff(earlier, later) { - const utcDayStart = (dt) => dt.toUTC(0, { keepLocalTime: true }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); - return Math.floor(Duration.fromMillis(ms).as("days")); -} -function highOrderDiffs(cursor, later, units) { - const differs = [ - ["years", (a, b) => b.year - a.year], - ["quarters", (a, b) => b.quarter - a.quarter + (b.year - a.year) * 4], - ["months", (a, b) => b.month - a.month + (b.year - a.year) * 12], - [ - "weeks", - (a, b) => { - const days = dayDiff(a, b); - return (days - days % 7) / 7; - } - ], - ["days", dayDiff] - ]; - const results = {}; - const earlier = cursor; - let lowestOrder, highWater; - for (const [unit, differ] of differs) { - if (units.indexOf(unit) >= 0) { - lowestOrder = unit; - results[unit] = differ(cursor, later); - highWater = earlier.plus(results); - if (highWater > later) { - results[unit]--; - cursor = earlier.plus(results); - if (cursor > later) { - highWater = cursor; - results[unit]--; - cursor = earlier.plus(results); - } - } else { - cursor = highWater; - } - } - } - return [cursor, results, highWater, lowestOrder]; -} -function diff_default(earlier, later, units, opts) { - let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); - const remainingMillis = later - cursor; - const lowerOrderUnits = units.filter((u) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u) >= 0); - if (lowerOrderUnits.length === 0) { - if (highWater < later) { - highWater = cursor.plus({ [lowestOrder]: 1 }); - } - if (highWater !== cursor) { - results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); - } - } - const duration = Duration.fromObject(results, opts); - if (lowerOrderUnits.length > 0) { - return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); - } else { - return duration; - } -} - -// node_modules/luxon/src/impl/digits.js -var numberingSystems = { - arab: "[\u0660-\u0669]", - arabext: "[\u06F0-\u06F9]", - bali: "[\u1B50-\u1B59]", - beng: "[\u09E6-\u09EF]", - deva: "[\u0966-\u096F]", - fullwide: "[\uFF10-\uFF19]", - gujr: "[\u0AE6-\u0AEF]", - hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", - khmr: "[\u17E0-\u17E9]", - knda: "[\u0CE6-\u0CEF]", - laoo: "[\u0ED0-\u0ED9]", - limb: "[\u1946-\u194F]", - mlym: "[\u0D66-\u0D6F]", - mong: "[\u1810-\u1819]", - mymr: "[\u1040-\u1049]", - orya: "[\u0B66-\u0B6F]", - tamldec: "[\u0BE6-\u0BEF]", - telu: "[\u0C66-\u0C6F]", - thai: "[\u0E50-\u0E59]", - tibt: "[\u0F20-\u0F29]", - latn: "\\d" -}; -var numberingSystemsUTF16 = { - arab: [1632, 1641], - arabext: [1776, 1785], - bali: [6992, 7001], - beng: [2534, 2543], - deva: [2406, 2415], - fullwide: [65296, 65303], - gujr: [2790, 2799], - khmr: [6112, 6121], - knda: [3302, 3311], - laoo: [3792, 3801], - limb: [6470, 6479], - mlym: [3430, 3439], - mong: [6160, 6169], - mymr: [4160, 4169], - orya: [2918, 2927], - tamldec: [3046, 3055], - telu: [3174, 3183], - thai: [3664, 3673], - tibt: [3872, 3881] -}; -var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); -function parseDigits(str) { - let value = parseInt(str, 10); - if (isNaN(value)) { - value = ""; - for (let i = 0; i < str.length; i++) { - const code = str.charCodeAt(i); - if (str[i].search(numberingSystems.hanidec) !== -1) { - value += hanidecChars.indexOf(str[i]); - } else { - for (const key in numberingSystemsUTF16) { - const [min2, max2] = numberingSystemsUTF16[key]; - if (code >= min2 && code <= max2) { - value += code - min2; - } - } - } - } - return parseInt(value, 10); - } else { - return value; - } -} -function digitRegex({ numberingSystem }, append = "") { - return new RegExp(`${numberingSystems[numberingSystem || "latn"]}${append}`); -} - -// node_modules/luxon/src/impl/tokenParser.js -var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; -function intUnit(regex, post = (i) => i) { - return { regex, deser: ([s2]) => post(parseDigits(s2)) }; -} -var NBSP = String.fromCharCode(160); -var spaceOrNBSP = `[ ${NBSP}]`; -var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); -function fixListRegex(s2) { - return s2.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); -} -function stripInsensitivities(s2) { - return s2.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); -} -function oneOf(strings, startIndex) { - if (strings === null) { - return null; - } else { - return { - regex: RegExp(strings.map(fixListRegex).join("|")), - deser: ([s2]) => strings.findIndex((i) => stripInsensitivities(s2) === stripInsensitivities(i)) + startIndex - }; - } -} -function offset(regex, groups) { - return { regex, deser: ([, h, m]) => signedOffset(h, m), groups }; -} -function simple(regex) { - return { regex, deser: ([s2]) => s2 }; -} -function escapeToken(value) { - return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -} -function unitForToken(token, loc) { - const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t) => ({ regex: RegExp(escapeToken(t.val)), deser: ([s2]) => s2, literal: true }), unitate = (t) => { - if (token.literal) { - return literal(t); - } - switch (t.val) { - case "G": - return oneOf(loc.eras("short"), 0); - case "GG": - return oneOf(loc.eras("long"), 0); - case "y": - return intUnit(oneToSix); - case "yy": - return intUnit(twoToFour, untruncateYear); - case "yyyy": - return intUnit(four); - case "yyyyy": - return intUnit(fourToSix); - case "yyyyyy": - return intUnit(six); - case "M": - return intUnit(oneOrTwo); - case "MM": - return intUnit(two); - case "MMM": - return oneOf(loc.months("short", true), 1); - case "MMMM": - return oneOf(loc.months("long", true), 1); - case "L": - return intUnit(oneOrTwo); - case "LL": - return intUnit(two); - case "LLL": - return oneOf(loc.months("short", false), 1); - case "LLLL": - return oneOf(loc.months("long", false), 1); - case "d": - return intUnit(oneOrTwo); - case "dd": - return intUnit(two); - case "o": - return intUnit(oneToThree); - case "ooo": - return intUnit(three); - case "HH": - return intUnit(two); - case "H": - return intUnit(oneOrTwo); - case "hh": - return intUnit(two); - case "h": - return intUnit(oneOrTwo); - case "mm": - return intUnit(two); - case "m": - return intUnit(oneOrTwo); - case "q": - return intUnit(oneOrTwo); - case "qq": - return intUnit(two); - case "s": - return intUnit(oneOrTwo); - case "ss": - return intUnit(two); - case "S": - return intUnit(oneToThree); - case "SSS": - return intUnit(three); - case "u": - return simple(oneToNine); - case "uu": - return simple(oneOrTwo); - case "uuu": - return intUnit(one); - case "a": - return oneOf(loc.meridiems(), 0); - case "kkkk": - return intUnit(four); - case "kk": - return intUnit(twoToFour, untruncateYear); - case "W": - return intUnit(oneOrTwo); - case "WW": - return intUnit(two); - case "E": - case "c": - return intUnit(one); - case "EEE": - return oneOf(loc.weekdays("short", false), 1); - case "EEEE": - return oneOf(loc.weekdays("long", false), 1); - case "ccc": - return oneOf(loc.weekdays("short", true), 1); - case "cccc": - return oneOf(loc.weekdays("long", true), 1); - case "Z": - case "ZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); - case "ZZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); - case "z": - return simple(/[a-z_+-/]{1,256}?/i); - case " ": - return simple(/[^\S\n\r]/); - default: - return literal(t); - } - }; - const unit = unitate(token) || { - invalidReason: MISSING_FTP - }; - unit.token = token; - return unit; -} -var partTypeStyleToTokenVal = { - year: { - "2-digit": "yy", - numeric: "yyyyy" - }, - month: { - numeric: "M", - "2-digit": "MM", - short: "MMM", - long: "MMMM" - }, - day: { - numeric: "d", - "2-digit": "dd" - }, - weekday: { - short: "EEE", - long: "EEEE" - }, - dayperiod: "a", - dayPeriod: "a", - hour12: { - numeric: "h", - "2-digit": "hh" - }, - hour24: { - numeric: "H", - "2-digit": "HH" - }, - minute: { - numeric: "m", - "2-digit": "mm" - }, - second: { - numeric: "s", - "2-digit": "ss" - }, - timeZoneName: { - long: "ZZZZZ", - short: "ZZZ" - } -}; -function tokenForPart(part, formatOpts, resolvedOpts) { - const { type, value } = part; - if (type === "literal") { - const isSpace = /^\s+$/.test(value); - return { - literal: !isSpace, - val: isSpace ? " " : value - }; - } - const style = formatOpts[type]; - let actualType = type; - if (type === "hour") { - if (formatOpts.hour12 != null) { - actualType = formatOpts.hour12 ? "hour12" : "hour24"; - } else if (formatOpts.hourCycle != null) { - if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { - actualType = "hour12"; - } else { - actualType = "hour24"; - } - } else { - actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; - } - } - let val = partTypeStyleToTokenVal[actualType]; - if (typeof val === "object") { - val = val[style]; - } - if (val) { - return { - literal: false, - val - }; - } - return void 0; -} -function buildRegex(units) { - const re = units.map((u) => u.regex).reduce((f, r) => `${f}(${r.source})`, ""); - return [`^${re}$`, units]; -} -function match(input, regex, handlers) { - const matches = input.match(regex); - if (matches) { - const all = {}; - let matchIndex = 1; - for (const i in handlers) { - if (hasOwnProperty(handlers, i)) { - const h = handlers[i], groups = h.groups ? h.groups + 1 : 1; - if (!h.literal && h.token) { - all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); - } - matchIndex += groups; - } - } - return [matches, all]; - } else { - return [matches, {}]; - } -} -function dateTimeFromMatches(matches) { - const toField = (token) => { - switch (token) { - case "S": - return "millisecond"; - case "s": - return "second"; - case "m": - return "minute"; - case "h": - case "H": - return "hour"; - case "d": - return "day"; - case "o": - return "ordinal"; - case "L": - case "M": - return "month"; - case "y": - return "year"; - case "E": - case "c": - return "weekday"; - case "W": - return "weekNumber"; - case "k": - return "weekYear"; - case "q": - return "quarter"; - default: - return null; - } - }; - let zone = null; - let specificOffset; - if (!isUndefined(matches.z)) { - zone = IANAZone.create(matches.z); - } - if (!isUndefined(matches.Z)) { - if (!zone) { - zone = new FixedOffsetZone(matches.Z); - } - specificOffset = matches.Z; - } - if (!isUndefined(matches.q)) { - matches.M = (matches.q - 1) * 3 + 1; - } - if (!isUndefined(matches.h)) { - if (matches.h < 12 && matches.a === 1) { - matches.h += 12; - } else if (matches.h === 12 && matches.a === 0) { - matches.h = 0; - } - } - if (matches.G === 0 && matches.y) { - matches.y = -matches.y; - } - if (!isUndefined(matches.u)) { - matches.S = parseMillis(matches.u); - } - const vals = Object.keys(matches).reduce((r, k) => { - const f = toField(k); - if (f) { - r[f] = matches[k]; - } - return r; - }, {}); - return [vals, zone, specificOffset]; -} -var dummyDateTimeCache = null; -function getDummyDateTime() { - if (!dummyDateTimeCache) { - dummyDateTimeCache = DateTime.fromMillis(1555555555555); - } - return dummyDateTimeCache; -} -function maybeExpandMacroToken(token, locale) { - if (token.literal) { - return token; - } - const formatOpts = Formatter.macroTokenToFormatOpts(token.val); - const tokens = formatOptsToTokens(formatOpts, locale); - if (tokens == null || tokens.includes(void 0)) { - return token; - } - return tokens; -} -function expandMacroTokens(tokens, locale) { - return Array.prototype.concat(...tokens.map((t) => maybeExpandMacroToken(t, locale))); -} -function explainFromTokens(locale, input, format) { - const tokens = expandMacroTokens(Formatter.parseFormat(format), locale), units = tokens.map((t) => unitForToken(t, locale)), disqualifyingUnit = units.find((t) => t.invalidReason); - if (disqualifyingUnit) { - return { input, tokens, invalidReason: disqualifyingUnit.invalidReason }; - } else { - const [regexString, handlers] = buildRegex(units), regex = RegExp(regexString, "i"), [rawMatches, matches] = match(input, regex, handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, void 0]; - if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { - throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); - } - return { input, tokens, regex, rawMatches, matches, result, zone, specificOffset }; - } -} -function parseFromTokens(locale, input, format) { - const { result, zone, specificOffset, invalidReason } = explainFromTokens(locale, input, format); - return [result, zone, specificOffset, invalidReason]; -} -function formatOptsToTokens(formatOpts, locale) { - if (!formatOpts) { - return null; - } - const formatter = Formatter.create(locale, formatOpts); - const df = formatter.dtFormatter(getDummyDateTime()); - const parts = df.formatToParts(); - const resolvedOpts = df.resolvedOptions(); - return parts.map((p) => tokenForPart(p, formatOpts, resolvedOpts)); -} - -// node_modules/luxon/src/datetime.js -var INVALID3 = "Invalid DateTime"; -var MAX_DATE = 864e13; -function unsupportedZone(zone) { - return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); -} -function possiblyCachedWeekData(dt) { - if (dt.weekData === null) { - dt.weekData = gregorianToWeek(dt.c); - } - return dt.weekData; -} -function possiblyCachedLocalWeekData(dt) { - if (dt.localWeekData === null) { - dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek()); - } - return dt.localWeekData; -} -function clone2(inst, alts) { - const current = { - ts: inst.ts, - zone: inst.zone, - c: inst.c, - o: inst.o, - loc: inst.loc, - invalid: inst.invalid - }; - return new DateTime({ ...current, ...alts, old: current }); -} -function fixOffset(localTS, o, tz) { - let utcGuess = localTS - o * 60 * 1e3; - const o2 = tz.offset(utcGuess); - if (o === o2) { - return [utcGuess, o]; - } - utcGuess -= (o2 - o) * 60 * 1e3; - const o3 = tz.offset(utcGuess); - if (o2 === o3) { - return [utcGuess, o2]; - } - return [localTS - Math.min(o2, o3) * 60 * 1e3, Math.max(o2, o3)]; -} -function tsToObj(ts, offset3) { - ts += offset3 * 60 * 1e3; - const d = new Date(ts); - return { - year: d.getUTCFullYear(), - month: d.getUTCMonth() + 1, - day: d.getUTCDate(), - hour: d.getUTCHours(), - minute: d.getUTCMinutes(), - second: d.getUTCSeconds(), - millisecond: d.getUTCMilliseconds() - }; -} -function objToTS(obj, offset3, zone) { - return fixOffset(objToLocalTS(obj), offset3, zone); -} -function adjustTime(inst, dur) { - const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c = { - ...inst.c, - year, - month, - day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 - }, millisToAdd = Duration.fromObject({ - years: dur.years - Math.trunc(dur.years), - quarters: dur.quarters - Math.trunc(dur.quarters), - months: dur.months - Math.trunc(dur.months), - weeks: dur.weeks - Math.trunc(dur.weeks), - days: dur.days - Math.trunc(dur.days), - hours: dur.hours, - minutes: dur.minutes, - seconds: dur.seconds, - milliseconds: dur.milliseconds - }).as("milliseconds"), localTS = objToLocalTS(c); - let [ts, o] = fixOffset(localTS, oPre, inst.zone); - if (millisToAdd !== 0) { - ts += millisToAdd; - o = inst.zone.offset(ts); - } - return { ts, o }; -} -function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) { - const { setZone, zone } = opts; - if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { - const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { - ...opts, - zone: interpretationZone, - specificOffset - }); - return setZone ? inst : inst.setZone(zone); - } else { - return DateTime.invalid(new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)); - } -} -function toTechFormat(dt, format, allowZ = true) { - return dt.isValid ? Formatter.create(Locale.create("en-US"), { - allowZ, - forceSimple: true - }).formatDateTimeFromString(dt, format) : null; -} -function toISODate(o, extended) { - const longFormat = o.c.year > 9999 || o.c.year < 0; - let c = ""; - if (longFormat && o.c.year >= 0) - c += "+"; - c += padStart(o.c.year, longFormat ? 6 : 4); - if (extended) { - c += "-"; - c += padStart(o.c.month); - c += "-"; - c += padStart(o.c.day); - } else { - c += padStart(o.c.month); - c += padStart(o.c.day); - } - return c; -} -function toISOTime(o, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone) { - let c = padStart(o.c.hour); - if (extended) { - c += ":"; - c += padStart(o.c.minute); - if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { - c += ":"; - } - } else { - c += padStart(o.c.minute); - } - if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) { - c += padStart(o.c.second); - if (o.c.millisecond !== 0 || !suppressMilliseconds) { - c += "."; - c += padStart(o.c.millisecond, 3); - } - } - if (includeOffset) { - if (o.isOffsetFixed && o.offset === 0 && !extendedZone) { - c += "Z"; - } else if (o.o < 0) { - c += "-"; - c += padStart(Math.trunc(-o.o / 60)); - c += ":"; - c += padStart(Math.trunc(-o.o % 60)); - } else { - c += "+"; - c += padStart(Math.trunc(o.o / 60)); - c += ":"; - c += padStart(Math.trunc(o.o % 60)); - } - } - if (extendedZone) { - c += "[" + o.zone.ianaName + "]"; - } - return c; -} -var defaultUnitValues = { - month: 1, - day: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 -}; -var defaultWeekUnitValues = { - weekNumber: 1, - weekday: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 -}; -var defaultOrdinalUnitValues = { - ordinal: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 -}; -var orderedUnits2 = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; -var orderedWeekUnits = [ - "weekYear", - "weekNumber", - "weekday", - "hour", - "minute", - "second", - "millisecond" -]; -var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; -function normalizeUnit(unit) { - const normalized = { - year: "year", - years: "year", - month: "month", - months: "month", - day: "day", - days: "day", - hour: "hour", - hours: "hour", - minute: "minute", - minutes: "minute", - quarter: "quarter", - quarters: "quarter", - second: "second", - seconds: "second", - millisecond: "millisecond", - milliseconds: "millisecond", - weekday: "weekday", - weekdays: "weekday", - weeknumber: "weekNumber", - weeksnumber: "weekNumber", - weeknumbers: "weekNumber", - weekyear: "weekYear", - weekyears: "weekYear", - ordinal: "ordinal" - }[unit.toLowerCase()]; - if (!normalized) - throw new InvalidUnitError(unit); - return normalized; -} -function normalizeUnitWithLocalWeeks(unit) { - switch (unit.toLowerCase()) { - case "localweekday": - case "localweekdays": - return "localWeekday"; - case "localweeknumber": - case "localweeknumbers": - return "localWeekNumber"; - case "localweekyear": - case "localweekyears": - return "localWeekYear"; - default: - return normalizeUnit(unit); - } -} -function quickDT(obj, opts) { - const zone = normalizeZone(opts.zone, Settings.defaultZone), loc = Locale.fromObject(opts), tsNow = Settings.now(); - let ts, o; - if (!isUndefined(obj.year)) { - for (const u of orderedUnits2) { - if (isUndefined(obj[u])) { - obj[u] = defaultUnitValues[u]; - } - } - const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); - if (invalid) { - return DateTime.invalid(invalid); - } - const offsetProvis = zone.offset(tsNow); - [ts, o] = objToTS(obj, offsetProvis, zone); - } else { - ts = tsNow; - } - return new DateTime({ ts, zone, loc, o }); -} -function diffRelative(start2, end2, opts) { - const round2 = isUndefined(opts.round) ? true : opts.round, format = (c, unit) => { - c = roundTo(c, round2 || opts.calendary ? 0 : 2, true); - const formatter = end2.loc.clone(opts).relFormatter(opts); - return formatter.format(c, unit); - }, differ = (unit) => { - if (opts.calendary) { - if (!end2.hasSame(start2, unit)) { - return end2.startOf(unit).diff(start2.startOf(unit), unit).get(unit); - } else - return 0; - } else { - return end2.diff(start2, unit).get(unit); - } - }; - if (opts.unit) { - return format(differ(opts.unit), opts.unit); - } - for (const unit of opts.units) { - const count = differ(unit); - if (Math.abs(count) >= 1) { - return format(count, unit); - } - } - return format(start2 > end2 ? -0 : 0, opts.units[opts.units.length - 1]); -} -function lastOpts(argList) { - let opts = {}, args; - if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { - opts = argList[argList.length - 1]; - args = Array.from(argList).slice(0, argList.length - 1); - } else { - args = Array.from(argList); - } - return [opts, args]; -} -var DateTime = class { - constructor(config) { - const zone = config.zone || Settings.defaultZone; - let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); - this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; - let c = null, o = null; - if (!invalid) { - const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); - if (unchanged) { - [c, o] = [config.old.c, config.old.o]; - } else { - const ot = zone.offset(this.ts); - c = tsToObj(this.ts, ot); - invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null; - c = invalid ? null : c; - o = invalid ? null : ot; - } - } - this._zone = zone; - this.loc = config.loc || Locale.create(); - this.invalid = invalid; - this.weekData = null; - this.localWeekData = null; - this.c = c; - this.o = o; - this.isLuxonDateTime = true; - } - static now() { - return new DateTime({}); - } - static local() { - const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; - return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); - } - static utc() { - const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; - opts.zone = FixedOffsetZone.utcInstance; - return quickDT({ year, month, day, hour, minute, second, millisecond }, opts); - } - static fromJSDate(date, options = {}) { - const ts = isDate(date) ? date.valueOf() : NaN; - if (Number.isNaN(ts)) { - return DateTime.invalid("invalid input"); - } - const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); - if (!zoneToUse.isValid) { - return DateTime.invalid(unsupportedZone(zoneToUse)); - } - return new DateTime({ - ts, - zone: zoneToUse, - loc: Locale.fromObject(options) - }); - } - static fromMillis(milliseconds, options = {}) { - if (!isNumber(milliseconds)) { - throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`); - } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { - return DateTime.invalid("Timestamp out of range"); - } else { - return new DateTime({ - ts: milliseconds, - zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options) - }); - } - } - static fromSeconds(seconds, options = {}) { - if (!isNumber(seconds)) { - throw new InvalidArgumentError("fromSeconds requires a numerical input"); - } else { - return new DateTime({ - ts: seconds * 1e3, - zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options) - }); - } - } - static fromObject(obj, opts = {}) { - obj = obj || {}; - const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); - if (!zoneToUse.isValid) { - return DateTime.invalid(unsupportedZone(zoneToUse)); - } - const loc = Locale.fromObject(opts); - const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); - const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc); - const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; - if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); - } - if (containsGregorMD && containsOrdinal) { - throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); - } - const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; - let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); - if (useWeekData) { - units = orderedWeekUnits; - defaultValues = defaultWeekUnitValues; - objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek); - } else if (containsOrdinal) { - units = orderedOrdinalUnits; - defaultValues = defaultOrdinalUnitValues; - objNow = gregorianToOrdinal(objNow); - } else { - units = orderedUnits2; - defaultValues = defaultUnitValues; - } - let foundFirst = false; - for (const u of units) { - const v = normalized[u]; - if (!isUndefined(v)) { - foundFirst = true; - } else if (foundFirst) { - normalized[u] = defaultValues[u]; - } else { - normalized[u] = objNow[u]; - } - } - const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); - if (invalid) { - return DateTime.invalid(invalid); - } - const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({ - ts: tsFinal, - zone: zoneToUse, - o: offsetFinal, - loc - }); - if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { - return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`); - } - return inst; - } - static fromISO(text, opts = {}) { - const [vals, parsedZone] = parseISODate(text); - return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text); - } - static fromRFC2822(text, opts = {}) { - const [vals, parsedZone] = parseRFC2822Date(text); - return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text); - } - static fromHTTP(text, opts = {}) { - const [vals, parsedZone] = parseHTTPDate(text); - return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); - } - static fromFormat(text, fmt, opts = {}) { - if (isUndefined(text) || isUndefined(fmt)) { - throw new InvalidArgumentError("fromFormat requires an input string and a format"); - } - const { locale = null, numberingSystem = null } = opts, localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true - }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt); - if (invalid) { - return DateTime.invalid(invalid); - } else { - return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset); - } - } - static fromString(text, fmt, opts = {}) { - return DateTime.fromFormat(text, fmt, opts); - } - static fromSQL(text, opts = {}) { - const [vals, parsedZone] = parseSQL(text); - return parseDataToDateTime(vals, parsedZone, opts, "SQL", text); - } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); - } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidDateTimeError(invalid); - } else { - return new DateTime({ invalid }); - } - } - static isDateTime(o) { - return o && o.isLuxonDateTime || false; - } - static parseFormatForOpts(formatOpts, localeOpts = {}) { - const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); - return !tokenList ? null : tokenList.map((t) => t ? t.val : null).join(""); - } - static expandFormat(fmt, localeOpts = {}) { - const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); - return expanded.map((t) => t.val).join(""); - } - get(unit) { - return this[unit]; - } - get isValid() { - return this.invalid === null; - } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - get locale() { - return this.isValid ? this.loc.locale : null; - } - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; - } - get outputCalendar() { - return this.isValid ? this.loc.outputCalendar : null; - } - get zone() { - return this._zone; - } - get zoneName() { - return this.isValid ? this.zone.name : null; - } - get year() { - return this.isValid ? this.c.year : NaN; - } - get quarter() { - return this.isValid ? Math.ceil(this.c.month / 3) : NaN; - } - get month() { - return this.isValid ? this.c.month : NaN; - } - get day() { - return this.isValid ? this.c.day : NaN; - } - get hour() { - return this.isValid ? this.c.hour : NaN; - } - get minute() { - return this.isValid ? this.c.minute : NaN; - } - get second() { - return this.isValid ? this.c.second : NaN; - } - get millisecond() { - return this.isValid ? this.c.millisecond : NaN; - } - get weekYear() { - return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; - } - get weekNumber() { - return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; - } - get weekday() { - return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; - } - get isWeekend() { - return this.isValid && this.loc.getWeekendDays().includes(this.weekday); - } - get localWeekday() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; - } - get localWeekNumber() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; - } - get localWeekYear() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; - } - get ordinal() { - return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; - } - get monthShort() { - return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null; - } - get monthLong() { - return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null; - } - get weekdayShort() { - return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null; - } - get weekdayLong() { - return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null; - } - get offset() { - return this.isValid ? +this.o : NaN; - } - get offsetNameShort() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "short", - locale: this.locale - }); - } else { - return null; - } - } - get offsetNameLong() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "long", - locale: this.locale - }); - } else { - return null; - } - } - get isOffsetFixed() { - return this.isValid ? this.zone.isUniversal : null; - } - get isInDST() { - if (this.isOffsetFixed) { - return false; - } else { - return this.offset > this.set({ month: 1, day: 1 }).offset || this.offset > this.set({ month: 5 }).offset; - } - } - getPossibleOffsets() { - if (!this.isValid || this.isOffsetFixed) { - return [this]; - } - const dayMs = 864e5; - const minuteMs = 6e4; - const localTS = objToLocalTS(this.c); - const oEarlier = this.zone.offset(localTS - dayMs); - const oLater = this.zone.offset(localTS + dayMs); - const o1 = this.zone.offset(localTS - oEarlier * minuteMs); - const o2 = this.zone.offset(localTS - oLater * minuteMs); - if (o1 === o2) { - return [this]; - } - const ts1 = localTS - o1 * minuteMs; - const ts2 = localTS - o2 * minuteMs; - const c1 = tsToObj(ts1, o1); - const c2 = tsToObj(ts2, o2); - if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { - return [clone2(this, { ts: ts1 }), clone2(this, { ts: ts2 })]; - } - return [this]; - } - get isInLeapYear() { - return isLeapYear(this.year); - } - get daysInMonth() { - return daysInMonth(this.year, this.month); - } - get daysInYear() { - return this.isValid ? daysInYear(this.year) : NaN; - } - get weeksInWeekYear() { - return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; - } - get weeksInLocalWeekYear() { - return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN; - } - resolvedLocaleOptions(opts = {}) { - const { locale, numberingSystem, calendar } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this); - return { locale, numberingSystem, outputCalendar: calendar }; - } - toUTC(offset3 = 0, opts = {}) { - return this.setZone(FixedOffsetZone.instance(offset3), opts); - } - toLocal() { - return this.setZone(Settings.defaultZone); - } - setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) { - zone = normalizeZone(zone, Settings.defaultZone); - if (zone.equals(this.zone)) { - return this; - } else if (!zone.isValid) { - return DateTime.invalid(unsupportedZone(zone)); - } else { - let newTS = this.ts; - if (keepLocalTime || keepCalendarTime) { - const offsetGuess = zone.offset(this.ts); - const asObj = this.toObject(); - [newTS] = objToTS(asObj, offsetGuess, zone); - } - return clone2(this, { ts: newTS, zone }); - } - } - reconfigure({ locale, numberingSystem, outputCalendar } = {}) { - const loc = this.loc.clone({ locale, numberingSystem, outputCalendar }); - return clone2(this, { loc }); - } - setLocale(locale) { - return this.reconfigure({ locale }); - } - set(values) { - if (!this.isValid) - return this; - const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); - const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc); - const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; - if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); - } - if (containsGregorMD && containsOrdinal) { - throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); - } - let mixed; - if (settingWeekStuff) { - mixed = weekToGregorian({ ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized }, minDaysInFirstWeek, startOfWeek); - } else if (!isUndefined(normalized.ordinal)) { - mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized }); - } else { - mixed = { ...this.toObject(), ...normalized }; - if (isUndefined(normalized.day)) { - mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); - } - } - const [ts, o] = objToTS(mixed, this.o, this.zone); - return clone2(this, { ts, o }); - } - plus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration); - return clone2(this, adjustTime(this, dur)); - } - minus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration).negate(); - return clone2(this, adjustTime(this, dur)); - } - startOf(unit, { useLocaleWeeks = false } = {}) { - if (!this.isValid) - return this; - const o = {}, normalizedUnit = Duration.normalizeUnit(unit); - switch (normalizedUnit) { - case "years": - o.month = 1; - case "quarters": - case "months": - o.day = 1; - case "weeks": - case "days": - o.hour = 0; - case "hours": - o.minute = 0; - case "minutes": - o.second = 0; - case "seconds": - o.millisecond = 0; - break; - case "milliseconds": - break; - } - if (normalizedUnit === "weeks") { - if (useLocaleWeeks) { - const startOfWeek = this.loc.getStartOfWeek(); - const { weekday } = this; - if (weekday < startOfWeek) { - o.weekNumber = this.weekNumber - 1; - } - o.weekday = startOfWeek; - } else { - o.weekday = 1; - } - } - if (normalizedUnit === "quarters") { - const q = Math.ceil(this.month / 3); - o.month = (q - 1) * 3 + 1; - } - return this.set(o); - } - endOf(unit, opts) { - return this.isValid ? this.plus({ [unit]: 1 }).startOf(unit, opts).minus(1) : this; - } - toFormat(fmt, opts = {}) { - return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID3; - } - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID3; - } - toLocaleParts(opts = {}) { - return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; - } - toISO({ - format = "extended", - suppressSeconds = false, - suppressMilliseconds = false, - includeOffset = true, - extendedZone = false - } = {}) { - if (!this.isValid) { - return null; - } - const ext = format === "extended"; - let c = toISODate(this, ext); - c += "T"; - c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); - return c; - } - toISODate({ format = "extended" } = {}) { - if (!this.isValid) { - return null; - } - return toISODate(this, format === "extended"); - } - toISOWeekDate() { - return toTechFormat(this, "kkkk-'W'WW-c"); - } - toISOTime({ - suppressMilliseconds = false, - suppressSeconds = false, - includeOffset = true, - includePrefix = false, - extendedZone = false, - format = "extended" - } = {}) { - if (!this.isValid) { - return null; - } - let c = includePrefix ? "T" : ""; - return c + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone); - } - toRFC2822() { - return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); - } - toHTTP() { - return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); - } - toSQLDate() { - if (!this.isValid) { - return null; - } - return toISODate(this, true); - } - toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) { - let fmt = "HH:mm:ss.SSS"; - if (includeZone || includeOffset) { - if (includeOffsetSpace) { - fmt += " "; - } - if (includeZone) { - fmt += "z"; - } else if (includeOffset) { - fmt += "ZZ"; - } - } - return toTechFormat(this, fmt, true); - } - toSQL(opts = {}) { - if (!this.isValid) { - return null; - } - return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; - } - toString() { - return this.isValid ? this.toISO() : INVALID3; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; - } else { - return `DateTime { Invalid, reason: ${this.invalidReason} }`; - } - } - valueOf() { - return this.toMillis(); - } - toMillis() { - return this.isValid ? this.ts : NaN; - } - toSeconds() { - return this.isValid ? this.ts / 1e3 : NaN; - } - toUnixInteger() { - return this.isValid ? Math.floor(this.ts / 1e3) : NaN; - } - toJSON() { - return this.toISO(); - } - toBSON() { - return this.toJSDate(); - } - toObject(opts = {}) { - if (!this.isValid) - return {}; - const base = { ...this.c }; - if (opts.includeConfig) { - base.outputCalendar = this.outputCalendar; - base.numberingSystem = this.loc.numberingSystem; - base.locale = this.loc.locale; - } - return base; - } - toJSDate() { - return new Date(this.isValid ? this.ts : NaN); - } - diff(otherDateTime, unit = "milliseconds", opts = {}) { - if (!this.isValid || !otherDateTime.isValid) { - return Duration.invalid("created by diffing an invalid DateTime"); - } - const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts }; - const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff_default(earlier, later, units, durOpts); - return otherIsLater ? diffed.negate() : diffed; - } - diffNow(unit = "milliseconds", opts = {}) { - return this.diff(DateTime.now(), unit, opts); - } - until(otherDateTime) { - return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; - } - hasSame(otherDateTime, unit, opts) { - if (!this.isValid) - return false; - const inputMs = otherDateTime.valueOf(); - const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true }); - return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); - } - equals(other) { - return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); - } - toRelative(options = {}) { - if (!this.isValid) - return null; - const base = options.base || DateTime.fromObject({}, { zone: this.zone }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; - let units = ["years", "months", "days", "hours", "minutes", "seconds"]; - let unit = options.unit; - if (Array.isArray(options.unit)) { - units = options.unit; - unit = void 0; - } - return diffRelative(base, this.plus(padding), { - ...options, - numeric: "always", - units, - unit - }); - } - toRelativeCalendar(options = {}) { - if (!this.isValid) - return null; - return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, { - ...options, - numeric: "auto", - units: ["years", "months", "days"], - calendary: true - }); - } - static min(...dateTimes) { - if (!dateTimes.every(DateTime.isDateTime)) { - throw new InvalidArgumentError("min requires all arguments be DateTimes"); - } - return bestBy(dateTimes, (i) => i.valueOf(), Math.min); - } - static max(...dateTimes) { - if (!dateTimes.every(DateTime.isDateTime)) { - throw new InvalidArgumentError("max requires all arguments be DateTimes"); - } - return bestBy(dateTimes, (i) => i.valueOf(), Math.max); - } - static fromFormatExplain(text, fmt, options = {}) { - const { locale = null, numberingSystem = null } = options, localeToUse = Locale.fromOpts({ - locale, - numberingSystem, - defaultToEN: true - }); - return explainFromTokens(localeToUse, text, fmt); - } - static fromStringExplain(text, fmt, options = {}) { - return DateTime.fromFormatExplain(text, fmt, options); - } - static get DATE_SHORT() { - return DATE_SHORT; - } - static get DATE_MED() { - return DATE_MED; - } - static get DATE_MED_WITH_WEEKDAY() { - return DATE_MED_WITH_WEEKDAY; - } - static get DATE_FULL() { - return DATE_FULL; - } - static get DATE_HUGE() { - return DATE_HUGE; - } - static get TIME_SIMPLE() { - return TIME_SIMPLE; - } - static get TIME_WITH_SECONDS() { - return TIME_WITH_SECONDS; - } - static get TIME_WITH_SHORT_OFFSET() { - return TIME_WITH_SHORT_OFFSET; - } - static get TIME_WITH_LONG_OFFSET() { - return TIME_WITH_LONG_OFFSET; - } - static get TIME_24_SIMPLE() { - return TIME_24_SIMPLE; - } - static get TIME_24_WITH_SECONDS() { - return TIME_24_WITH_SECONDS; - } - static get TIME_24_WITH_SHORT_OFFSET() { - return TIME_24_WITH_SHORT_OFFSET; - } - static get TIME_24_WITH_LONG_OFFSET() { - return TIME_24_WITH_LONG_OFFSET; - } - static get DATETIME_SHORT() { - return DATETIME_SHORT; - } - static get DATETIME_SHORT_WITH_SECONDS() { - return DATETIME_SHORT_WITH_SECONDS; - } - static get DATETIME_MED() { - return DATETIME_MED; - } - static get DATETIME_MED_WITH_SECONDS() { - return DATETIME_MED_WITH_SECONDS; - } - static get DATETIME_MED_WITH_WEEKDAY() { - return DATETIME_MED_WITH_WEEKDAY; - } - static get DATETIME_FULL() { - return DATETIME_FULL; - } - static get DATETIME_FULL_WITH_SECONDS() { - return DATETIME_FULL_WITH_SECONDS; - } - static get DATETIME_HUGE() { - return DATETIME_HUGE; - } - static get DATETIME_HUGE_WITH_SECONDS() { - return DATETIME_HUGE_WITH_SECONDS; - } -}; -function friendlyDateTime(dateTimeish) { - if (DateTime.isDateTime(dateTimeish)) { - return dateTimeish; - } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { - return DateTime.fromJSDate(dateTimeish); - } else if (dateTimeish && typeof dateTimeish === "object") { - return DateTime.fromObject(dateTimeish); - } else { - throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`); - } -} - -// src/main.ts -var import_obsidian7 = require("obsidian"); - -// src/api.ts -var import_api = __toESM(require_src()); -var import_obsidian = require("obsidian"); -var baseUrl = (endpoint) => endpoint.replace(/\/api\/graphql$/, ""); -var getContent = async (endpoint, apiKey, libraryItemIds) => { - const response = await (0, import_obsidian.requestUrl)({ - url: `${baseUrl(endpoint)}/api/content`, - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: apiKey - }, - body: JSON.stringify({ libraryItemIds, format: "highlightedMarkdown" }) - }); - return response.json; -}; -var downloadFromUrl = async (url) => { - try { - const response = await (0, import_obsidian.requestUrl)({ - url - }); - return response.text; - } catch (error) { - if (error.status === 404) { - await sleep(1e3); - return downloadFromUrl(url); - } - throw error; - } -}; -var fetchContentForItems = async (endpoint, apiKey, items) => { - const content = await getContent(endpoint, apiKey, items.map((a) => a.id)); - await Promise.allSettled(content.data.map(async (c) => { - if (c.error) { - console.error("Error fetching content", c.error); - return; - } - const item = items.find((i) => i.id === c.libraryItemId); - if (!item) { - console.error("Item not found", c.libraryItemId); - return; - } - item.content = await Promise.race([ - downloadFromUrl(c.downloadUrl), - new Promise((_, reject) => setTimeout(() => reject("Timeout"), 6e5)) - ]); - })); -}; -var getItems = async (endpoint, apiKey, after = 0, first = 10, updatedAt = "", query = "", includeContent = false, format = "html") => { - const omnivore = new import_api.Omnivore({ - authToken: apiKey, - baseUrl: baseUrl(endpoint), - timeoutMs: 1e4 - }); - const response = await omnivore.items.search({ - after, - first, - query: `${updatedAt ? "updated:" + updatedAt : ""} sort:saved-asc ${query}`, - includeContent: false, - format - }); - const items = response.edges.map((e) => e.node); - if (includeContent && items.length > 0) { - try { - await fetchContentForItems(endpoint, apiKey, items); - } catch (error) { - console.error("Error fetching content", error); - } - } - return [items, response.pageInfo.hasNextPage]; -}; -var deleteItem = async (endpoint, apiKey, articleId) => { - const omnivore = new import_api.Omnivore({ - authToken: apiKey, - baseUrl: baseUrl(endpoint), - timeoutMs: 1e4 - }); - await omnivore.items.delete({ id: articleId }); - return true; -}; - -// src/settings/template.ts -var import_lodash = __toESM(require_lodash()); - -// node_modules/mustache/mustache.mjs -var objectToString = Object.prototype.toString; -var isArray = Array.isArray || function isArrayPolyfill(object) { - return objectToString.call(object) === "[object Array]"; -}; -function isFunction(object) { - return typeof object === "function"; -} -function typeStr(obj) { - return isArray(obj) ? "array" : typeof obj; -} -function escapeRegExp(string) { - return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); -} -function hasProperty(obj, propName) { - return obj != null && typeof obj === "object" && propName in obj; -} -function primitiveHasOwnProperty(primitive, propName) { - return primitive != null && typeof primitive !== "object" && primitive.hasOwnProperty && primitive.hasOwnProperty(propName); -} -var regExpTest = RegExp.prototype.test; -function testRegExp(re, string) { - return regExpTest.call(re, string); -} -var nonSpaceRe = /\S/; -function isWhitespace(string) { - return !testRegExp(nonSpaceRe, string); -} -var entityMap = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'", - "/": "/", - "`": "`", - "=": "=" -}; -function escapeHtml(string) { - return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s2) { - return entityMap[s2]; - }); -} -var whiteRe = /\s*/; -var spaceRe = /\s+/; -var equalsRe = /\s*=/; -var curlyRe = /\s*\}/; -var tagRe = /#|\^|\/|>|\{|&|=|!/; -function parseTemplate(template, tags) { - if (!template) - return []; - var lineHasNonSpace = false; - var sections = []; - var tokens = []; - var spaces = []; - var hasTag = false; - var nonSpace = false; - var indentation = ""; - var tagIndex = 0; - function stripSpace() { - if (hasTag && !nonSpace) { - while (spaces.length) - delete tokens[spaces.pop()]; - } else { - spaces = []; - } - hasTag = false; - nonSpace = false; - } - var openingTagRe, closingTagRe, closingCurlyRe; - function compileTags(tagsToCompile) { - if (typeof tagsToCompile === "string") - tagsToCompile = tagsToCompile.split(spaceRe, 2); - if (!isArray(tagsToCompile) || tagsToCompile.length !== 2) - throw new Error("Invalid tags: " + tagsToCompile); - openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + "\\s*"); - closingTagRe = new RegExp("\\s*" + escapeRegExp(tagsToCompile[1])); - closingCurlyRe = new RegExp("\\s*" + escapeRegExp("}" + tagsToCompile[1])); - } - compileTags(tags || mustache.tags); - var scanner = new Scanner(template); - var start2, type, value, chr, token, openSection; - while (!scanner.eos()) { - start2 = scanner.pos; - value = scanner.scanUntil(openingTagRe); - if (value) { - for (var i = 0, valueLength = value.length; i < valueLength; ++i) { - chr = value.charAt(i); - if (isWhitespace(chr)) { - spaces.push(tokens.length); - indentation += chr; - } else { - nonSpace = true; - lineHasNonSpace = true; - indentation += " "; - } - tokens.push(["text", chr, start2, start2 + 1]); - start2 += 1; - if (chr === "\n") { - stripSpace(); - indentation = ""; - tagIndex = 0; - lineHasNonSpace = false; - } - } - } - if (!scanner.scan(openingTagRe)) - break; - hasTag = true; - type = scanner.scan(tagRe) || "name"; - scanner.scan(whiteRe); - if (type === "=") { - value = scanner.scanUntil(equalsRe); - scanner.scan(equalsRe); - scanner.scanUntil(closingTagRe); - } else if (type === "{") { - value = scanner.scanUntil(closingCurlyRe); - scanner.scan(curlyRe); - scanner.scanUntil(closingTagRe); - type = "&"; - } else { - value = scanner.scanUntil(closingTagRe); - } - if (!scanner.scan(closingTagRe)) - throw new Error("Unclosed tag at " + scanner.pos); - if (type == ">") { - token = [type, value, start2, scanner.pos, indentation, tagIndex, lineHasNonSpace]; - } else { - token = [type, value, start2, scanner.pos]; - } - tagIndex++; - tokens.push(token); - if (type === "#" || type === "^") { - sections.push(token); - } else if (type === "/") { - openSection = sections.pop(); - if (!openSection) - throw new Error('Unopened section "' + value + '" at ' + start2); - if (openSection[1] !== value) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + start2); - } else if (type === "name" || type === "{" || type === "&") { - nonSpace = true; - } else if (type === "=") { - compileTags(value); - } - } - stripSpace(); - openSection = sections.pop(); - if (openSection) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); - return nestTokens(squashTokens(tokens)); -} -function squashTokens(tokens) { - var squashedTokens = []; - var token, lastToken; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - if (token) { - if (token[0] === "text" && lastToken && lastToken[0] === "text") { - lastToken[1] += token[1]; - lastToken[3] = token[3]; - } else { - squashedTokens.push(token); - lastToken = token; - } - } - } - return squashedTokens; -} -function nestTokens(tokens) { - var nestedTokens = []; - var collector = nestedTokens; - var sections = []; - var token, section; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - switch (token[0]) { - case "#": - case "^": - collector.push(token); - sections.push(token); - collector = token[4] = []; - break; - case "/": - section = sections.pop(); - section[5] = token[2]; - collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; - break; - default: - collector.push(token); - } - } - return nestedTokens; -} -function Scanner(string) { - this.string = string; - this.tail = string; - this.pos = 0; -} -Scanner.prototype.eos = function eos() { - return this.tail === ""; -}; -Scanner.prototype.scan = function scan(re) { - var match3 = this.tail.match(re); - if (!match3 || match3.index !== 0) - return ""; - var string = match3[0]; - this.tail = this.tail.substring(string.length); - this.pos += string.length; - return string; -}; -Scanner.prototype.scanUntil = function scanUntil(re) { - var index = this.tail.search(re), match3; - switch (index) { - case -1: - match3 = this.tail; - this.tail = ""; - break; - case 0: - match3 = ""; - break; - default: - match3 = this.tail.substring(0, index); - this.tail = this.tail.substring(index); - } - this.pos += match3.length; - return match3; -}; -function Context(view, parentContext) { - this.view = view; - this.cache = { ".": this.view }; - this.parent = parentContext; -} -Context.prototype.push = function push(view) { - return new Context(view, this); -}; -Context.prototype.lookup = function lookup(name) { - var cache = this.cache; - var value; - if (cache.hasOwnProperty(name)) { - value = cache[name]; - } else { - var context = this, intermediateValue, names, index, lookupHit = false; - while (context) { - if (name.indexOf(".") > 0) { - intermediateValue = context.view; - names = name.split("."); - index = 0; - while (intermediateValue != null && index < names.length) { - if (index === names.length - 1) - lookupHit = hasProperty(intermediateValue, names[index]) || primitiveHasOwnProperty(intermediateValue, names[index]); - intermediateValue = intermediateValue[names[index++]]; - } - } else { - intermediateValue = context.view[name]; - lookupHit = hasProperty(context.view, name); - } - if (lookupHit) { - value = intermediateValue; - break; - } - context = context.parent; - } - cache[name] = value; - } - if (isFunction(value)) - value = value.call(this.view); - return value; -}; -function Writer() { - this.templateCache = { - _cache: {}, - set: function set(key, value) { - this._cache[key] = value; - }, - get: function get(key) { - return this._cache[key]; - }, - clear: function clear() { - this._cache = {}; - } - }; -} -Writer.prototype.clearCache = function clearCache() { - if (typeof this.templateCache !== "undefined") { - this.templateCache.clear(); - } -}; -Writer.prototype.parse = function parse2(template, tags) { - var cache = this.templateCache; - var cacheKey = template + ":" + (tags || mustache.tags).join(":"); - var isCacheEnabled = typeof cache !== "undefined"; - var tokens = isCacheEnabled ? cache.get(cacheKey) : void 0; - if (tokens == void 0) { - tokens = parseTemplate(template, tags); - isCacheEnabled && cache.set(cacheKey, tokens); - } - return tokens; -}; -Writer.prototype.render = function render(template, view, partials, config) { - var tags = this.getConfigTags(config); - var tokens = this.parse(template, tags); - var context = view instanceof Context ? view : new Context(view, void 0); - return this.renderTokens(tokens, context, partials, template, config); -}; -Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate, config) { - var buffer = ""; - var token, symbol, value; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - value = void 0; - token = tokens[i]; - symbol = token[0]; - if (symbol === "#") - value = this.renderSection(token, context, partials, originalTemplate, config); - else if (symbol === "^") - value = this.renderInverted(token, context, partials, originalTemplate, config); - else if (symbol === ">") - value = this.renderPartial(token, context, partials, config); - else if (symbol === "&") - value = this.unescapedValue(token, context); - else if (symbol === "name") - value = this.escapedValue(token, context, config); - else if (symbol === "text") - value = this.rawValue(token); - if (value !== void 0) - buffer += value; - } - return buffer; -}; -Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate, config) { - var self2 = this; - var buffer = ""; - var value = context.lookup(token[1]); - function subRender(template) { - return self2.render(template, context, partials, config); - } - if (!value) - return; - if (isArray(value)) { - for (var j = 0, valueLength = value.length; j < valueLength; ++j) { - buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); - } - } else if (typeof value === "object" || typeof value === "string" || typeof value === "number") { - buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); - } else if (isFunction(value)) { - if (typeof originalTemplate !== "string") - throw new Error("Cannot use higher-order sections without the original template"); - value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); - if (value != null) - buffer += value; - } else { - buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); - } - return buffer; -}; -Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate, config) { - var value = context.lookup(token[1]); - if (!value || isArray(value) && value.length === 0) - return this.renderTokens(token[4], context, partials, originalTemplate, config); -}; -Writer.prototype.indentPartial = function indentPartial(partial, indentation, lineHasNonSpace) { - var filteredIndentation = indentation.replace(/[^ \t]/g, ""); - var partialByNl = partial.split("\n"); - for (var i = 0; i < partialByNl.length; i++) { - if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { - partialByNl[i] = filteredIndentation + partialByNl[i]; - } - } - return partialByNl.join("\n"); -}; -Writer.prototype.renderPartial = function renderPartial(token, context, partials, config) { - if (!partials) - return; - var tags = this.getConfigTags(config); - var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; - if (value != null) { - var lineHasNonSpace = token[6]; - var tagIndex = token[5]; - var indentation = token[4]; - var indentedValue = value; - if (tagIndex == 0 && indentation) { - indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); - } - var tokens = this.parse(indentedValue, tags); - return this.renderTokens(tokens, context, partials, indentedValue, config); - } -}; -Writer.prototype.unescapedValue = function unescapedValue(token, context) { - var value = context.lookup(token[1]); - if (value != null) - return value; -}; -Writer.prototype.escapedValue = function escapedValue(token, context, config) { - var escape2 = this.getConfigEscape(config) || mustache.escape; - var value = context.lookup(token[1]); - if (value != null) - return typeof value === "number" && escape2 === mustache.escape ? String(value) : escape2(value); -}; -Writer.prototype.rawValue = function rawValue(token) { - return token[1]; -}; -Writer.prototype.getConfigTags = function getConfigTags(config) { - if (isArray(config)) { - return config; - } else if (config && typeof config === "object") { - return config.tags; - } else { - return void 0; - } -}; -Writer.prototype.getConfigEscape = function getConfigEscape(config) { - if (config && typeof config === "object" && !isArray(config)) { - return config.escape; - } else { - return void 0; - } -}; -var mustache = { - name: "mustache.js", - version: "4.2.0", - tags: ["{{", "}}"], - clearCache: void 0, - escape: void 0, - parse: void 0, - render: void 0, - Scanner: void 0, - Context: void 0, - Writer: void 0, - set templateCache(cache) { - defaultWriter.templateCache = cache; - }, - get templateCache() { - return defaultWriter.templateCache; - } -}; -var defaultWriter = new Writer(); -mustache.clearCache = function clearCache2() { - return defaultWriter.clearCache(); -}; -mustache.parse = function parse3(template, tags) { - return defaultWriter.parse(template, tags); -}; -mustache.render = function render2(template, view, partials, config) { - if (typeof template !== "string") { - throw new TypeError('Invalid template! Template should be a "string" but "' + typeStr(template) + '" was given as the first argument for mustache#render(template, view, partials)'); - } - return defaultWriter.render(template, view, partials, config); -}; -mustache.escape = escapeHtml; -mustache.Scanner = Scanner; -mustache.Context = Context; -mustache.Writer = Writer; -var mustache_default = mustache; - -// src/settings/template.ts -var import_obsidian3 = require("obsidian"); - -// src/util.ts -var import_diff_match_patch = __toESM(require_diff_match_patch()); -var import_markdown_escape = __toESM(require_markdown_escape()); -var import_obsidian2 = require("obsidian"); - -// node_modules/out-of-character/builds/out-of-character.mjs -var require$$0 = [ - { - type: "Line Break", - name: "LINE FEED", - code: "U+000A", - escapeChar: "\\n", - aka: "LF", - actualUnicodeChar: "\n", - codeEscaped: "\\u000A", - url: "https://www.compart.com/en/unicode/U+000A" - }, - { - type: "Separator", - name: "LINE TABULATION", - code: "U+000B", - escapeChar: "\\t", - aka: "TAB", - replaceWith: " ", - actualUnicodeChar: "\v", - codeEscaped: "\\u000B", - url: "https://www.compart.com/en/unicode/U+000B" - }, - { - type: "Separator", - name: "FORM FEED", - code: "U+000C", - escapeChar: "\\f", - aka: "FF", - replaceWith: "", - actualUnicodeChar: "\f", - codeEscaped: "\\u000C", - url: "https://www.compart.com/en/unicode/U+000C" - }, - { - type: "Line Break", - name: "CARRIAGE RETURN", - code: "U+000D", - escapeChar: "\\r", - aka: "CR", - actualUnicodeChar: "\r", - codeEscaped: "\\u000D", - url: "https://www.compart.com/en/unicode/U+000D" - }, - { - type: "Separators", - name: "NEXT LINE", - code: "U+0085", - escapeChar: "", - aka: "NEL", - replaceWith: "", - actualUnicodeChar: "\x85", - codeEscaped: "\\u0085", - url: "https://www.compart.com/en/unicode/U+0085" - }, - { - type: "Whitespace", - name: "NO-BREAK SPACE", - code: "U+00A0", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\xA0", - codeEscaped: "\\u00A0", - url: "https://www.compart.com/en/unicode/U+00A0" - }, - { - type: "Separators", - name: "LINE SEPARATOR", - code: "U+2028", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2028", - codeEscaped: "\\u2028", - url: "https://www.compart.com/en/unicode/U+2028" - }, - { - type: "Separators", - name: "PARAGRAPH SEPARATOR", - code: "U+2029", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2029", - codeEscaped: "\\u2029", - url: "https://www.compart.com/en/unicode/U+2029" - }, - { - type: "Whitespace", - name: "CHARACTER TABULATION", - code: "U+0009", - escapeChar: "", - actualUnicodeChar: " ", - codeEscaped: "\\u0009", - url: "https://www.compart.com/en/unicode/U+0009" - }, - { - type: "Whitespace", - name: "SPACE", - code: "U+0020", - escapeChar: "", - actualUnicodeChar: " ", - codeEscaped: "\\u0020", - url: "https://www.compart.com/en/unicode/U+0020" - }, - { - htmlentity: "­", - htmlcode: "­", - csscode: "\\00AD", - unicode: "U+00AD", - name: "SOFT HYPHEN", - type: "Invisible", - code: "U+00AD", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\xAD", - codeEscaped: "\\u00AD", - url: "https://www.compart.com/en/unicode/U+00AD" - }, - { - type: "Invisible", - name: "COMBINING GRAPHEME JOINER", - code: "U+034F", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u034F", - codeEscaped: "\\u034F", - url: "https://www.compart.com/en/unicode/U+034F" - }, - { - type: "Invisible", - name: "ARABIC LETTER MARK", - code: "U+061C", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u061C", - codeEscaped: "\\u061C", - url: "https://www.compart.com/en/unicode/U+061C" - }, - { - type: "Visible", - name: "SYRIAC ABBREVIATION MARK", - code: "U+070F", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u070F", - codeEscaped: "\\u070F", - url: "https://www.compart.com/en/unicode/U+070F" - }, - { - type: "Whitespace", - name: "HANGUL CHOSEONG FILLER", - code: "U+115F", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u115F", - codeEscaped: "\\u115F", - url: "https://www.compart.com/en/unicode/U+115F" - }, - { - type: "Whitespace", - name: "HANGUL JUNGSEONG FILLER", - code: "U+1160", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u1160", - codeEscaped: "\\u1160", - url: "https://www.compart.com/en/unicode/U+1160" - }, - { - type: "Visible", - name: "OGHAM SPACE MARK", - code: "U+1680", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u1680", - codeEscaped: "\\u1680", - url: "https://www.compart.com/en/unicode/U+1680" - }, - { - type: "Invisible", - name: "KHMER VOWEL INHERENT AQ", - code: "U+17B4", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u17B4", - codeEscaped: "\\u17B4", - url: "https://www.compart.com/en/unicode/U+17B4" - }, - { - type: "Invisible", - name: "KHMER VOWEL INHERENT AA", - code: "U+17B5", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u17B5", - codeEscaped: "\\u17B5", - url: "https://www.compart.com/en/unicode/U+17B5" - }, - { - type: "Invisible", - name: "MONGOLIAN VOWEL SEPARATOR", - code: "U+180E", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u180E", - codeEscaped: "\\u180E", - url: "https://www.compart.com/en/unicode/U+180E" - }, - { - type: "Whitespace", - name: "EN QUAD", - code: "U+2000", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2000", - codeEscaped: "\\u2000", - url: "https://www.compart.com/en/unicode/U+2000" - }, - { - type: "Whitespace", - name: "EM QUAD", - code: "U+2001", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2001", - codeEscaped: "\\u2001", - url: "https://www.compart.com/en/unicode/U+2001" - }, - { - htmlentity: " ", - htmlcode: " ", - csscode: "\\2002", - unicode: "U+2002", - name: "EN SPACE", - type: "Whitespace", - code: "U+2002", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2002", - codeEscaped: "\\u2002", - url: "https://www.compart.com/en/unicode/U+2002" - }, - { - htmlentity: " ", - htmlcode: " ", - csscode: "\\2003", - unicode: "U+2003", - name: "EM SPACE", - type: "Whitespace", - code: "U+2003", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2003", - codeEscaped: "\\u2003", - url: "https://www.compart.com/en/unicode/U+2003" - }, - { - type: "Whitespace", - name: "THREE-PER-EM SPACE", - code: "U+2004", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2004", - codeEscaped: "\\u2004", - url: "https://www.compart.com/en/unicode/U+2004" - }, - { - type: "Whitespace", - name: "FOUR-PER-EM SPACE", - code: "U+2005", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2005", - codeEscaped: "\\u2005", - url: "https://www.compart.com/en/unicode/U+2005" - }, - { - type: "Whitespace", - name: "SIX-PER-EM SPACE", - code: "U+2006", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2006", - codeEscaped: "\\u2006", - url: "https://www.compart.com/en/unicode/U+2006" - }, - { - type: "Whitespace", - name: "FIGURE SPACE", - code: "U+2007", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2007", - codeEscaped: "\\u2007", - url: "https://www.compart.com/en/unicode/U+2007" - }, - { - type: "Whitespace", - name: "PUNCTUATION SPACE", - code: "U+2008", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2008", - codeEscaped: "\\u2008", - url: "https://www.compart.com/en/unicode/U+2008" - }, - { - htmlentity: " ", - htmlcode: " ", - csscode: "\\2009", - unicode: "U+2009", - name: "THIN SPACE", - type: "Whitespace", - code: "U+2009", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2009", - codeEscaped: "\\u2009", - url: "https://www.compart.com/en/unicode/U+2009" - }, - { - type: "Whitespace", - name: "HAIR SPACE", - code: "U+200A", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u200A", - codeEscaped: "\\u200A", - url: "https://www.compart.com/en/unicode/U+200A" - }, - { - type: "Invisible", - name: "ZERO WIDTH SPACE", - code: "U+200B", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u200B", - codeEscaped: "\\u200B", - url: "https://www.compart.com/en/unicode/U+200B" - }, - { - htmlentity: "‌", - htmlcode: "‌", - csscode: "\\200C", - unicode: "U+200C", - name: "ZERO WIDTH NON-JOINER", - type: "Invisible", - code: "U+200C", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u200C", - codeEscaped: "\\u200C", - url: "https://www.compart.com/en/unicode/U+200C" - }, - { - htmlentity: "‍", - htmlcode: "‍", - csscode: "\\200D", - unicode: "U+200D", - name: "ZERO WIDTH", - type: "Invisible", - code: "U+200D", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u200D", - codeEscaped: "\\u200D", - url: "https://www.compart.com/en/unicode/U+200D" - }, - { - htmlentity: "‎", - htmlcode: "‎", - csscode: "\\200E", - unicode: "U+200E", - name: "LEFT-TO-RIGHT MARK", - type: "Invisible", - code: "U+200E", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u200E", - codeEscaped: "\\u200E", - url: "https://www.compart.com/en/unicode/U+200E" - }, - { - htmlentity: "‏", - htmlcode: "‏", - csscode: "\\200F", - unicode: "U+200F", - name: "RIGHT-TO-LEFT MARK", - type: "Invisible", - code: "U+200F", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u200F", - codeEscaped: "\\u200F", - url: "https://www.compart.com/en/unicode/U+200F" - }, - { - type: "Whitespace", - name: "NARROW NO-BREAK SPACE", - code: "U+202F", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u202F", - codeEscaped: "\\u202F", - url: "https://www.compart.com/en/unicode/U+202F" - }, - { - type: "Whitespace", - name: "MEDIUM MATHEMATICAL SPACE", - code: "U+205F", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u205F", - codeEscaped: "\\u205F", - url: "https://www.compart.com/en/unicode/U+205F" - }, - { - type: "Invisible", - name: "WORD JOINER", - code: "U+2060", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2060", - codeEscaped: "\\u2060", - url: "https://www.compart.com/en/unicode/U+2060" - }, - { - type: "Invisible", - name: "FUNCTION APPLICATION", - code: "U+2061", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2061", - codeEscaped: "\\u2061", - url: "https://www.compart.com/en/unicode/U+2061" - }, - { - type: "Invisible", - name: "INVISIBLE TIMES", - code: "U+2062", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2062", - codeEscaped: "\\u2062", - url: "https://www.compart.com/en/unicode/U+2062" - }, - { - type: "Invisible", - name: "INVISIBLE SEPARATOR", - code: "U+2063", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2063", - codeEscaped: "\\u2063", - url: "https://www.compart.com/en/unicode/U+2063" - }, - { - type: "Invisible", - name: "INVISIBLE PLUS", - code: "U+2064", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u2064", - codeEscaped: "\\u2064", - url: "https://www.compart.com/en/unicode/U+2064" - }, - { - type: "Invisible", - name: "INHIBIT SYMMETRIC SWAPPING", - code: "U+206A", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206A", - codeEscaped: "\\u206A", - url: "https://www.compart.com/en/unicode/U+206A" - }, - { - type: "Invisible", - name: "ACTIVATE SYMMETRIC SWAPPING", - code: "U+206B", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206B", - codeEscaped: "\\u206B", - url: "https://www.compart.com/en/unicode/U+206B" - }, - { - type: "Invisible", - name: "INHIBIT ARABIC FORM SHAPING", - code: "U+206C", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206C", - codeEscaped: "\\u206C", - url: "https://www.compart.com/en/unicode/U+206C" - }, - { - type: "Invisible", - name: "ACTIVATE ARABIC FORM SHAPING", - code: "U+206D", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206D", - codeEscaped: "\\u206D", - url: "https://www.compart.com/en/unicode/U+206D" - }, - { - type: "Invisible", - name: "NATIONAL DIGIT SHAPES", - code: "U+206E", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206E", - codeEscaped: "\\u206E", - url: "https://www.compart.com/en/unicode/U+206E" - }, - { - type: "Invisible", - name: "NOMINAL DIGIT SHAPES", - code: "U+206F", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u206F", - codeEscaped: "\\u206F", - url: "https://www.compart.com/en/unicode/U+206F" - }, - { - type: "Whitespace", - name: "IDEOGRAPHIC SPACE", - code: "U+3000", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u3000", - codeEscaped: "\\u3000", - url: "https://www.compart.com/en/unicode/U+3000" - }, - { - type: "Whitespace", - name: "BRAILLE PATTERN BLANK", - code: "U+2800", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u2800", - codeEscaped: "\\u2800", - url: "https://www.compart.com/en/unicode/U+2800" - }, - { - type: "Whitespace", - name: "HANGUL FILLER", - code: "U+3164", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\u3164", - codeEscaped: "\\u3164", - url: "https://www.compart.com/en/unicode/U+3164" - }, - { - type: "Invisible", - name: "ZERO WIDTH NO-BREAK SPACE", - code: "U+FEFF", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\uFEFF", - codeEscaped: "\\uFEFF", - url: "https://www.compart.com/en/unicode/U+FEFF" - }, - { - type: "Whitespace", - name: "HALFWIDTH HANGUL FILLER", - code: "U+FFA0", - escapeChar: "", - replaceWith: " ", - actualUnicodeChar: "\uFFA0", - codeEscaped: "\\uFFA0", - url: "https://www.compart.com/en/unicode/U+FFA0" - }, - { - type: "Visible", - name: "KAITHI VOWEL SIGN I", - code: "U+110B1", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{110B1}", - codeEscaped: "\\u110B1", - url: "https://www.compart.com/en/unicode/U+110B1" - }, - { - type: "Visible", - name: "SHORTHAND FORMAT LETTER OVERLAP", - code: "U+1BCA0", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1BCA0}", - codeEscaped: "\\u1BCA0", - url: "https://www.compart.com/en/unicode/U+1BCA0" - }, - { - type: "Visible", - name: "SHORTHAND FORMAT CONTINUING OVERLAP", - code: "U+1BCA1", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1BCA1}", - codeEscaped: "\\u1BCA1", - url: "https://www.compart.com/en/unicode/U+1BCA1" - }, - { - type: "Visible", - name: "SHORTHAND FORMAT DOWN STEP", - code: "U+1BCA2", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1BCA2}", - codeEscaped: "\\u1BCA2", - url: "https://www.compart.com/en/unicode/U+1BCA2" - }, - { - type: "Visible", - name: "SHORTHAND FORMAT UP STEP", - code: "U+1BCA3", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1BCA3}", - codeEscaped: "\\u1BCA3", - url: "https://www.compart.com/en/unicode/U+1BCA3" - }, - { - type: "Visible", - name: "MUSICAL SYMBOL NULL NOTEHEAD", - code: "U+1D159", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D159}", - codeEscaped: "\\u1D159", - url: "https://www.compart.com/en/unicode/U+1D159" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL BEGIN BEAM", - code: "U+1D173", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D173}", - codeEscaped: "\\u1D173", - url: "https://www.compart.com/en/unicode/U+1D173" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL END BEAM", - code: "U+1D174", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D174}", - codeEscaped: "\\u1D174", - url: "https://www.compart.com/en/unicode/U+1D174" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL BEGIN TIE", - code: "U+1D175", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D175}", - codeEscaped: "\\u1D175", - url: "https://www.compart.com/en/unicode/U+1D175" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL END TIE", - code: "U+1D176", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D176}", - codeEscaped: "\\u1D176", - url: "https://www.compart.com/en/unicode/U+1D176" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL BEGIN SLUR", - code: "U+1D177", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D177}", - codeEscaped: "\\u1D177", - url: "https://www.compart.com/en/unicode/U+1D177" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL END SLUR", - code: "U+1D178", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D178}", - codeEscaped: "\\u1D178", - url: "https://www.compart.com/en/unicode/U+1D178" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL BEGIN PHRASE", - code: "U+1D179", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D179}", - codeEscaped: "\\u1D179", - url: "https://www.compart.com/en/unicode/U+1D179" - }, - { - type: "Invisible", - name: "MUSICAL SYMBOL END PHRASE", - code: "U+1D17A", - escapeChar: "", - replaceWith: "", - actualUnicodeChar: "\u{1D17A}", - codeEscaped: "\\u1D17A", - url: "https://www.compart.com/en/unicode/U+1D17A" - } -]; -var isVariationSelector = function isVariationSelector2(num) { - return num >= 65024 && num <= 65039; -}; -var isHighSurrogate = function isHighSurrogate2(num) { - return num >= 55296 && num <= 56319; -}; -var isLowSurrogate = function isLowSurrogate2(num) { - return num >= 56320 && num <= 57343; -}; -var isEmoji$1 = function isEmoji(text, i) { - if (text[i - 1]) { - var code = text.charCodeAt(i - 1); - if (isHighSurrogate(code) || isLowSurrogate(code) || isVariationSelector(code)) { - return true; - } - } - if (text[i + 1]) { - var _code = text.charCodeAt(i + 1); - if (isHighSurrogate(_code) || isLowSurrogate(_code) || isVariationSelector(_code)) { - return true; - } - } - return false; -}; -var isEmoji_1 = isEmoji$1; -var data = require$$0; -var isEmoji2 = isEmoji_1; -var padStr = function padStr2(str, width) { - while (str.length < width) { - str = "0" + str; - } - return str; -}; -var byCode = data.reduce(function(h, obj) { - h[obj.code] = obj; - return h; -}, {}); -var codes = data.filter(function(obj) { - return obj.replaceWith !== void 0; -}).map(function(obj) { - return obj.code.replace(/^U\+/, "\\u"); -}); -var findAll$1 = function findAll(text) { - var regEx = new RegExp("(".concat(codes.join("|"), ")"), "g"); - var matches = []; - text.replace(regEx, function(ch, _b, offset3) { - var code = ch.charCodeAt(0); - var hex = code.toString(16).toUpperCase(); - hex = "U+" + padStr(hex, 4); - var found = byCode[hex] || {}; - if (found.code === "U+200D") { - if (isEmoji2(text, offset3)) { - return ch; - } - } - matches.push({ - name: found.name, - code: found.code, - offset: offset3, - replacement: found.replaceWith || "" - }); - return ch; - }); - return matches; -}; -var match2 = findAll$1; -var findAll2 = match2; -var src = { - detect: function detect(text) { - var matches = findAll2(text); - if (matches.length > 0) { - return matches; - } - return null; - }, - replace: function replace(text) { - var matches = findAll2(text); - matches.forEach(function(o) { - var code = o.code.replace(/^U\+/, "\\u"); - var reg = new RegExp(code, "g"); - text = text.replace(reg, o.replacement || ""); - }); - return text; - } -}; -var out_of_character_default = src; - -// src/util.ts -var DATE_FORMAT_W_OUT_SECONDS = "yyyy-MM-dd'T'HH:mm"; -var DATE_FORMAT = `${DATE_FORMAT_W_OUT_SECONDS}:ss`; -var REPLACEMENT_CHAR = "-"; -var ILLEGAL_CHAR_REGEX_FILE = /[<>:"/\\|?*\u0000-\u001F]/g; -var ILLEGAL_CHAR_REGEX_FOLDER = /[<>:"\\|?*\u0000-\u001F]/g; -var getHighlightLocation = (patch) => { - if (!patch) { - return 0; - } - const dmp = new import_diff_match_patch.diff_match_patch(); - const patches = dmp.patch_fromText(patch); - return patches[0].start1 || 0; -}; -var getHighlightPoint = (patch) => { - if (!patch) { - return { left: 0, top: 0 }; - } - const { bbox } = JSON.parse(patch); - if (!bbox || bbox.length !== 4) { - return { left: 0, top: 0 }; - } - return { left: bbox[0], top: bbox[1] }; -}; -var compareHighlightsInFile = (a, b) => { - const highlightPointA = getHighlightPoint(a.patch); - const highlightPointB = getHighlightPoint(b.patch); - if (highlightPointA.top === highlightPointB.top) { - return highlightPointA.left - highlightPointB.left; - } - return highlightPointA.top - highlightPointB.top; -}; -var parseDateTime = (str) => { - const res = DateTime.fromFormat(str, DATE_FORMAT); - if (res.isValid) { - return res; - } - return DateTime.fromFormat(str, DATE_FORMAT_W_OUT_SECONDS); -}; -var wrapAround = (value, size) => { - return (value % size + size) % size; -}; -var replaceIllegalCharsFile = (str) => { - return removeInvisibleChars(str.replace(ILLEGAL_CHAR_REGEX_FILE, REPLACEMENT_CHAR)); -}; -var replaceIllegalCharsFolder = (str) => { - return removeInvisibleChars(str.replace(ILLEGAL_CHAR_REGEX_FOLDER, REPLACEMENT_CHAR)); -}; -function formatDate(date, format) { - if (isNaN(Date.parse(date))) { - throw new Error(`Invalid date: ${date}`); - } - return DateTime.fromJSDate(new Date(date)).toFormat(format); -} -var getQueryFromFilter = (filter) => { - switch (filter) { - case "ALL": - return "in:all"; - case "HIGHLIGHTS": - return `in:all has:highlights`; - case "ARCHIVED": - return `in:archive`; - case "LIBRARY": - return `in:library`; - default: - return "in:all"; - } -}; -var siteNameFromUrl = (originalArticleUrl) => { - try { - return new URL(originalArticleUrl).hostname.replace(/^www\./, ""); - } catch { - return ""; - } -}; -var wrapHighlightMarkup = (quote, highlightRenderOption) => { - const { highlightManagerId, highlightColor } = highlightRenderOption; - const markupRender = (content) => { - if (content.trim().length === 0) { - return ""; - } - if (highlightManagerId == "hltr" /* HIGHLIGHTR */) { - return `${content}`; - } else { - return `${content}`; - } - }; - return quote.replaceAll(/(>)?(.+)$/gm, (_, g1, g2) => { - return (g1 ?? "") + markupRender(g2); - }); -}; -var formatHighlightQuote = (quote, template, highlightRenderOption) => { - if (!quote) { - return ""; - } - const regex = /{{#highlights}}(\n)*>/gm; - if (regex.test(template)) { - quote = quote.replaceAll(">", ">").replaceAll(/\n/gm, "\n> "); - } - if (highlightRenderOption != null) { - quote = wrapHighlightMarkup(quote, highlightRenderOption); - } - return quote; -}; -var findFrontMatterIndex = (frontMatter, id) => { - return frontMatter.findIndex((fm) => fm.id == id); -}; -var parseFrontMatterFromContent = (content) => { - const frontMatter = content.match(/^---\n(.*?)\n---/s); - if (!frontMatter) { - return void 0; - } - return (0, import_obsidian2.parseYaml)(frontMatter[1]); -}; -var removeFrontMatterFromContent = (content) => { - const frontMatterRegex = /^---.*?---\n*/s; - return content.replace(frontMatterRegex, ""); -}; -var snakeToCamelCase = (str) => str.replace(/(_[a-z])/g, (group) => group.toUpperCase().replace("_", "")); -var removeInvisibleChars = (str) => { - return out_of_character_default.replace(str); -}; -var setOrUpdateHighlightColors = (colorSetting) => { - const root = document.documentElement; - Object.entries(colorSetting).forEach(([k, v]) => { - root.style.setProperty(`--omni-${k}`, v); - }); -}; - -// src/settings/template.ts -var DEFAULT_TEMPLATE = `# {{{title}}} -#Omnivore - -[Read on Omnivore]({{{omnivoreUrl}}}) -[Read Original]({{{originalUrl}}}) - -{{#highlights.length}} -## Highlights - -{{#highlights}} -> {{{text}}} [\u2934\uFE0F]({{{highlightUrl}}}) {{#labels}} #{{name}} {{/labels}} ^{{{highlightID}}} -{{#note}} - -{{{note}}} -{{/note}} - -{{/highlights}} -{{/highlights.length}}`; -var getItemState = (item) => { - if (item.isArchived) { - return "ARCHIVED" /* Archived */; - } - if (item.readingProgressPercent > 0) { - return item.readingProgressPercent === 100 ? "COMPLETED" /* Completed */ : "READING" /* Reading */; - } - return "INBOX" /* Inbox */; -}; -function lowerCase() { - return function(text, render4) { - return render4(text).toLowerCase(); - }; -} -function upperCase() { - return function(text, render4) { - return render4(text).toUpperCase(); - }; -} -function upperCaseFirst() { - return function(text, render4) { - const str = render4(text); - return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase(); - }; -} -function formatDateFunc() { - return function(text, render4) { - const [dateVariable, format] = text.split(",", 2); - const date = render4(dateVariable); - if (!date) { - return ""; - } - return formatDate(date, format); - }; -} -var functionMap = { - lowerCase, - upperCase, - upperCaseFirst, - formatDate: formatDateFunc -}; -var getOmnivoreUrl = (item) => { - return `https://omnivore.app/me/${item.slug}`; -}; -var renderFilename = (item, filename, dateFormat) => { - const renderedFilename = render3(item, filename, dateFormat); - return (0, import_lodash.truncate)(renderedFilename, { - length: 100 - }); -}; -var renderLabels = (labels) => { - return labels?.map((l2) => ({ - name: l2.name.replaceAll(" ", "_") - })); -}; -var renderItemContent = async (item, template, highlightOrder, highlightManagerId, dateHighlightedFormat, dateSavedFormat, isSingleFile, frontMatterVariables, frontMatterTemplate, fileAttachment) => { - const itemHighlights = item.highlights?.filter((h) => h.type === "HIGHLIGHT") || []; - if (highlightOrder === "LOCATION") { - itemHighlights.sort((a, b) => { - try { - if (item.pageType === "FILE") { - return compareHighlightsInFile(a, b); - } - return getHighlightLocation(a.patch) - getHighlightLocation(b.patch); - } catch (e) { - console.error(e); - return compareHighlightsInFile(a, b); - } - }); - } - const highlights = itemHighlights.map((highlight) => { - const highlightColor = highlight.color ?? "yellow"; - const highlightRenderOption = highlightManagerId ? { - highlightColor, - highlightManagerId - } : null; - return { - text: formatHighlightQuote(highlight.quote, template, highlightRenderOption), - highlightUrl: `https://omnivore.app/me/${item.slug}#${highlight.id}`, - highlightID: highlight.id.slice(0, 8), - dateHighlighted: highlight.updatedAt ? formatDate(highlight.updatedAt, dateHighlightedFormat) : void 0, - note: highlight.annotation ?? void 0, - labels: renderLabels(highlight.labels || void 0), - color: highlightColor, - positionPercent: highlight.highlightPositionPercent || 0, - positionAnchorIndex: highlight.highlightPositionAnchorIndex ? highlight.highlightPositionAnchorIndex + 1 : 0 - }; - }); - const dateSaved = formatDate(item.savedAt, dateSavedFormat); - const siteName = item.siteName || siteNameFromUrl(item.originalArticleUrl || item.url); - const publishedAt = item.publishedAt; - const datePublished = publishedAt ? formatDate(publishedAt, dateSavedFormat).trim() : void 0; - const articleNote = item.highlights?.find((h) => h.type === "NOTE"); - const dateRead = item.readAt ? formatDate(item.readAt, dateSavedFormat).trim() : void 0; - const wordsCount = item.wordsCount; - const readLength = wordsCount ? Math.round(Math.max(1, wordsCount / 235)) : void 0; - const articleView = { - id: item.id, - title: item.title, - omnivoreUrl: `https://omnivore.app/me/${item.slug}`, - siteName, - originalUrl: item.originalArticleUrl || item.url, - author: item.author || "unknown", - labels: renderLabels(item.labels || void 0), - dateSaved, - highlights, - content: item.contentReader === "WEB" ? item.content || void 0 : void 0, - datePublished, - fileAttachment, - description: item.description || void 0, - note: articleNote?.annotation ?? void 0, - type: item.pageType, - dateRead, - wordsCount: item.wordsCount || void 0, - readLength, - state: getItemState(item), - dateArchived: item.archivedAt || void 0, - image: item.image || void 0, - updatedAt: item.updatedAt || void 0, - ...functionMap - }; - let frontMatter = { - id: item.id - }; - if (frontMatterTemplate) { - const frontMatterTemplateRendered = mustache_default.render(frontMatterTemplate, articleView); - try { - const frontMatterParsed = (0, import_obsidian3.parseYaml)(frontMatterTemplateRendered); - frontMatter = { - ...frontMatterParsed, - ...frontMatter - }; - } catch (error) { - console.error("Error parsing front matter template", error); - frontMatter = { - ...frontMatter, - omnivore_error: "There was an error parsing the front matter template. See console for details." - }; - } - } else { - for (const item2 of frontMatterVariables) { - const aliasedVariables = item2.split("::"); - const variable = aliasedVariables[0]; - const articleVariable = snakeToCamelCase(variable); - const key = aliasedVariables[1] || variable; - if (variable === "tags" && articleView.labels && articleView.labels.length > 0) { - frontMatter[key] = articleView.labels.map((l2) => l2.name); - continue; - } - const value = articleView[articleVariable]; - if (value) { - frontMatter[key] = value; - } - } - } - const content = mustache_default.render(template, articleView); - let contentWithoutFrontMatter = removeFrontMatterFromContent(content); - let frontMatterYaml = (0, import_obsidian3.stringifyYaml)(frontMatter); - if (isSingleFile) { - const sectionStart = `%%${item.id}_start%%`; - const sectionEnd = `%%${item.id}_end%%`; - contentWithoutFrontMatter = `${sectionStart} -${contentWithoutFrontMatter} -${sectionEnd}`; - frontMatterYaml = (0, import_obsidian3.stringifyYaml)([frontMatter]); - } - const frontMatterStr = `--- -${frontMatterYaml}---`; - return `${frontMatterStr} - -${contentWithoutFrontMatter}`; -}; -var render3 = (item, template, dateFormat) => { - const dateSaved = formatDate(item.savedAt, dateFormat); - const datePublished = item.publishedAt ? formatDate(item.publishedAt, dateFormat).trim() : void 0; - const dateArchived = item.archivedAt ? formatDate(item.archivedAt, dateFormat).trim() : void 0; - const dateRead = item.readAt ? formatDate(item.readAt, dateFormat).trim() : void 0; - const view = { - ...item, - siteName: item.siteName || siteNameFromUrl(item.originalArticleUrl || item.url), - author: item.author || "unknown", - omnivoreUrl: getOmnivoreUrl(item), - originalUrl: item.originalArticleUrl || item.url, - date: dateSaved, - dateSaved, - datePublished, - dateArchived, - dateRead, - type: item.pageType, - state: getItemState(item), - ...functionMap - }; - return mustache_default.render(template, view); -}; -var preParseTemplate = (template) => { - return mustache_default.parse(template); -}; - -// src/settings/index.ts -var FRONT_MATTER_VARIABLES = [ - "title", - "author", - "tags", - "date_saved", - "date_published", - "omnivore_url", - "site_name", - "original_url", - "description", - "note", - "type", - "date_read", - "words_count", - "read_length", - "state", - "date_archived", - "image" -]; -var Filter = /* @__PURE__ */ ((Filter2) => { - Filter2["ALL"] = "Sync all the items"; - Filter2["LIBRARY"] = "Sync only the library items"; - Filter2["ARCHIVED"] = "Sync only the archived items"; - Filter2["HIGHLIGHTS"] = "Sync only the highlighted items"; - return Filter2; -})(Filter || {}); -var HighlightOrder = /* @__PURE__ */ ((HighlightOrder2) => { - HighlightOrder2["LOCATION"] = "the location of highlights in the article"; - HighlightOrder2["TIME"] = "the time that highlights are updated"; - return HighlightOrder2; -})(HighlightOrder || {}); -var DEFAULT_SETTINGS = { - dateHighlightedFormat: "yyyy-MM-dd HH:mm:ss", - dateSavedFormat: "yyyy-MM-dd HH:mm:ss", - apiKey: "", - filter: "ALL", - syncAt: "", - customQuery: "", - template: DEFAULT_TEMPLATE, - highlightOrder: "LOCATION", - syncing: false, - folder: "Omnivore/{{{date}}}", - folderDateFormat: "yyyy-MM-dd", - endpoint: "https://api-prod.omnivore.app/api/graphql", - filename: "{{{title}}}", - filenameDateFormat: "yyyy-MM-dd", - attachmentFolder: "Omnivore/attachments", - version: "0.0.0", - isSingleFile: false, - frequency: 0, - intervalId: 0, - frontMatterVariables: [], - frontMatterTemplate: "", - syncOnStart: true, - enableHighlightColorRender: false, - highlightManagerId: "omni" /* OMNIVORE */, - highlightColorMapping: { - ["yellow" /* Yellow */]: "#fff3a3", - ["red" /* Red */]: "#ff5582", - ["blue" /* Blue */]: "#adccff", - ["green" /* Green */]: "#bbfabb" - } -}; - -// src/settingsTab.ts -var import_obsidian6 = require("obsidian"); - -// src/settings/file-suggest.ts -var import_obsidian5 = require("obsidian"); - -// node_modules/@popperjs/core/lib/enums.js -var top = "top"; -var bottom = "bottom"; -var right = "right"; -var left = "left"; -var auto = "auto"; -var basePlacements = [top, bottom, right, left]; -var start = "start"; -var end = "end"; -var clippingParents = "clippingParents"; -var viewport = "viewport"; -var popper = "popper"; -var reference = "reference"; -var variationPlacements = /* @__PURE__ */ basePlacements.reduce(function(acc, placement) { - return acc.concat([placement + "-" + start, placement + "-" + end]); -}, []); -var placements = /* @__PURE__ */ [].concat(basePlacements, [auto]).reduce(function(acc, placement) { - return acc.concat([placement, placement + "-" + start, placement + "-" + end]); -}, []); -var beforeRead = "beforeRead"; -var read = "read"; -var afterRead = "afterRead"; -var beforeMain = "beforeMain"; -var main = "main"; -var afterMain = "afterMain"; -var beforeWrite = "beforeWrite"; -var write = "write"; -var afterWrite = "afterWrite"; -var modifierPhases = [beforeRead, read, afterRead, beforeMain, main, afterMain, beforeWrite, write, afterWrite]; - -// node_modules/@popperjs/core/lib/dom-utils/getNodeName.js -function getNodeName(element) { - return element ? (element.nodeName || "").toLowerCase() : null; -} - -// node_modules/@popperjs/core/lib/dom-utils/getWindow.js -function getWindow(node) { - if (node == null) { - return window; - } - if (node.toString() !== "[object Window]") { - var ownerDocument = node.ownerDocument; - return ownerDocument ? ownerDocument.defaultView || window : window; - } - return node; -} - -// node_modules/@popperjs/core/lib/dom-utils/instanceOf.js -function isElement(node) { - var OwnElement = getWindow(node).Element; - return node instanceof OwnElement || node instanceof Element; -} -function isHTMLElement(node) { - var OwnElement = getWindow(node).HTMLElement; - return node instanceof OwnElement || node instanceof HTMLElement; -} -function isShadowRoot(node) { - if (typeof ShadowRoot === "undefined") { - return false; - } - var OwnElement = getWindow(node).ShadowRoot; - return node instanceof OwnElement || node instanceof ShadowRoot; -} - -// node_modules/@popperjs/core/lib/modifiers/applyStyles.js -function applyStyles(_ref) { - var state = _ref.state; - Object.keys(state.elements).forEach(function(name) { - var style = state.styles[name] || {}; - var attributes = state.attributes[name] || {}; - var element = state.elements[name]; - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } - Object.assign(element.style, style); - Object.keys(attributes).forEach(function(name2) { - var value = attributes[name2]; - if (value === false) { - element.removeAttribute(name2); - } else { - element.setAttribute(name2, value === true ? "" : value); - } - }); - }); -} -function effect(_ref2) { - var state = _ref2.state; - var initialStyles = { - popper: { - position: state.options.strategy, - left: "0", - top: "0", - margin: "0" - }, - arrow: { - position: "absolute" - }, - reference: {} - }; - Object.assign(state.elements.popper.style, initialStyles.popper); - state.styles = initialStyles; - if (state.elements.arrow) { - Object.assign(state.elements.arrow.style, initialStyles.arrow); - } - return function() { - Object.keys(state.elements).forEach(function(name) { - var element = state.elements[name]; - var attributes = state.attributes[name] || {}; - var styleProperties = Object.keys(state.styles.hasOwnProperty(name) ? state.styles[name] : initialStyles[name]); - var style = styleProperties.reduce(function(style2, property) { - style2[property] = ""; - return style2; - }, {}); - if (!isHTMLElement(element) || !getNodeName(element)) { - return; - } - Object.assign(element.style, style); - Object.keys(attributes).forEach(function(attribute) { - element.removeAttribute(attribute); - }); - }); - }; -} -var applyStyles_default = { - name: "applyStyles", - enabled: true, - phase: "write", - fn: applyStyles, - effect, - requires: ["computeStyles"] -}; - -// node_modules/@popperjs/core/lib/utils/getBasePlacement.js -function getBasePlacement(placement) { - return placement.split("-")[0]; -} - -// node_modules/@popperjs/core/lib/utils/math.js -var max = Math.max; -var min = Math.min; -var round = Math.round; - -// node_modules/@popperjs/core/lib/utils/userAgent.js -function getUAString() { - var uaData = navigator.userAgentData; - if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) { - return uaData.brands.map(function(item) { - return item.brand + "/" + item.version; - }).join(" "); - } - return navigator.userAgent; -} - -// node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js -function isLayoutViewport() { - return !/^((?!chrome|android).)*safari/i.test(getUAString()); -} - -// node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js -function getBoundingClientRect(element, includeScale, isFixedStrategy) { - if (includeScale === void 0) { - includeScale = false; - } - if (isFixedStrategy === void 0) { - isFixedStrategy = false; - } - var clientRect = element.getBoundingClientRect(); - var scaleX = 1; - var scaleY = 1; - if (includeScale && isHTMLElement(element)) { - scaleX = element.offsetWidth > 0 ? round(clientRect.width) / element.offsetWidth || 1 : 1; - scaleY = element.offsetHeight > 0 ? round(clientRect.height) / element.offsetHeight || 1 : 1; - } - var _ref = isElement(element) ? getWindow(element) : window, visualViewport = _ref.visualViewport; - var addVisualOffsets = !isLayoutViewport() && isFixedStrategy; - var x = (clientRect.left + (addVisualOffsets && visualViewport ? visualViewport.offsetLeft : 0)) / scaleX; - var y = (clientRect.top + (addVisualOffsets && visualViewport ? visualViewport.offsetTop : 0)) / scaleY; - var width = clientRect.width / scaleX; - var height = clientRect.height / scaleY; - return { - width, - height, - top: y, - right: x + width, - bottom: y + height, - left: x, - x, - y - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js -function getLayoutRect(element) { - var clientRect = getBoundingClientRect(element); - var width = element.offsetWidth; - var height = element.offsetHeight; - if (Math.abs(clientRect.width - width) <= 1) { - width = clientRect.width; - } - if (Math.abs(clientRect.height - height) <= 1) { - height = clientRect.height; - } - return { - x: element.offsetLeft, - y: element.offsetTop, - width, - height - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/contains.js -function contains(parent, child) { - var rootNode = child.getRootNode && child.getRootNode(); - if (parent.contains(child)) { - return true; - } else if (rootNode && isShadowRoot(rootNode)) { - var next = child; - do { - if (next && parent.isSameNode(next)) { - return true; - } - next = next.parentNode || next.host; - } while (next); - } - return false; -} - -// node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js -function getComputedStyle(element) { - return getWindow(element).getComputedStyle(element); -} - -// node_modules/@popperjs/core/lib/dom-utils/isTableElement.js -function isTableElement(element) { - return ["table", "td", "th"].indexOf(getNodeName(element)) >= 0; -} - -// node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js -function getDocumentElement(element) { - return ((isElement(element) ? element.ownerDocument : element.document) || window.document).documentElement; -} - -// node_modules/@popperjs/core/lib/dom-utils/getParentNode.js -function getParentNode(element) { - if (getNodeName(element) === "html") { - return element; - } - return element.assignedSlot || element.parentNode || (isShadowRoot(element) ? element.host : null) || getDocumentElement(element); -} - -// node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js -function getTrueOffsetParent(element) { - if (!isHTMLElement(element) || getComputedStyle(element).position === "fixed") { - return null; - } - return element.offsetParent; -} -function getContainingBlock(element) { - var isFirefox = /firefox/i.test(getUAString()); - var isIE = /Trident/i.test(getUAString()); - if (isIE && isHTMLElement(element)) { - var elementCss = getComputedStyle(element); - if (elementCss.position === "fixed") { - return null; - } - } - var currentNode = getParentNode(element); - if (isShadowRoot(currentNode)) { - currentNode = currentNode.host; - } - while (isHTMLElement(currentNode) && ["html", "body"].indexOf(getNodeName(currentNode)) < 0) { - var css = getComputedStyle(currentNode); - if (css.transform !== "none" || css.perspective !== "none" || css.contain === "paint" || ["transform", "perspective"].indexOf(css.willChange) !== -1 || isFirefox && css.willChange === "filter" || isFirefox && css.filter && css.filter !== "none") { - return currentNode; - } else { - currentNode = currentNode.parentNode; - } - } - return null; -} -function getOffsetParent(element) { - var window2 = getWindow(element); - var offsetParent = getTrueOffsetParent(element); - while (offsetParent && isTableElement(offsetParent) && getComputedStyle(offsetParent).position === "static") { - offsetParent = getTrueOffsetParent(offsetParent); - } - if (offsetParent && (getNodeName(offsetParent) === "html" || getNodeName(offsetParent) === "body" && getComputedStyle(offsetParent).position === "static")) { - return window2; - } - return offsetParent || getContainingBlock(element) || window2; -} - -// node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js -function getMainAxisFromPlacement(placement) { - return ["top", "bottom"].indexOf(placement) >= 0 ? "x" : "y"; -} - -// node_modules/@popperjs/core/lib/utils/within.js -function within(min2, value, max2) { - return max(min2, min(value, max2)); -} -function withinMaxClamp(min2, value, max2) { - var v = within(min2, value, max2); - return v > max2 ? max2 : v; -} - -// node_modules/@popperjs/core/lib/utils/getFreshSideObject.js -function getFreshSideObject() { - return { - top: 0, - right: 0, - bottom: 0, - left: 0 - }; -} - -// node_modules/@popperjs/core/lib/utils/mergePaddingObject.js -function mergePaddingObject(paddingObject) { - return Object.assign({}, getFreshSideObject(), paddingObject); -} - -// node_modules/@popperjs/core/lib/utils/expandToHashMap.js -function expandToHashMap(value, keys) { - return keys.reduce(function(hashMap, key) { - hashMap[key] = value; - return hashMap; - }, {}); -} - -// node_modules/@popperjs/core/lib/modifiers/arrow.js -var toPaddingObject = function toPaddingObject2(padding, state) { - padding = typeof padding === "function" ? padding(Object.assign({}, state.rects, { - placement: state.placement - })) : padding; - return mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); -}; -function arrow(_ref) { - var _state$modifiersData$; - var state = _ref.state, name = _ref.name, options = _ref.options; - var arrowElement = state.elements.arrow; - var popperOffsets2 = state.modifiersData.popperOffsets; - var basePlacement = getBasePlacement(state.placement); - var axis = getMainAxisFromPlacement(basePlacement); - var isVertical = [left, right].indexOf(basePlacement) >= 0; - var len = isVertical ? "height" : "width"; - if (!arrowElement || !popperOffsets2) { - return; - } - var paddingObject = toPaddingObject(options.padding, state); - var arrowRect = getLayoutRect(arrowElement); - var minProp = axis === "y" ? top : left; - var maxProp = axis === "y" ? bottom : right; - var endDiff = state.rects.reference[len] + state.rects.reference[axis] - popperOffsets2[axis] - state.rects.popper[len]; - var startDiff = popperOffsets2[axis] - state.rects.reference[axis]; - var arrowOffsetParent = getOffsetParent(arrowElement); - var clientSize = arrowOffsetParent ? axis === "y" ? arrowOffsetParent.clientHeight || 0 : arrowOffsetParent.clientWidth || 0 : 0; - var centerToReference = endDiff / 2 - startDiff / 2; - var min2 = paddingObject[minProp]; - var max2 = clientSize - arrowRect[len] - paddingObject[maxProp]; - var center = clientSize / 2 - arrowRect[len] / 2 + centerToReference; - var offset3 = within(min2, center, max2); - var axisProp = axis; - state.modifiersData[name] = (_state$modifiersData$ = {}, _state$modifiersData$[axisProp] = offset3, _state$modifiersData$.centerOffset = offset3 - center, _state$modifiersData$); -} -function effect2(_ref2) { - var state = _ref2.state, options = _ref2.options; - var _options$element = options.element, arrowElement = _options$element === void 0 ? "[data-popper-arrow]" : _options$element; - if (arrowElement == null) { - return; - } - if (typeof arrowElement === "string") { - arrowElement = state.elements.popper.querySelector(arrowElement); - if (!arrowElement) { - return; - } - } - if (!contains(state.elements.popper, arrowElement)) { - return; - } - state.elements.arrow = arrowElement; -} -var arrow_default = { - name: "arrow", - enabled: true, - phase: "main", - fn: arrow, - effect: effect2, - requires: ["popperOffsets"], - requiresIfExists: ["preventOverflow"] -}; - -// node_modules/@popperjs/core/lib/utils/getVariation.js -function getVariation(placement) { - return placement.split("-")[1]; -} - -// node_modules/@popperjs/core/lib/modifiers/computeStyles.js -var unsetSides = { - top: "auto", - right: "auto", - bottom: "auto", - left: "auto" -}; -function roundOffsetsByDPR(_ref, win) { - var x = _ref.x, y = _ref.y; - var dpr = win.devicePixelRatio || 1; - return { - x: round(x * dpr) / dpr || 0, - y: round(y * dpr) / dpr || 0 - }; -} -function mapToStyles(_ref2) { - var _Object$assign2; - var popper2 = _ref2.popper, popperRect = _ref2.popperRect, placement = _ref2.placement, variation = _ref2.variation, offsets = _ref2.offsets, position = _ref2.position, gpuAcceleration = _ref2.gpuAcceleration, adaptive = _ref2.adaptive, roundOffsets = _ref2.roundOffsets, isFixed = _ref2.isFixed; - var _offsets$x = offsets.x, x = _offsets$x === void 0 ? 0 : _offsets$x, _offsets$y = offsets.y, y = _offsets$y === void 0 ? 0 : _offsets$y; - var _ref3 = typeof roundOffsets === "function" ? roundOffsets({ - x, - y - }) : { - x, - y - }; - x = _ref3.x; - y = _ref3.y; - var hasX = offsets.hasOwnProperty("x"); - var hasY = offsets.hasOwnProperty("y"); - var sideX = left; - var sideY = top; - var win = window; - if (adaptive) { - var offsetParent = getOffsetParent(popper2); - var heightProp = "clientHeight"; - var widthProp = "clientWidth"; - if (offsetParent === getWindow(popper2)) { - offsetParent = getDocumentElement(popper2); - if (getComputedStyle(offsetParent).position !== "static" && position === "absolute") { - heightProp = "scrollHeight"; - widthProp = "scrollWidth"; - } - } - offsetParent = offsetParent; - if (placement === top || (placement === left || placement === right) && variation === end) { - sideY = bottom; - var offsetY = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.height : offsetParent[heightProp]; - y -= offsetY - popperRect.height; - y *= gpuAcceleration ? 1 : -1; - } - if (placement === left || (placement === top || placement === bottom) && variation === end) { - sideX = right; - var offsetX = isFixed && offsetParent === win && win.visualViewport ? win.visualViewport.width : offsetParent[widthProp]; - x -= offsetX - popperRect.width; - x *= gpuAcceleration ? 1 : -1; - } - } - var commonStyles = Object.assign({ - position - }, adaptive && unsetSides); - var _ref4 = roundOffsets === true ? roundOffsetsByDPR({ - x, - y - }, getWindow(popper2)) : { - x, - y - }; - x = _ref4.x; - y = _ref4.y; - if (gpuAcceleration) { - var _Object$assign; - return Object.assign({}, commonStyles, (_Object$assign = {}, _Object$assign[sideY] = hasY ? "0" : "", _Object$assign[sideX] = hasX ? "0" : "", _Object$assign.transform = (win.devicePixelRatio || 1) <= 1 ? "translate(" + x + "px, " + y + "px)" : "translate3d(" + x + "px, " + y + "px, 0)", _Object$assign)); - } - return Object.assign({}, commonStyles, (_Object$assign2 = {}, _Object$assign2[sideY] = hasY ? y + "px" : "", _Object$assign2[sideX] = hasX ? x + "px" : "", _Object$assign2.transform = "", _Object$assign2)); -} -function computeStyles(_ref5) { - var state = _ref5.state, options = _ref5.options; - var _options$gpuAccelerat = options.gpuAcceleration, gpuAcceleration = _options$gpuAccelerat === void 0 ? true : _options$gpuAccelerat, _options$adaptive = options.adaptive, adaptive = _options$adaptive === void 0 ? true : _options$adaptive, _options$roundOffsets = options.roundOffsets, roundOffsets = _options$roundOffsets === void 0 ? true : _options$roundOffsets; - var commonStyles = { - placement: getBasePlacement(state.placement), - variation: getVariation(state.placement), - popper: state.elements.popper, - popperRect: state.rects.popper, - gpuAcceleration, - isFixed: state.options.strategy === "fixed" - }; - if (state.modifiersData.popperOffsets != null) { - state.styles.popper = Object.assign({}, state.styles.popper, mapToStyles(Object.assign({}, commonStyles, { - offsets: state.modifiersData.popperOffsets, - position: state.options.strategy, - adaptive, - roundOffsets - }))); - } - if (state.modifiersData.arrow != null) { - state.styles.arrow = Object.assign({}, state.styles.arrow, mapToStyles(Object.assign({}, commonStyles, { - offsets: state.modifiersData.arrow, - position: "absolute", - adaptive: false, - roundOffsets - }))); - } - state.attributes.popper = Object.assign({}, state.attributes.popper, { - "data-popper-placement": state.placement - }); -} -var computeStyles_default = { - name: "computeStyles", - enabled: true, - phase: "beforeWrite", - fn: computeStyles, - data: {} -}; - -// node_modules/@popperjs/core/lib/modifiers/eventListeners.js -var passive = { - passive: true -}; -function effect3(_ref) { - var state = _ref.state, instance = _ref.instance, options = _ref.options; - var _options$scroll = options.scroll, scroll = _options$scroll === void 0 ? true : _options$scroll, _options$resize = options.resize, resize = _options$resize === void 0 ? true : _options$resize; - var window2 = getWindow(state.elements.popper); - var scrollParents = [].concat(state.scrollParents.reference, state.scrollParents.popper); - if (scroll) { - scrollParents.forEach(function(scrollParent) { - scrollParent.addEventListener("scroll", instance.update, passive); - }); - } - if (resize) { - window2.addEventListener("resize", instance.update, passive); - } - return function() { - if (scroll) { - scrollParents.forEach(function(scrollParent) { - scrollParent.removeEventListener("scroll", instance.update, passive); - }); - } - if (resize) { - window2.removeEventListener("resize", instance.update, passive); - } - }; -} -var eventListeners_default = { - name: "eventListeners", - enabled: true, - phase: "write", - fn: function fn() { - }, - effect: effect3, - data: {} -}; - -// node_modules/@popperjs/core/lib/utils/getOppositePlacement.js -var hash = { - left: "right", - right: "left", - bottom: "top", - top: "bottom" -}; -function getOppositePlacement(placement) { - return placement.replace(/left|right|bottom|top/g, function(matched) { - return hash[matched]; - }); -} - -// node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js -var hash2 = { - start: "end", - end: "start" -}; -function getOppositeVariationPlacement(placement) { - return placement.replace(/start|end/g, function(matched) { - return hash2[matched]; - }); -} - -// node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js -function getWindowScroll(node) { - var win = getWindow(node); - var scrollLeft = win.pageXOffset; - var scrollTop = win.pageYOffset; - return { - scrollLeft, - scrollTop - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js -function getWindowScrollBarX(element) { - return getBoundingClientRect(getDocumentElement(element)).left + getWindowScroll(element).scrollLeft; -} - -// node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js -function getViewportRect(element, strategy) { - var win = getWindow(element); - var html = getDocumentElement(element); - var visualViewport = win.visualViewport; - var width = html.clientWidth; - var height = html.clientHeight; - var x = 0; - var y = 0; - if (visualViewport) { - width = visualViewport.width; - height = visualViewport.height; - var layoutViewport = isLayoutViewport(); - if (layoutViewport || !layoutViewport && strategy === "fixed") { - x = visualViewport.offsetLeft; - y = visualViewport.offsetTop; - } - } - return { - width, - height, - x: x + getWindowScrollBarX(element), - y - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js -function getDocumentRect(element) { - var _element$ownerDocumen; - var html = getDocumentElement(element); - var winScroll = getWindowScroll(element); - var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; - var width = max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); - var height = max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); - var x = -winScroll.scrollLeft + getWindowScrollBarX(element); - var y = -winScroll.scrollTop; - if (getComputedStyle(body || html).direction === "rtl") { - x += max(html.clientWidth, body ? body.clientWidth : 0) - width; - } - return { - width, - height, - x, - y - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js -function isScrollParent(element) { - var _getComputedStyle = getComputedStyle(element), overflow = _getComputedStyle.overflow, overflowX = _getComputedStyle.overflowX, overflowY = _getComputedStyle.overflowY; - return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX); -} - -// node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js -function getScrollParent(node) { - if (["html", "body", "#document"].indexOf(getNodeName(node)) >= 0) { - return node.ownerDocument.body; - } - if (isHTMLElement(node) && isScrollParent(node)) { - return node; - } - return getScrollParent(getParentNode(node)); -} - -// node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js -function listScrollParents(element, list) { - var _element$ownerDocumen; - if (list === void 0) { - list = []; - } - var scrollParent = getScrollParent(element); - var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); - var win = getWindow(scrollParent); - var target = isBody ? [win].concat(win.visualViewport || [], isScrollParent(scrollParent) ? scrollParent : []) : scrollParent; - var updatedList = list.concat(target); - return isBody ? updatedList : updatedList.concat(listScrollParents(getParentNode(target))); -} - -// node_modules/@popperjs/core/lib/utils/rectToClientRect.js -function rectToClientRect(rect) { - return Object.assign({}, rect, { - left: rect.x, - top: rect.y, - right: rect.x + rect.width, - bottom: rect.y + rect.height - }); -} - -// node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js -function getInnerBoundingClientRect(element, strategy) { - var rect = getBoundingClientRect(element, false, strategy === "fixed"); - rect.top = rect.top + element.clientTop; - rect.left = rect.left + element.clientLeft; - rect.bottom = rect.top + element.clientHeight; - rect.right = rect.left + element.clientWidth; - rect.width = element.clientWidth; - rect.height = element.clientHeight; - rect.x = rect.left; - rect.y = rect.top; - return rect; -} -function getClientRectFromMixedType(element, clippingParent, strategy) { - return clippingParent === viewport ? rectToClientRect(getViewportRect(element, strategy)) : isElement(clippingParent) ? getInnerBoundingClientRect(clippingParent, strategy) : rectToClientRect(getDocumentRect(getDocumentElement(element))); -} -function getClippingParents(element) { - var clippingParents2 = listScrollParents(getParentNode(element)); - var canEscapeClipping = ["absolute", "fixed"].indexOf(getComputedStyle(element).position) >= 0; - var clipperElement = canEscapeClipping && isHTMLElement(element) ? getOffsetParent(element) : element; - if (!isElement(clipperElement)) { - return []; - } - return clippingParents2.filter(function(clippingParent) { - return isElement(clippingParent) && contains(clippingParent, clipperElement) && getNodeName(clippingParent) !== "body"; - }); -} -function getClippingRect(element, boundary, rootBoundary, strategy) { - var mainClippingParents = boundary === "clippingParents" ? getClippingParents(element) : [].concat(boundary); - var clippingParents2 = [].concat(mainClippingParents, [rootBoundary]); - var firstClippingParent = clippingParents2[0]; - var clippingRect = clippingParents2.reduce(function(accRect, clippingParent) { - var rect = getClientRectFromMixedType(element, clippingParent, strategy); - accRect.top = max(rect.top, accRect.top); - accRect.right = min(rect.right, accRect.right); - accRect.bottom = min(rect.bottom, accRect.bottom); - accRect.left = max(rect.left, accRect.left); - return accRect; - }, getClientRectFromMixedType(element, firstClippingParent, strategy)); - clippingRect.width = clippingRect.right - clippingRect.left; - clippingRect.height = clippingRect.bottom - clippingRect.top; - clippingRect.x = clippingRect.left; - clippingRect.y = clippingRect.top; - return clippingRect; -} - -// node_modules/@popperjs/core/lib/utils/computeOffsets.js -function computeOffsets(_ref) { - var reference2 = _ref.reference, element = _ref.element, placement = _ref.placement; - var basePlacement = placement ? getBasePlacement(placement) : null; - var variation = placement ? getVariation(placement) : null; - var commonX = reference2.x + reference2.width / 2 - element.width / 2; - var commonY = reference2.y + reference2.height / 2 - element.height / 2; - var offsets; - switch (basePlacement) { - case top: - offsets = { - x: commonX, - y: reference2.y - element.height - }; - break; - case bottom: - offsets = { - x: commonX, - y: reference2.y + reference2.height - }; - break; - case right: - offsets = { - x: reference2.x + reference2.width, - y: commonY - }; - break; - case left: - offsets = { - x: reference2.x - element.width, - y: commonY - }; - break; - default: - offsets = { - x: reference2.x, - y: reference2.y - }; - } - var mainAxis = basePlacement ? getMainAxisFromPlacement(basePlacement) : null; - if (mainAxis != null) { - var len = mainAxis === "y" ? "height" : "width"; - switch (variation) { - case start: - offsets[mainAxis] = offsets[mainAxis] - (reference2[len] / 2 - element[len] / 2); - break; - case end: - offsets[mainAxis] = offsets[mainAxis] + (reference2[len] / 2 - element[len] / 2); - break; - default: - } - } - return offsets; -} - -// node_modules/@popperjs/core/lib/utils/detectOverflow.js -function detectOverflow(state, options) { - if (options === void 0) { - options = {}; - } - var _options = options, _options$placement = _options.placement, placement = _options$placement === void 0 ? state.placement : _options$placement, _options$strategy = _options.strategy, strategy = _options$strategy === void 0 ? state.strategy : _options$strategy, _options$boundary = _options.boundary, boundary = _options$boundary === void 0 ? clippingParents : _options$boundary, _options$rootBoundary = _options.rootBoundary, rootBoundary = _options$rootBoundary === void 0 ? viewport : _options$rootBoundary, _options$elementConte = _options.elementContext, elementContext = _options$elementConte === void 0 ? popper : _options$elementConte, _options$altBoundary = _options.altBoundary, altBoundary = _options$altBoundary === void 0 ? false : _options$altBoundary, _options$padding = _options.padding, padding = _options$padding === void 0 ? 0 : _options$padding; - var paddingObject = mergePaddingObject(typeof padding !== "number" ? padding : expandToHashMap(padding, basePlacements)); - var altContext = elementContext === popper ? reference : popper; - var popperRect = state.rects.popper; - var element = state.elements[altBoundary ? altContext : elementContext]; - var clippingClientRect = getClippingRect(isElement(element) ? element : element.contextElement || getDocumentElement(state.elements.popper), boundary, rootBoundary, strategy); - var referenceClientRect = getBoundingClientRect(state.elements.reference); - var popperOffsets2 = computeOffsets({ - reference: referenceClientRect, - element: popperRect, - strategy: "absolute", - placement - }); - var popperClientRect = rectToClientRect(Object.assign({}, popperRect, popperOffsets2)); - var elementClientRect = elementContext === popper ? popperClientRect : referenceClientRect; - var overflowOffsets = { - top: clippingClientRect.top - elementClientRect.top + paddingObject.top, - bottom: elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom, - left: clippingClientRect.left - elementClientRect.left + paddingObject.left, - right: elementClientRect.right - clippingClientRect.right + paddingObject.right - }; - var offsetData = state.modifiersData.offset; - if (elementContext === popper && offsetData) { - var offset3 = offsetData[placement]; - Object.keys(overflowOffsets).forEach(function(key) { - var multiply = [right, bottom].indexOf(key) >= 0 ? 1 : -1; - var axis = [top, bottom].indexOf(key) >= 0 ? "y" : "x"; - overflowOffsets[key] += offset3[axis] * multiply; - }); - } - return overflowOffsets; -} - -// node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js -function computeAutoPlacement(state, options) { - if (options === void 0) { - options = {}; - } - var _options = options, placement = _options.placement, boundary = _options.boundary, rootBoundary = _options.rootBoundary, padding = _options.padding, flipVariations = _options.flipVariations, _options$allowedAutoP = _options.allowedAutoPlacements, allowedAutoPlacements = _options$allowedAutoP === void 0 ? placements : _options$allowedAutoP; - var variation = getVariation(placement); - var placements2 = variation ? flipVariations ? variationPlacements : variationPlacements.filter(function(placement2) { - return getVariation(placement2) === variation; - }) : basePlacements; - var allowedPlacements = placements2.filter(function(placement2) { - return allowedAutoPlacements.indexOf(placement2) >= 0; - }); - if (allowedPlacements.length === 0) { - allowedPlacements = placements2; - } - var overflows = allowedPlacements.reduce(function(acc, placement2) { - acc[placement2] = detectOverflow(state, { - placement: placement2, - boundary, - rootBoundary, - padding - })[getBasePlacement(placement2)]; - return acc; - }, {}); - return Object.keys(overflows).sort(function(a, b) { - return overflows[a] - overflows[b]; - }); -} - -// node_modules/@popperjs/core/lib/modifiers/flip.js -function getExpandedFallbackPlacements(placement) { - if (getBasePlacement(placement) === auto) { - return []; - } - var oppositePlacement = getOppositePlacement(placement); - return [getOppositeVariationPlacement(placement), oppositePlacement, getOppositeVariationPlacement(oppositePlacement)]; -} -function flip(_ref) { - var state = _ref.state, options = _ref.options, name = _ref.name; - if (state.modifiersData[name]._skip) { - return; - } - var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? true : _options$altAxis, specifiedFallbackPlacements = options.fallbackPlacements, padding = options.padding, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, _options$flipVariatio = options.flipVariations, flipVariations = _options$flipVariatio === void 0 ? true : _options$flipVariatio, allowedAutoPlacements = options.allowedAutoPlacements; - var preferredPlacement = state.options.placement; - var basePlacement = getBasePlacement(preferredPlacement); - var isBasePlacement = basePlacement === preferredPlacement; - var fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipVariations ? [getOppositePlacement(preferredPlacement)] : getExpandedFallbackPlacements(preferredPlacement)); - var placements2 = [preferredPlacement].concat(fallbackPlacements).reduce(function(acc, placement2) { - return acc.concat(getBasePlacement(placement2) === auto ? computeAutoPlacement(state, { - placement: placement2, - boundary, - rootBoundary, - padding, - flipVariations, - allowedAutoPlacements - }) : placement2); - }, []); - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var checksMap = /* @__PURE__ */ new Map(); - var makeFallbackChecks = true; - var firstFittingPlacement = placements2[0]; - for (var i = 0; i < placements2.length; i++) { - var placement = placements2[i]; - var _basePlacement = getBasePlacement(placement); - var isStartVariation = getVariation(placement) === start; - var isVertical = [top, bottom].indexOf(_basePlacement) >= 0; - var len = isVertical ? "width" : "height"; - var overflow = detectOverflow(state, { - placement, - boundary, - rootBoundary, - altBoundary, - padding - }); - var mainVariationSide = isVertical ? isStartVariation ? right : left : isStartVariation ? bottom : top; - if (referenceRect[len] > popperRect[len]) { - mainVariationSide = getOppositePlacement(mainVariationSide); - } - var altVariationSide = getOppositePlacement(mainVariationSide); - var checks = []; - if (checkMainAxis) { - checks.push(overflow[_basePlacement] <= 0); - } - if (checkAltAxis) { - checks.push(overflow[mainVariationSide] <= 0, overflow[altVariationSide] <= 0); - } - if (checks.every(function(check) { - return check; - })) { - firstFittingPlacement = placement; - makeFallbackChecks = false; - break; - } - checksMap.set(placement, checks); - } - if (makeFallbackChecks) { - var numberOfChecks = flipVariations ? 3 : 1; - var _loop = function _loop2(_i2) { - var fittingPlacement = placements2.find(function(placement2) { - var checks2 = checksMap.get(placement2); - if (checks2) { - return checks2.slice(0, _i2).every(function(check) { - return check; - }); - } - }); - if (fittingPlacement) { - firstFittingPlacement = fittingPlacement; - return "break"; - } - }; - for (var _i = numberOfChecks; _i > 0; _i--) { - var _ret = _loop(_i); - if (_ret === "break") - break; - } - } - if (state.placement !== firstFittingPlacement) { - state.modifiersData[name]._skip = true; - state.placement = firstFittingPlacement; - state.reset = true; - } -} -var flip_default = { - name: "flip", - enabled: true, - phase: "main", - fn: flip, - requiresIfExists: ["offset"], - data: { - _skip: false - } -}; - -// node_modules/@popperjs/core/lib/modifiers/hide.js -function getSideOffsets(overflow, rect, preventedOffsets) { - if (preventedOffsets === void 0) { - preventedOffsets = { - x: 0, - y: 0 - }; - } - return { - top: overflow.top - rect.height - preventedOffsets.y, - right: overflow.right - rect.width + preventedOffsets.x, - bottom: overflow.bottom - rect.height + preventedOffsets.y, - left: overflow.left - rect.width - preventedOffsets.x - }; -} -function isAnySideFullyClipped(overflow) { - return [top, right, bottom, left].some(function(side) { - return overflow[side] >= 0; - }); -} -function hide(_ref) { - var state = _ref.state, name = _ref.name; - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var preventedOffsets = state.modifiersData.preventOverflow; - var referenceOverflow = detectOverflow(state, { - elementContext: "reference" - }); - var popperAltOverflow = detectOverflow(state, { - altBoundary: true - }); - var referenceClippingOffsets = getSideOffsets(referenceOverflow, referenceRect); - var popperEscapeOffsets = getSideOffsets(popperAltOverflow, popperRect, preventedOffsets); - var isReferenceHidden = isAnySideFullyClipped(referenceClippingOffsets); - var hasPopperEscaped = isAnySideFullyClipped(popperEscapeOffsets); - state.modifiersData[name] = { - referenceClippingOffsets, - popperEscapeOffsets, - isReferenceHidden, - hasPopperEscaped - }; - state.attributes.popper = Object.assign({}, state.attributes.popper, { - "data-popper-reference-hidden": isReferenceHidden, - "data-popper-escaped": hasPopperEscaped - }); -} -var hide_default = { - name: "hide", - enabled: true, - phase: "main", - requiresIfExists: ["preventOverflow"], - fn: hide -}; - -// node_modules/@popperjs/core/lib/modifiers/offset.js -function distanceAndSkiddingToXY(placement, rects, offset3) { - var basePlacement = getBasePlacement(placement); - var invertDistance = [left, top].indexOf(basePlacement) >= 0 ? -1 : 1; - var _ref = typeof offset3 === "function" ? offset3(Object.assign({}, rects, { - placement - })) : offset3, skidding = _ref[0], distance = _ref[1]; - skidding = skidding || 0; - distance = (distance || 0) * invertDistance; - return [left, right].indexOf(basePlacement) >= 0 ? { - x: distance, - y: skidding - } : { - x: skidding, - y: distance - }; -} -function offset2(_ref2) { - var state = _ref2.state, options = _ref2.options, name = _ref2.name; - var _options$offset = options.offset, offset3 = _options$offset === void 0 ? [0, 0] : _options$offset; - var data2 = placements.reduce(function(acc, placement) { - acc[placement] = distanceAndSkiddingToXY(placement, state.rects, offset3); - return acc; - }, {}); - var _data$state$placement = data2[state.placement], x = _data$state$placement.x, y = _data$state$placement.y; - if (state.modifiersData.popperOffsets != null) { - state.modifiersData.popperOffsets.x += x; - state.modifiersData.popperOffsets.y += y; - } - state.modifiersData[name] = data2; -} -var offset_default = { - name: "offset", - enabled: true, - phase: "main", - requires: ["popperOffsets"], - fn: offset2 -}; - -// node_modules/@popperjs/core/lib/modifiers/popperOffsets.js -function popperOffsets(_ref) { - var state = _ref.state, name = _ref.name; - state.modifiersData[name] = computeOffsets({ - reference: state.rects.reference, - element: state.rects.popper, - strategy: "absolute", - placement: state.placement - }); -} -var popperOffsets_default = { - name: "popperOffsets", - enabled: true, - phase: "read", - fn: popperOffsets, - data: {} -}; - -// node_modules/@popperjs/core/lib/utils/getAltAxis.js -function getAltAxis(axis) { - return axis === "x" ? "y" : "x"; -} - -// node_modules/@popperjs/core/lib/modifiers/preventOverflow.js -function preventOverflow(_ref) { - var state = _ref.state, options = _ref.options, name = _ref.name; - var _options$mainAxis = options.mainAxis, checkMainAxis = _options$mainAxis === void 0 ? true : _options$mainAxis, _options$altAxis = options.altAxis, checkAltAxis = _options$altAxis === void 0 ? false : _options$altAxis, boundary = options.boundary, rootBoundary = options.rootBoundary, altBoundary = options.altBoundary, padding = options.padding, _options$tether = options.tether, tether = _options$tether === void 0 ? true : _options$tether, _options$tetherOffset = options.tetherOffset, tetherOffset = _options$tetherOffset === void 0 ? 0 : _options$tetherOffset; - var overflow = detectOverflow(state, { - boundary, - rootBoundary, - padding, - altBoundary - }); - var basePlacement = getBasePlacement(state.placement); - var variation = getVariation(state.placement); - var isBasePlacement = !variation; - var mainAxis = getMainAxisFromPlacement(basePlacement); - var altAxis = getAltAxis(mainAxis); - var popperOffsets2 = state.modifiersData.popperOffsets; - var referenceRect = state.rects.reference; - var popperRect = state.rects.popper; - var tetherOffsetValue = typeof tetherOffset === "function" ? tetherOffset(Object.assign({}, state.rects, { - placement: state.placement - })) : tetherOffset; - var normalizedTetherOffsetValue = typeof tetherOffsetValue === "number" ? { - mainAxis: tetherOffsetValue, - altAxis: tetherOffsetValue - } : Object.assign({ - mainAxis: 0, - altAxis: 0 - }, tetherOffsetValue); - var offsetModifierState = state.modifiersData.offset ? state.modifiersData.offset[state.placement] : null; - var data2 = { - x: 0, - y: 0 - }; - if (!popperOffsets2) { - return; - } - if (checkMainAxis) { - var _offsetModifierState$; - var mainSide = mainAxis === "y" ? top : left; - var altSide = mainAxis === "y" ? bottom : right; - var len = mainAxis === "y" ? "height" : "width"; - var offset3 = popperOffsets2[mainAxis]; - var min2 = offset3 + overflow[mainSide]; - var max2 = offset3 - overflow[altSide]; - var additive = tether ? -popperRect[len] / 2 : 0; - var minLen = variation === start ? referenceRect[len] : popperRect[len]; - var maxLen = variation === start ? -popperRect[len] : -referenceRect[len]; - var arrowElement = state.elements.arrow; - var arrowRect = tether && arrowElement ? getLayoutRect(arrowElement) : { - width: 0, - height: 0 - }; - var arrowPaddingObject = state.modifiersData["arrow#persistent"] ? state.modifiersData["arrow#persistent"].padding : getFreshSideObject(); - var arrowPaddingMin = arrowPaddingObject[mainSide]; - var arrowPaddingMax = arrowPaddingObject[altSide]; - var arrowLen = within(0, referenceRect[len], arrowRect[len]); - var minOffset = isBasePlacement ? referenceRect[len] / 2 - additive - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis : minLen - arrowLen - arrowPaddingMin - normalizedTetherOffsetValue.mainAxis; - var maxOffset = isBasePlacement ? -referenceRect[len] / 2 + additive + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis : maxLen + arrowLen + arrowPaddingMax + normalizedTetherOffsetValue.mainAxis; - var arrowOffsetParent = state.elements.arrow && getOffsetParent(state.elements.arrow); - var clientOffset = arrowOffsetParent ? mainAxis === "y" ? arrowOffsetParent.clientTop || 0 : arrowOffsetParent.clientLeft || 0 : 0; - var offsetModifierValue = (_offsetModifierState$ = offsetModifierState == null ? void 0 : offsetModifierState[mainAxis]) != null ? _offsetModifierState$ : 0; - var tetherMin = offset3 + minOffset - offsetModifierValue - clientOffset; - var tetherMax = offset3 + maxOffset - offsetModifierValue; - var preventedOffset = within(tether ? min(min2, tetherMin) : min2, offset3, tether ? max(max2, tetherMax) : max2); - popperOffsets2[mainAxis] = preventedOffset; - data2[mainAxis] = preventedOffset - offset3; - } - if (checkAltAxis) { - var _offsetModifierState$2; - var _mainSide = mainAxis === "x" ? top : left; - var _altSide = mainAxis === "x" ? bottom : right; - var _offset = popperOffsets2[altAxis]; - var _len = altAxis === "y" ? "height" : "width"; - var _min = _offset + overflow[_mainSide]; - var _max = _offset - overflow[_altSide]; - var isOriginSide = [top, left].indexOf(basePlacement) !== -1; - var _offsetModifierValue = (_offsetModifierState$2 = offsetModifierState == null ? void 0 : offsetModifierState[altAxis]) != null ? _offsetModifierState$2 : 0; - var _tetherMin = isOriginSide ? _min : _offset - referenceRect[_len] - popperRect[_len] - _offsetModifierValue + normalizedTetherOffsetValue.altAxis; - var _tetherMax = isOriginSide ? _offset + referenceRect[_len] + popperRect[_len] - _offsetModifierValue - normalizedTetherOffsetValue.altAxis : _max; - var _preventedOffset = tether && isOriginSide ? withinMaxClamp(_tetherMin, _offset, _tetherMax) : within(tether ? _tetherMin : _min, _offset, tether ? _tetherMax : _max); - popperOffsets2[altAxis] = _preventedOffset; - data2[altAxis] = _preventedOffset - _offset; - } - state.modifiersData[name] = data2; -} -var preventOverflow_default = { - name: "preventOverflow", - enabled: true, - phase: "main", - fn: preventOverflow, - requiresIfExists: ["offset"] -}; - -// node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js -function getHTMLElementScroll(element) { - return { - scrollLeft: element.scrollLeft, - scrollTop: element.scrollTop - }; -} - -// node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js -function getNodeScroll(node) { - if (node === getWindow(node) || !isHTMLElement(node)) { - return getWindowScroll(node); - } else { - return getHTMLElementScroll(node); - } -} - -// node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js -function isElementScaled(element) { - var rect = element.getBoundingClientRect(); - var scaleX = round(rect.width) / element.offsetWidth || 1; - var scaleY = round(rect.height) / element.offsetHeight || 1; - return scaleX !== 1 || scaleY !== 1; -} -function getCompositeRect(elementOrVirtualElement, offsetParent, isFixed) { - if (isFixed === void 0) { - isFixed = false; - } - var isOffsetParentAnElement = isHTMLElement(offsetParent); - var offsetParentIsScaled = isHTMLElement(offsetParent) && isElementScaled(offsetParent); - var documentElement = getDocumentElement(offsetParent); - var rect = getBoundingClientRect(elementOrVirtualElement, offsetParentIsScaled, isFixed); - var scroll = { - scrollLeft: 0, - scrollTop: 0 - }; - var offsets = { - x: 0, - y: 0 - }; - if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) { - if (getNodeName(offsetParent) !== "body" || isScrollParent(documentElement)) { - scroll = getNodeScroll(offsetParent); - } - if (isHTMLElement(offsetParent)) { - offsets = getBoundingClientRect(offsetParent, true); - offsets.x += offsetParent.clientLeft; - offsets.y += offsetParent.clientTop; - } else if (documentElement) { - offsets.x = getWindowScrollBarX(documentElement); - } - } - return { - x: rect.left + scroll.scrollLeft - offsets.x, - y: rect.top + scroll.scrollTop - offsets.y, - width: rect.width, - height: rect.height - }; -} - -// node_modules/@popperjs/core/lib/utils/orderModifiers.js -function order(modifiers) { - var map = /* @__PURE__ */ new Map(); - var visited = /* @__PURE__ */ new Set(); - var result = []; - modifiers.forEach(function(modifier) { - map.set(modifier.name, modifier); - }); - function sort(modifier) { - visited.add(modifier.name); - var requires = [].concat(modifier.requires || [], modifier.requiresIfExists || []); - requires.forEach(function(dep) { - if (!visited.has(dep)) { - var depModifier = map.get(dep); - if (depModifier) { - sort(depModifier); - } - } - }); - result.push(modifier); - } - modifiers.forEach(function(modifier) { - if (!visited.has(modifier.name)) { - sort(modifier); - } - }); - return result; -} -function orderModifiers(modifiers) { - var orderedModifiers = order(modifiers); - return modifierPhases.reduce(function(acc, phase) { - return acc.concat(orderedModifiers.filter(function(modifier) { - return modifier.phase === phase; - })); - }, []); -} - -// node_modules/@popperjs/core/lib/utils/debounce.js -function debounce(fn2) { - var pending; - return function() { - if (!pending) { - pending = new Promise(function(resolve) { - Promise.resolve().then(function() { - pending = void 0; - resolve(fn2()); - }); - }); - } - return pending; - }; -} - -// node_modules/@popperjs/core/lib/utils/mergeByName.js -function mergeByName(modifiers) { - var merged = modifiers.reduce(function(merged2, current) { - var existing = merged2[current.name]; - merged2[current.name] = existing ? Object.assign({}, existing, current, { - options: Object.assign({}, existing.options, current.options), - data: Object.assign({}, existing.data, current.data) - }) : current; - return merged2; - }, {}); - return Object.keys(merged).map(function(key) { - return merged[key]; - }); -} - -// node_modules/@popperjs/core/lib/createPopper.js -var DEFAULT_OPTIONS = { - placement: "bottom", - modifiers: [], - strategy: "absolute" -}; -function areValidElements() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - return !args.some(function(element) { - return !(element && typeof element.getBoundingClientRect === "function"); - }); -} -function popperGenerator(generatorOptions) { - if (generatorOptions === void 0) { - generatorOptions = {}; - } - var _generatorOptions = generatorOptions, _generatorOptions$def = _generatorOptions.defaultModifiers, defaultModifiers2 = _generatorOptions$def === void 0 ? [] : _generatorOptions$def, _generatorOptions$def2 = _generatorOptions.defaultOptions, defaultOptions = _generatorOptions$def2 === void 0 ? DEFAULT_OPTIONS : _generatorOptions$def2; - return function createPopper2(reference2, popper2, options) { - if (options === void 0) { - options = defaultOptions; - } - var state = { - placement: "bottom", - orderedModifiers: [], - options: Object.assign({}, DEFAULT_OPTIONS, defaultOptions), - modifiersData: {}, - elements: { - reference: reference2, - popper: popper2 - }, - attributes: {}, - styles: {} - }; - var effectCleanupFns = []; - var isDestroyed = false; - var instance = { - state, - setOptions: function setOptions(setOptionsAction) { - var options2 = typeof setOptionsAction === "function" ? setOptionsAction(state.options) : setOptionsAction; - cleanupModifierEffects(); - state.options = Object.assign({}, defaultOptions, state.options, options2); - state.scrollParents = { - reference: isElement(reference2) ? listScrollParents(reference2) : reference2.contextElement ? listScrollParents(reference2.contextElement) : [], - popper: listScrollParents(popper2) - }; - var orderedModifiers = orderModifiers(mergeByName([].concat(defaultModifiers2, state.options.modifiers))); - state.orderedModifiers = orderedModifiers.filter(function(m) { - return m.enabled; - }); - runModifierEffects(); - return instance.update(); - }, - forceUpdate: function forceUpdate() { - if (isDestroyed) { - return; - } - var _state$elements = state.elements, reference3 = _state$elements.reference, popper3 = _state$elements.popper; - if (!areValidElements(reference3, popper3)) { - return; - } - state.rects = { - reference: getCompositeRect(reference3, getOffsetParent(popper3), state.options.strategy === "fixed"), - popper: getLayoutRect(popper3) - }; - state.reset = false; - state.placement = state.options.placement; - state.orderedModifiers.forEach(function(modifier) { - return state.modifiersData[modifier.name] = Object.assign({}, modifier.data); - }); - for (var index = 0; index < state.orderedModifiers.length; index++) { - if (state.reset === true) { - state.reset = false; - index = -1; - continue; - } - var _state$orderedModifie = state.orderedModifiers[index], fn2 = _state$orderedModifie.fn, _state$orderedModifie2 = _state$orderedModifie.options, _options = _state$orderedModifie2 === void 0 ? {} : _state$orderedModifie2, name = _state$orderedModifie.name; - if (typeof fn2 === "function") { - state = fn2({ - state, - options: _options, - name, - instance - }) || state; - } - } - }, - update: debounce(function() { - return new Promise(function(resolve) { - instance.forceUpdate(); - resolve(state); - }); - }), - destroy: function destroy() { - cleanupModifierEffects(); - isDestroyed = true; - } - }; - if (!areValidElements(reference2, popper2)) { - return instance; - } - instance.setOptions(options).then(function(state2) { - if (!isDestroyed && options.onFirstUpdate) { - options.onFirstUpdate(state2); - } - }); - function runModifierEffects() { - state.orderedModifiers.forEach(function(_ref) { - var name = _ref.name, _ref$options = _ref.options, options2 = _ref$options === void 0 ? {} : _ref$options, effect4 = _ref.effect; - if (typeof effect4 === "function") { - var cleanupFn = effect4({ - state, - name, - instance, - options: options2 - }); - var noopFn = function noopFn2() { - }; - effectCleanupFns.push(cleanupFn || noopFn); - } - }); - } - function cleanupModifierEffects() { - effectCleanupFns.forEach(function(fn2) { - return fn2(); - }); - effectCleanupFns = []; - } - return instance; - }; -} - -// node_modules/@popperjs/core/lib/popper.js -var defaultModifiers = [eventListeners_default, popperOffsets_default, computeStyles_default, applyStyles_default, offset_default, flip_default, preventOverflow_default, arrow_default, hide_default]; -var createPopper = /* @__PURE__ */ popperGenerator({ - defaultModifiers -}); - -// src/settings/suggest.ts -var import_obsidian4 = require("obsidian"); -var Suggest = class { - constructor(owner, containerEl, scope) { - this.owner = owner; - this.containerEl = containerEl; - containerEl.on("click", ".suggestion-item", this.onSuggestionClick.bind(this)); - containerEl.on("mousemove", ".suggestion-item", this.onSuggestionMouseover.bind(this)); - scope.register([], "ArrowUp", (event) => { - if (!event.isComposing) { - this.setSelectedItem(this.selectedItem - 1, true); - return false; - } - }); - scope.register([], "ArrowDown", (event) => { - if (!event.isComposing) { - this.setSelectedItem(this.selectedItem + 1, true); - return false; - } - }); - scope.register([], "Enter", (event) => { - if (!event.isComposing) { - this.useSelectedItem(event); - return false; - } - }); - } - onSuggestionClick(event, el) { - event.preventDefault(); - const item = this.suggestions.indexOf(el); - this.setSelectedItem(item, false); - this.useSelectedItem(event); - } - onSuggestionMouseover(_event, el) { - const item = this.suggestions.indexOf(el); - this.setSelectedItem(item, false); - } - setSuggestions(values) { - this.containerEl.empty(); - const suggestionEls = []; - values.forEach((value) => { - const suggestionEl = this.containerEl.createDiv("suggestion-item"); - this.owner.renderSuggestion(value, suggestionEl); - suggestionEls.push(suggestionEl); - }); - this.values = values; - this.suggestions = suggestionEls; - this.setSelectedItem(0, false); - } - useSelectedItem(event) { - const currentValue = this.values[this.selectedItem]; - if (currentValue) { - this.owner.selectSuggestion(currentValue, event); - } - } - setSelectedItem(selectedIndex, scrollIntoView) { - const normalizedIndex = wrapAround(selectedIndex, this.suggestions.length); - const prevSelectedSuggestion = this.suggestions[this.selectedItem]; - const selectedSuggestion = this.suggestions[normalizedIndex]; - prevSelectedSuggestion?.removeClass("is-selected"); - selectedSuggestion?.addClass("is-selected"); - this.selectedItem = normalizedIndex; - if (scrollIntoView) { - selectedSuggestion.scrollIntoView(false); - } - } -}; -var TextInputSuggest = class { - constructor(app, inputEl) { - this.app = app; - this.inputEl = inputEl; - this.scope = new import_obsidian4.Scope(); - this.suggestEl = createDiv("suggestion-container"); - const suggestion = this.suggestEl.createDiv("suggestion"); - this.suggest = new Suggest(this, suggestion, this.scope); - this.scope.register([], "Escape", this.close.bind(this)); - this.inputEl.addEventListener("input", this.onInputChanged.bind(this)); - this.inputEl.addEventListener("focus", this.onInputChanged.bind(this)); - this.inputEl.addEventListener("blur", this.close.bind(this)); - this.suggestEl.on("mousedown", ".suggestion-container", (event) => { - event.preventDefault(); - }); - } - onInputChanged() { - const inputStr = this.inputEl.value; - const suggestions = this.getSuggestions(inputStr); - if (suggestions.length > 0) { - this.suggest.setSuggestions(suggestions); - this.open(this.app.dom.appContainerEl, this.inputEl); - } - } - open(container, inputEl) { - ; - this.app.keymap.pushScope(this.scope); - container.appendChild(this.suggestEl); - this.popper = createPopper(inputEl, this.suggestEl, { - placement: "bottom-start", - modifiers: [ - { - name: "sameWidth", - enabled: true, - fn: ({ state, instance }) => { - const targetWidth = `${state.rects.reference.width}px`; - if (state.styles.popper.width === targetWidth) { - return; - } - state.styles.popper.width = targetWidth; - instance.update(); - }, - phase: "beforeWrite", - requires: ["computeStyles"] - } - ] - }); - } - close() { - ; - this.app.keymap.popScope(this.scope); - this.suggest.setSuggestions([]); - this.popper.destroy(); - this.suggestEl.detach(); - } -}; - -// src/settings/file-suggest.ts -var FolderSuggest = class extends TextInputSuggest { - getSuggestions(inputStr) { - const abstractFiles = this.app.vault.getAllLoadedFiles(); - const folders = []; - const lowerCaseInputStr = inputStr.toLowerCase(); - abstractFiles.forEach((folder) => { - if (folder instanceof import_obsidian5.TFolder && folder.path.toLowerCase().contains(lowerCaseInputStr)) { - folders.push(folder); - } - }); - return folders; - } - renderSuggestion(file, el) { - el.setText(file.path); - } - selectSuggestion(file) { - this.inputEl.value = file.path; - this.inputEl.trigger("input"); - this.close(); - } -}; - -// src/settingsTab.ts -var OmnivoreSettingTab = class extends import_obsidian6.PluginSettingTab { - constructor(app, plugin) { - super(app, plugin); - this.plugin = plugin; - } - display() { - const { containerEl } = this; - containerEl.empty(); - new import_obsidian6.Setting(containerEl).setName("API Key").setDesc(createFragment((fragment) => { - fragment.append("You can create an API key at ", fragment.createEl("a", { - text: "https://omnivore.app/settings/api", - href: "https://omnivore.app/settings/api" - })); - })).addText((text) => text.setPlaceholder("Enter your Omnivore Api Key").setValue(this.plugin.settings.apiKey).onChange(async (value) => { - this.plugin.settings.apiKey = value; - await this.plugin.saveSettings(); - })); - containerEl.createEl("h3", { text: "Query" }); - new import_obsidian6.Setting(containerEl).setName("Filter").setDesc("Select an Omnivore search filter type. Changing this would update the 'Custom Query' accordingly and reset the 'Last sync' timestamp").addDropdown((dropdown) => { - dropdown.addOptions(Filter); - dropdown.setValue(this.plugin.settings.filter).onChange(async (value) => { - this.plugin.settings.filter = value; - this.plugin.settings.customQuery = getQueryFromFilter(value); - this.plugin.settings.syncAt = ""; - await this.plugin.saveSettings(); - this.display(); - }); - }); - new import_obsidian6.Setting(containerEl).setName("Custom Query").setDesc(createFragment((fragment) => { - fragment.append("See ", fragment.createEl("a", { - text: "https://docs.omnivore.app/using/search", - href: "https://docs.omnivore.app/using/search" - }), " for more info on search query syntax. Changing this would reset the 'Last Sync' timestamp"); - })).addText((text) => text.setPlaceholder("Enter an Omnivore custom search query if advanced filter is selected").setValue(this.plugin.settings.customQuery).onChange(async (value) => { - this.plugin.settings.customQuery = value; - this.plugin.settings.syncAt = ""; - await this.plugin.saveSettings(); - })); - containerEl.createEl("h3", { text: "Sync" }); - new import_obsidian6.Setting(containerEl).setName("Sync on startup").setDesc("Check this box if you want to sync with Omnivore when the app is loaded").addToggle((toggle) => toggle.setValue(this.plugin.settings.syncOnStart).onChange(async (value) => { - this.plugin.settings.syncOnStart = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Frequency").setDesc("Enter the frequency in minutes to sync with Omnivore automatically. 0 means manual sync").addText((text) => text.setPlaceholder("Enter the frequency").setValue(this.plugin.settings.frequency.toString()).onChange(async (value) => { - const frequency = parseInt(value); - if (isNaN(frequency)) { - new import_obsidian6.Notice("Frequency must be a positive integer"); - return; - } - this.plugin.settings.frequency = frequency; - await this.plugin.saveSettings(); - this.plugin.scheduleSync(); - })); - new import_obsidian6.Setting(containerEl).setName("Last Sync").setDesc("Last time the plugin synced with Omnivore. The 'Sync' command fetches articles updated after this timestamp").addMomentFormat((momentFormat) => momentFormat.setPlaceholder("Last Sync").setValue(this.plugin.settings.syncAt).setDefaultFormat("yyyy-MM-dd'T'HH:mm:ss").onChange(async (value) => { - this.plugin.settings.syncAt = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Is Single File").setDesc("Check this box if you want to save all articles in a single file").addToggle((toggle) => toggle.setValue(this.plugin.settings.isSingleFile).onChange(async (value) => { - this.plugin.settings.isSingleFile = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Folder").setDesc("Enter the folder where the data will be stored. {{{title}}}, {{{dateSaved}}} and {{{datePublished}}} could be used in the folder name").addSearch((search) => { - new FolderSuggest(this.app, search.inputEl); - search.setPlaceholder("Enter the folder").setValue(this.plugin.settings.folder).onChange(async (value) => { - this.plugin.settings.folder = value; - await this.plugin.saveSettings(); - }); - }); - new import_obsidian6.Setting(containerEl).setName("Folder Date Format").setDesc(createFragment((fragment) => { - fragment.append("If date is used as part of folder name, specify the format date for use. Format ", fragment.createEl("a", { - text: "reference", - href: "https://moment.github.io/luxon/#/formatting?id=table-of-tokens" - })); - })).addText((text) => text.setPlaceholder("yyyy-MM-dd").setValue(this.plugin.settings.folderDateFormat).onChange(async (value) => { - this.plugin.settings.folderDateFormat = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Attachment Folder").setDesc("Enter the folder where the attachment will be downloaded to. {{{title}}}, {{{dateSaved}}} and {{{datePublished}}} could be used in the folder name").addSearch((search) => { - new FolderSuggest(this.app, search.inputEl); - search.setPlaceholder("Enter the attachment folder").setValue(this.plugin.settings.attachmentFolder).onChange(async (value) => { - this.plugin.settings.attachmentFolder = value; - await this.plugin.saveSettings(); - }); - }); - new import_obsidian6.Setting(containerEl).setName("Filename").setDesc("Enter the filename where the data will be stored. {{id}}, {{{title}}}, {{{dateSaved}}} and {{{datePublished}}} could be used in the filename").addText((text) => text.setPlaceholder("Enter the filename").setValue(this.plugin.settings.filename).onChange(async (value) => { - this.plugin.settings.filename = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Filename Date Format").setDesc(createFragment((fragment) => { - fragment.append("If date is used as part of file name, specify the format date for use. Format ", fragment.createEl("a", { - text: "reference", - href: "https://moment.github.io/luxon/#/formatting?id=table-of-tokens" - })); - })).addText((text) => text.setPlaceholder("yyyy-MM-dd").setValue(this.plugin.settings.filenameDateFormat).onChange(async (value) => { - this.plugin.settings.filenameDateFormat = value; - await this.plugin.saveSettings(); - })); - containerEl.createEl("h3", { text: "Article" }); - new import_obsidian6.Setting(containerEl).setName("Front Matter").setDesc(createFragment((fragment) => { - fragment.append("Enter the metadata to be used in your note separated by commas. You can also use custom aliases in the format of metatdata::alias, e.g. date_saved::date. ", fragment.createEl("br"), fragment.createEl("br"), "Available metadata can be found at ", fragment.createEl("a", { - text: "Reference", - href: "https://docs.omnivore.app/integrations/obsidian.html#front-matter" - }), fragment.createEl("br"), fragment.createEl("br"), "If you want to use a custom front matter template, you can enter it below under the advanced settings"); - })).addTextArea((text) => { - text.setPlaceholder("Enter the metadata").setValue(this.plugin.settings.frontMatterVariables.join(",")).onChange(async (value) => { - this.plugin.settings.frontMatterVariables = value.split(",").map((v) => v.trim()).filter((v, i2, a) => FRONT_MATTER_VARIABLES.includes(v.split("::")[0]) && a.indexOf(v) === i2); - await this.plugin.saveSettings(); - }); - text.inputEl.setAttr("rows", 4); - text.inputEl.setAttr("cols", 30); - }); - new import_obsidian6.Setting(containerEl).setName("Article Template").setDesc(createFragment((fragment) => { - fragment.append("Enter template to render articles with ", fragment.createEl("a", { - text: "Reference", - href: "https://docs.omnivore.app/integrations/obsidian.html#controlling-the-layout-of-the-data-imported-to-obsidian" - }), fragment.createEl("br"), fragment.createEl("br"), "If you want to use a custom front matter template, you can enter it below under the advanced settings"); - })).addTextArea((text) => { - text.setPlaceholder("Enter the template").setValue(this.plugin.settings.template).onChange(async (value) => { - this.plugin.settings.template = value ? value : DEFAULT_SETTINGS.template; - await this.plugin.saveSettings(); - }); - text.inputEl.setAttr("rows", 25); - text.inputEl.setAttr("cols", 50); - }).addExtraButton((button) => { - button.setIcon("reset").setTooltip("Reset template").onClick(async () => { - this.plugin.settings.template = DEFAULT_SETTINGS.template; - await this.plugin.saveSettings(); - this.display(); - new import_obsidian6.Notice("Template reset"); - }); - }); - new import_obsidian6.Setting(containerEl).setName("Date Saved Format").setDesc("Enter the date format for dateSaved variable in rendered template").addText((text) => text.setPlaceholder("yyyy-MM-dd'T'HH:mm:ss").setValue(this.plugin.settings.dateSavedFormat).onChange(async (value) => { - this.plugin.settings.dateSavedFormat = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(containerEl).setName("Date Highlighted Format").setDesc("Enter the date format for dateHighlighted variable in rendered template").addText((text) => text.setPlaceholder("Date Highlighted Format").setValue(this.plugin.settings.dateHighlightedFormat).onChange(async (value) => { - this.plugin.settings.dateHighlightedFormat = value; - await this.plugin.saveSettings(); - })); - containerEl.createEl("h4", { text: "Highlights" }); - new import_obsidian6.Setting(containerEl).setName("Highlight Order").setDesc("Select the order in which highlights are applied").addDropdown((dropdown) => { - dropdown.addOptions(HighlightOrder); - dropdown.setValue(this.plugin.settings.highlightOrder).onChange(async (value) => { - this.plugin.settings.highlightOrder = value; - await this.plugin.saveSettings(); - }); - }); - new import_obsidian6.Setting(containerEl).setName("Render Highlight Color").setDesc("Check this box if you want to render highlights with color used in the Omnivore App").addToggle((toggle) => toggle.setValue(this.plugin.settings.enableHighlightColorRender).onChange(async (value) => { - this.plugin.settings.enableHighlightColorRender = value; - await this.plugin.saveSettings(); - this.displayBlock(renderHighlightConfigContainer, value); - })); - const renderHighlightConfigContainer = containerEl.createEl("div"); - this.displayBlock(renderHighlightConfigContainer, this.plugin.settings.enableHighlightColorRender); - new import_obsidian6.Setting(renderHighlightConfigContainer).setName("Use Highlightr for Highlight styling").setDesc(createFragment((fragment) => { - fragment.append(fragment.createEl("a", { - text: "Highlightr", - href: "https://github.com/chetachiezikeuzor/Highlightr-Plugin" - }), " is a community plugin for managing highlight style and hotkeys", fragment.createEl("br"), "Check this if you'd like to delegate configuration of highlight color and styling to it", fragment.createEl("br"), 'Ensure to select "css-class" as the highlight-method in the highlightr plugin'); - })).addToggle((toggle) => toggle.setValue(this.plugin.settings.highlightManagerId == "hltr" /* HIGHLIGHTR */).onChange(async (value) => { - this.plugin.settings.highlightManagerId = value ? "hltr" /* HIGHLIGHTR */ : "omni" /* OMNIVORE */; - await this.plugin.saveSettings(); - this.displayBlock(omnivoreHighlightConfigContainer, !value); - })); - const omnivoreHighlightConfigContainer = renderHighlightConfigContainer.createEl("div", { - cls: "omnivore-highlight-config-container" - }); - this.displayBlock(omnivoreHighlightConfigContainer, this.plugin.settings.highlightManagerId == "omni" /* OMNIVORE */); - const highlighterSetting = new import_obsidian6.Setting(omnivoreHighlightConfigContainer); - const colorPickers = {}; - highlighterSetting.setName("Configure highlight colors").setDesc("Configure how the highlight colors in Omnivore should render in notes").addButton((button) => { - button.setButtonText("Save"); - button.setTooltip("Save highlight color setting"); - button.setClass("omnivore-btn"); - button.setClass("omnivore-btn-primary"); - button.onClick(async (e) => { - const highlightColorMapping = this.plugin.settings.highlightColorMapping; - Object.entries(colorPickers).forEach(([color, picker]) => { - highlightColorMapping[color] = picker.getValue(); - }); - setOrUpdateHighlightColors(highlightColorMapping); - await this.plugin.saveSettings(); - new import_obsidian6.Notice("Saved highlight color settings"); - }); - }); - const getPenIcon = (hexCode) => ``; - const colorMap = this.plugin.settings.highlightColorMapping; - Object.entries(colorMap).forEach(([colorName, hexCode]) => { - let penIcon = getPenIcon(hexCode); - const settingItem = omnivoreHighlightConfigContainer.createEl("div"); - settingItem.addClass("omnivore-highlight-setting-item"); - const colorIcon = settingItem.createEl("span"); - colorIcon.addClass("omnivore-highlight-setting-icon"); - colorIcon.innerHTML = penIcon; - const colorSetting = new import_obsidian6.Setting(settingItem).setName(colorName).setDesc(hexCode); - colorSetting.addColorPicker((colorPicker) => { - colorPicker.setValue(hexCode); - colorPickers[colorName] = colorPicker; - colorPicker.onChange((v) => { - penIcon = getPenIcon(v); - colorIcon.innerHTML = penIcon; - colorSetting.setDesc(v); - }); - }); - }); - containerEl.createEl("h3", { - cls: "omnivore-collapsible", - text: "Advanced Settings" - }); - const advancedSettings = containerEl.createEl("div", { - cls: "omnivore-content" - }); - new import_obsidian6.Setting(advancedSettings).setName("API Endpoint").setDesc("Enter the Omnivore server's API endpoint").addText((text) => text.setPlaceholder("API endpoint").setValue(this.plugin.settings.endpoint).onChange(async (value) => { - this.plugin.settings.endpoint = value; - await this.plugin.saveSettings(); - })); - new import_obsidian6.Setting(advancedSettings).setName("Front Matter Template").setDesc(createFragment((fragment) => { - fragment.append("Enter YAML template to render the front matter with ", fragment.createEl("a", { - text: "Reference", - href: "https://docs.omnivore.app/integrations/obsidian.html#front-matter-template" - }), fragment.createEl("br"), fragment.createEl("br"), "We recommend you to use Front Matter section under the basic settings to define the metadata.", fragment.createEl("br"), fragment.createEl("br"), "If this template is set, it will override the Front Matter so please make sure your template is a valid YAML."); - })).addTextArea((text) => { - text.setPlaceholder("Enter the template").setValue(this.plugin.settings.frontMatterTemplate).onChange(async (value) => { - this.plugin.settings.frontMatterTemplate = value; - await this.plugin.saveSettings(); - }); - text.inputEl.setAttr("rows", 10); - text.inputEl.setAttr("cols", 30); - }).addExtraButton((button) => { - button.setIcon("reset").setTooltip("Reset front matter template").onClick(async () => { - this.plugin.settings.frontMatterTemplate = DEFAULT_SETTINGS.frontMatterTemplate; - await this.plugin.saveSettings(); - this.display(); - new import_obsidian6.Notice("Front matter template reset"); - }); - }); - const help = containerEl.createEl("p"); - help.innerHTML = `For more information, please visit our GitHub page, email us at feedback@omnivore.app or join our Discord server.`; - const coll = document.getElementsByClassName("omnivore-collapsible"); - let i; - for (i = 0; i < coll.length; i++) { - coll[i].addEventListener("click", function() { - this.classList.toggle("omnivore-active"); - const content = this.nextElementSibling; - if (content.style.maxHeight) { - content.style.maxHeight = null; - } else { - content.style.maxHeight = "fit-content"; - } - }); - } - } - displayBlock(block, display) { - block.style.display = display ? "block" : "none"; - } -}; - -// src/main.ts -var OmnivorePlugin = class extends import_obsidian7.Plugin { - async onload() { - await this.loadSettings(); - await this.resetSyncingStateSetting(); - const latestVersion = this.manifest.version; - const currentVersion = this.settings.version; - if (latestVersion !== currentVersion) { - this.settings.version = latestVersion; - await this.saveSettings(); - const releaseNotes = `Omnivore plugin is upgraded to ${latestVersion}. - - What's new: https://github.com/omnivore-app/obsidian-omnivore/blob/main/CHANGELOG.md - `; - new import_obsidian7.Notice(releaseNotes, 1e4); - } - this.addCommand({ - id: "sync", - name: "Sync new changes", - callback: async () => { - await this.fetchOmnivore(); - } - }); - this.addCommand({ - id: "deleteArticle", - name: "Delete Current Article from Omnivore", - callback: async () => { - await this.deleteCurrentItem(this.app.workspace.getActiveFile()); - } - }); - this.addCommand({ - id: "resync", - name: "Resync all articles", - callback: async () => { - this.settings.syncAt = ""; - await this.saveSettings(); - new import_obsidian7.Notice("Omnivore Last Sync reset"); - await this.fetchOmnivore(); - } - }); - const iconId = "Omnivore"; - (0, import_obsidian7.addIcon)(iconId, ``); - this.addRibbonIcon(iconId, iconId, async (evt) => { - await this.fetchOmnivore(); - }); - this.addSettingTab(new OmnivoreSettingTab(this.app, this)); - this.scheduleSync(); - if (this.settings.syncOnStart) { - await this.fetchOmnivore(false); - } - } - onunload() { - } - async loadSettings() { - this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); - if (this.settings.filter === "ADVANCED") { - this.settings.filter = "ALL"; - console.log("obsidian-omnivore: advanced filter is replaced with all filter"); - const customQuery = this.settings.customQuery; - this.settings.customQuery = `in:all ${customQuery ? `(${customQuery})` : ""}`; - console.log(`obsidian-omnivore: custom query is set to ${this.settings.customQuery}`); - this.saveSettings(); - } - if (!this.settings.customQuery) { - this.settings.customQuery = getQueryFromFilter(this.settings.filter); - console.log(`obsidian-omnivore: custom query is set to ${this.settings.customQuery}`); - this.saveSettings(); - } - setOrUpdateHighlightColors(this.settings.highlightColorMapping); - } - async saveSettings() { - await this.saveData(this.settings); - } - async scheduleSync() { - if (this.settings.intervalId > 0) { - window.clearInterval(this.settings.intervalId); - } - const frequency = this.settings.frequency; - if (frequency > 0) { - const intervalId = window.setInterval(async () => { - await this.fetchOmnivore(false); - }, frequency * 60 * 1e3); - this.settings.intervalId = intervalId; - await this.saveSettings(); - this.registerInterval(intervalId); - } - } - async downloadFileAsAttachment(item) { - const url = item.url; - const response = await (0, import_obsidian7.requestUrl)({ - url, - contentType: "application/pdf" - }); - const folderName = (0, import_obsidian7.normalizePath)(render3(item, this.settings.attachmentFolder, this.settings.folderDateFormat)); - const folder = this.app.vault.getAbstractFileByPath(folderName); - if (!(folder instanceof import_obsidian7.TFolder)) { - await this.app.vault.createFolder(folderName); - } - const fileName = (0, import_obsidian7.normalizePath)(`${folderName}/${item.id}.pdf`); - const file = this.app.vault.getAbstractFileByPath(fileName); - if (!(file instanceof import_obsidian7.TFile)) { - const newFile = await this.app.vault.createBinary(fileName, response.arrayBuffer); - return newFile.path; - } - return file.path; - } - async fetchOmnivore(manualSync = true) { - const { - syncAt, - apiKey, - customQuery, - highlightOrder, - syncing, - template, - folder, - filename, - isSingleFile, - frontMatterVariables, - frontMatterTemplate - } = this.settings; - if (syncing) { - new import_obsidian7.Notice("\u{1F422} Already syncing ..."); - return; - } - if (!apiKey) { - new import_obsidian7.Notice("Missing Omnivore api key"); - return; - } - this.settings.syncing = true; - await this.saveSettings(); - try { - console.log(`obsidian-omnivore starting sync since: '${syncAt}'`); - manualSync && new import_obsidian7.Notice("\u{1F680} Fetching items ..."); - frontMatterTemplate && preParseTemplate(frontMatterTemplate); - const templateSpans = preParseTemplate(template); - const includeContent = templateSpans.some((templateSpan) => templateSpan[1] === "content"); - const includeFileAttachment = templateSpans.some((templateSpan) => templateSpan[1] === "fileAttachment"); - const size = 15; - for (let after = 0; ; after += size) { - const [items, hasNextPage] = await getItems(this.settings.endpoint, apiKey, after, size, parseDateTime(syncAt).toISO() || void 0, customQuery, includeContent, "highlightedMarkdown"); - for (const item of items) { - const folderName = replaceIllegalCharsFolder((0, import_obsidian7.normalizePath)(render3(item, folder, this.settings.folderDateFormat))); - const omnivoreFolder = this.app.vault.getAbstractFileByPath(folderName); - if (!(omnivoreFolder instanceof import_obsidian7.TFolder)) { - await this.app.vault.createFolder(folderName); - } - const fileAttachment = item.pageType === "FILE" && includeFileAttachment ? await this.downloadFileAsAttachment(item) : void 0; - const content = await renderItemContent(item, template, highlightOrder, this.settings.enableHighlightColorRender ? this.settings.highlightManagerId : void 0, this.settings.dateHighlightedFormat, this.settings.dateSavedFormat, isSingleFile, frontMatterVariables, frontMatterTemplate, fileAttachment); - const customFilename = replaceIllegalCharsFile(renderFilename(item, filename, this.settings.filenameDateFormat)); - const pageName = `${folderName}/${customFilename}.md`; - const normalizedPath = (0, import_obsidian7.normalizePath)(pageName); - const omnivoreFile = this.app.vault.getAbstractFileByPath(normalizedPath); - if (omnivoreFile instanceof import_obsidian7.TFile) { - if (isSingleFile) { - const existingContent = await this.app.vault.read(omnivoreFile); - const contentWithoutFrontmatter = removeFrontMatterFromContent(content); - const existingContentWithoutFrontmatter = removeFrontMatterFromContent(existingContent); - let existingFrontMatter = parseFrontMatterFromContent(existingContent) || []; - if (!Array.isArray(existingFrontMatter)) { - existingFrontMatter = [existingFrontMatter]; - } - const newFrontMatter = parseFrontMatterFromContent(content); - if (!newFrontMatter || !Array.isArray(newFrontMatter) || newFrontMatter.length === 0) { - throw new Error("Front matter does not exist in the template"); - } - let newContentWithoutFrontMatter; - const frontMatterIdx = findFrontMatterIndex(existingFrontMatter, item.id); - if (frontMatterIdx >= 0) { - const sectionStart = `%%${item.id}_start%%`; - const sectionEnd = `%%${item.id}_end%%`; - const existingContentRegex = new RegExp(`${sectionStart}.*?${sectionEnd}`, "s"); - newContentWithoutFrontMatter = existingContentWithoutFrontmatter.replace(existingContentRegex, contentWithoutFrontmatter); - existingFrontMatter[frontMatterIdx] = newFrontMatter[0]; - } else { - newContentWithoutFrontMatter = `${contentWithoutFrontmatter} - -${existingContentWithoutFrontmatter}`; - existingFrontMatter.unshift(newFrontMatter[0]); - } - const newFrontMatterStr = `--- -${(0, import_obsidian7.stringifyYaml)(existingFrontMatter)}---`; - await this.app.vault.modify(omnivoreFile, `${newFrontMatterStr} - -${newContentWithoutFrontMatter}`); - continue; - } - await this.app.fileManager.processFrontMatter(omnivoreFile, async (frontMatter) => { - const id = frontMatter.id; - if (id && id !== item.id) { - const newPageName = `${folderName}/${customFilename}-${item.id}.md`; - const newNormalizedPath = (0, import_obsidian7.normalizePath)(newPageName); - const newOmnivoreFile = this.app.vault.getAbstractFileByPath(newNormalizedPath); - if (newOmnivoreFile instanceof import_obsidian7.TFile) { - const existingContent2 = await this.app.vault.read(newOmnivoreFile); - if (existingContent2 !== content) { - await this.app.vault.modify(newOmnivoreFile, content); - } - return; - } - await this.app.vault.create(newNormalizedPath, content); - return; - } - const existingContent = await this.app.vault.read(omnivoreFile); - if (existingContent !== content) { - await this.app.vault.modify(omnivoreFile, content); - } - }); - continue; - } - try { - await this.app.vault.create(normalizedPath, content); - } catch (error) { - if (error.toString().includes("File already exists")) { - new import_obsidian7.Notice(`Skipping file creation: ${normalizedPath}. Please check if you have duplicated article titles and delete the file if needed.`); - } else { - throw error; - } - } - } - this.settings.syncAt = DateTime.local().toFormat(DATE_FORMAT); - if (!hasNextPage) { - break; - } - } - console.log("obsidian-omnivore sync completed", this.settings.syncAt); - manualSync && new import_obsidian7.Notice("\u{1F389} Sync completed"); - } catch (e) { - new import_obsidian7.Notice("Failed to fetch items"); - console.error(e); - } finally { - this.settings.syncing = false; - await this.saveSettings(); - } - } - async deleteCurrentItem(file) { - if (!file) { - return; - } - const itemId = this.app.metadataCache.getFileCache(file)?.frontmatter?.id; - if (!itemId) { - new import_obsidian7.Notice("Failed to delete article: article id not found"); - } - try { - const isDeleted = deleteItem(this.settings.endpoint, this.settings.apiKey, itemId); - if (!isDeleted) { - new import_obsidian7.Notice("Failed to delete article in Omnivore"); - } - } catch (e) { - new import_obsidian7.Notice("Failed to delete article in Omnivore"); - console.error(e); - } - await this.app.vault.delete(file); - } - async resetSyncingStateSetting() { - this.settings.syncing = false; - this.settings.intervalId = 0; - await this.saveSettings(); - } -}; -/*! - * mustache.js - Logic-less {{mustache}} templates with JavaScript - * http://github.com/janl/mustache.js - */ -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-omnivore/manifest.json b/.obsidian/plugins/obsidian-omnivore/manifest.json deleted file mode 100644 index 81ddc98c..00000000 --- a/.obsidian/plugins/obsidian-omnivore/manifest.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "obsidian-omnivore", - "name": "Omnivore", - "version": "1.10.4", - "minAppVersion": "0.15.0", - "description": "This is an Omnivore plugin for Obsidian.", - "author": "Omnivore", - "authorUrl": "https://github.com/omnivore-app", - "isDesktopOnly": false -} \ No newline at end of file diff --git a/.obsidian/plugins/obsidian-omnivore/styles.css b/.obsidian/plugins/obsidian-omnivore/styles.css deleted file mode 100644 index 07f38574..00000000 --- a/.obsidian/plugins/obsidian-omnivore/styles.css +++ /dev/null @@ -1,77 +0,0 @@ -/* Style the button that is used to open and close the collapsible content */ -.omnivore-collapsible { - cursor: pointer; - border-bottom: outset; -} - -/* Style the collapsible content. Note: hidden by default */ -.omnivore-content { - max-height: 0; - overflow: hidden; - transition: max-height 0.2s ease-out; -} - -.omnivore-collapsible:after { - content: '\02795'; /* Unicode character for "plus" sign (+) */ - float: right; -} - -.omnivore-active:after { - content: '\2796'; /* Unicode character for "minus" sign (-) */ -} - -.omnivore-highlight-config-container { - border-bottom: 1px solid var(--background-modifier-border); -} - -.modal.mod-settings - button:not(.mod-cta):not(.mod-warning).omnivore-btn.omnivore-btn-primary { - color: var(--text-accent); -} - -.modal.mod-settings - button:not(.mod-cta):not(.mod-warning).omnivore-btn.omnivore-btn-primary:hover { - color: var(--text-accent-hover); - background-color: var(--background-secondary); -} - -/*---------------------------------------------------------------- -Omnivore Highlight Color Config Setting -----------------------------------------------------------------*/ - -.omnivore-highlight-setting-item { - display: grid; - grid-gap: 8px; - grid-template-columns: 0.5fr 7fr; - align-items: center; - border-top: 1px solid var(--background-modifier-border); -} - -.omnivore-highlight-setting-icon { - display: flex; - height: 24px; - width: 24px; -} - -mark.omni { - background-color: var(--text-highlight-rgb); - font-weight: 500; - margin: 0 -0.05em; - padding: 0.125em 0.15em; - border-radius: 0.25em; - -webkit-box-decoration-break: clone; - box-decoration-break: clone; -} - -mark.omni-yellow { - --text-highlight-rgb: var(--omni-yellow); -} -mark.omni-red { - --text-highlight-rgb: var(--omni-red); -} -mark.omni-green { - --text-highlight-rgb: var(--omni-green); -} -mark.omni-blue { - --text-highlight-rgb: var(--omni-blue); -} diff --git a/.obsidian/plugins/omnisearch/main.js b/.obsidian/plugins/omnisearch/main.js deleted file mode 100644 index 618ac5d5..00000000 --- a/.obsidian/plugins/omnisearch/main.js +++ /dev/null @@ -1,170 +0,0 @@ -/* -THIS IS A GENERATED/BUNDLED FILE BY ESBUILD -if you want to view the source, please visit the github repository of this plugin -*/ - -var sI=Object.create;var Du=Object.defineProperty;var oI=Object.getOwnPropertyDescriptor;var uI=Object.getOwnPropertyNames;var cI=Object.getPrototypeOf,lI=Object.prototype.hasOwnProperty;var fI=(e,t,r)=>t in e?Du(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var Pi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Nn=(e,t)=>{for(var r in t)Du(e,r,{get:t[r],enumerable:!0})},F_=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of uI(t))!lI.call(e,i)&&i!==r&&Du(e,i,{get:()=>t[i],enumerable:!(n=oI(t,i))||n.enumerable});return e};var ln=(e,t,r)=>(r=e!=null?sI(cI(e)):{},F_(t||!e||!e.__esModule?Du(r,"default",{value:e,enumerable:!0}):r,e)),B_=e=>F_(Du({},"__esModule",{value:!0}),e);var ql=(e,t,r)=>(fI(e,typeof t!="symbol"?t+"":t,r),r),dp=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var Mi=(e,t,r)=>(dp(e,t,"read from private field"),r?r.call(e):t.get(e)),ku=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},hp=(e,t,r,n)=>(dp(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var $_=(e,t,r)=>(dp(e,t,"access private method"),r);var H_,U_=v(()=>{H_="5"});var Wn=v(()=>{U_();typeof window<"u"&&((window.__svelte??={}).v??=new Set).add(H_)});var va,is,as,Fi,Pt,Ht,V_,q_,bt=v(()=>{va="[",is="[!",as="]",Fi={},Pt=Symbol(),Ht=Symbol("filename"),V_=Symbol("hmr"),q_="http://www.w3.org/1999/xhtml"});var zl,z_=v(()=>{zl=!0});var Y_,se,K_=v(()=>{Y_=globalThis.process?.env?.NODE_ENV,se=Y_&&!Y_.toLowerCase().startsWith("prod")});var j_=v(()=>{});var mt=v(()=>{z_();K_();j_()});var xr,ss,Ru,W_,Nt=v(()=>{xr=Symbol("$state"),ss=Symbol("$state metadata"),Ru=Symbol("legacy props"),W_=Symbol("")});function xa(e){return typeof e=="function"}function X_(e){return e()}function os(e){for(var t=0;t{fn=Array.isArray,G_=Array.prototype.indexOf,Lu=Array.from,pp=Object.keys,Kt=Object.defineProperty,Kr=Object.getOwnPropertyDescriptor,Yl=Object.getOwnPropertyDescriptors,mp=Object.prototype,Q_=Array.prototype,Ta=Object.getPrototypeOf;Ut=()=>{}});function Z_(){var e=Pu;Pu=[],os(e)}function J_(){var e=Mu;Mu=[],os(e)}function dn(e){Pu.length===0&&queueMicrotask(Z_),Pu.push(e)}function eb(e){Mu.length===0&&dI(J_),Mu.push(e)}function gp(){Pu.length>0&&Z_(),Mu.length>0&&J_()}var dI,Pu,Mu,On=v(()=>{it();dI=typeof requestIdleCallback>"u"?e=>setTimeout(e,1):requestIdleCallback,Pu=[],Mu=[]});function Kl(e){return e===this.v}function Js(e,t){return e!=e?t==t:e!==t||e!==null&&typeof e=="object"||typeof e=="function"}function eo(e){return!Js(e,this.v)}var us=v(()=>{});function _p(){if(se){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function tb(){if(se){let e=new Error(`derived_references_self -A derived value cannot reference itself recursively -https://svelte.dev/e/derived_references_self`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/derived_references_self")}function rb(e){if(se){let t=new Error(`effect_in_teardown -\`${e}\` cannot be used inside an effect cleanup function -https://svelte.dev/e/effect_in_teardown`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function nb(){if(se){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function ib(e){if(se){let t=new Error(`effect_orphan -\`${e}\` can only be used inside an effect (e.g. during component initialisation) -https://svelte.dev/e/effect_orphan`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_orphan")}function ab(){if(se){let e=new Error(`effect_update_depth_exceeded -Maximum update depth exceeded. This can happen when a reactive block or effect repeatedly sets a new value. Svelte limits the number of nested updates to prevent infinite loops -https://svelte.dev/e/effect_update_depth_exceeded`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function sb(){if(se){let e=new Error(`hydration_failed -Failed to hydrate the application -https://svelte.dev/e/hydration_failed`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/hydration_failed")}function ob(e){if(se){let t=new Error(`props_invalid_value -Cannot do \`bind:${e}={undefined}\` when \`${e}\` has a fallback value -https://svelte.dev/e/props_invalid_value`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/props_invalid_value")}function ub(e){if(se){let t=new Error(`rune_outside_svelte -The \`${e}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files -https://svelte.dev/e/rune_outside_svelte`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function cb(){if(se){let e=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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function lb(){if(se){let e=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function fb(){if(se){let e=new Error("state_unsafe_local_read\nReading state that was created inside the same derived is forbidden. Consider using `untrack` to read locally created state\nhttps://svelte.dev/e/state_unsafe_local_read");throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/state_unsafe_local_read")}function db(){if(se){let e=new Error("state_unsafe_mutation\nUpdating state inside a derived 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 e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}var hn=v(()=>{mt()});function hb(){mi=!0}var mi,gi,Bi=v(()=>{mi=!1,gi=!1});var bp=v(()=>{mt()});var Fu=v(()=>{mt();bp();it()});function $i(e){let t=Error(),r=t.stack;if(r){let n=r.split(` -`),i=[` -`];for(let a=0;a{bt();Fu();it();Nt();He();Ge();Bu=null});function xp(e){cs=e}function Mt(e,t){var r={f:0,v:e,reactions:null,equals:Kl,rv:0,wv:0};return se&&gi&&(r.created=t??$i("CreatedAt"),r.debug=null),r}function Xn(e){return mb(Mt(e))}function _i(e,t=!1){let r=Mt(e);return t||(r.equals=eo),mi&&Pe!==null&&Pe.l!==null&&(Pe.l.s??=[]).push(r),r}function ft(e,t=!1){return mb(_i(e,t))}function mb(e){return $e!==null&&!gn&&$e.f&2&&(Gn===null?_b([e]):Gn.push(e)),e}function oe(e,t){return $e!==null&&!gn&&bi()&&$e.f&18&&(Gn===null||!Gn.includes(e))&&db(),no(e,t)}function no(e,t){if(!e.equals(t)){var r=e.v;if(fs?ro.set(e,t):ro.set(e,r),e.v=t,e.wv=Hu(),se&&gi&&(e.updated=$i("UpdatedAt"),Oe!=null&&(e.trace_need_increase=!0,e.trace_v??=r)),gb(e,2048),bi()&&Oe!==null&&Oe.f&1024&&!(Oe.f&96)&&(pn===null?bb([e]):pn.push(e)),se&&cs.size>0){let n=Array.from(cs);for(let i of n)i.f&1024&&Ar(i,4096),Ui(i)&&ds(i);cs.clear()}}return t}function gb(e,t){var r=e.reactions;if(r!==null)for(var n=bi(),i=r.length,a=0;a{mt();Ge();us();Nt();hn();Bi();to();Ot();cs=new Set,ro=new Map});function kn(e){var t=2050,r=$e!==null&&$e.f&2?$e:null;Oe===null||r!==null&&r.f&256?t|=256:Oe.f|=1048576;let n={ctx:Pe,deps:null,effects:null,equals:Kl,f:t,fn:e,reactions:null,rv:0,v:null,wv:0,parent:r??Oe};return se&&gi&&(n.created=$i("CreatedAt")),n}function Br(e){let t=kn(e);return t.equals=eo,t}function jl(e){var t=e.effects;if(t!==null){e.effects=null;for(var r=0;r{mt();Nt();Ge();us();hn();He();yr();to();Bi();Ot();yp=[]});function Eb(e,t,r){se?console.warn(`%c[svelte] hydration_attribute_changed -%cThe \`${e}\` attribute on \`${t}\` 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`,ao,so):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function vb(e){se?console.warn(`%c[svelte] hydration_html_changed -%c${e?`The value of an \`{@html ...}\` block ${e} changed between server and client renders. The client value will be ignored in favour of the server value`:"The value of an `{@html ...}` block changed between server and client renders. The client value will be ignored in favour of the server value"} -https://svelte.dev/e/hydration_html_changed`,ao,so):console.warn("https://svelte.dev/e/hydration_html_changed")}function ps(e){se?console.warn(`%c[svelte] hydration_mismatch -%c${e?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${e}`:"Hydration failed because the initial UI does not match what was rendered on the server"} -https://svelte.dev/e/hydration_mismatch`,ao,so):console.warn("https://svelte.dev/e/hydration_mismatch")}function Tb(){se?console.warn(`%c[svelte] lifecycle_double_unmount -%cTried to unmount a component that was not mounted -https://svelte.dev/e/lifecycle_double_unmount`,ao,so):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function Sp(e,t){se?console.warn(`%c[svelte] ownership_invalid_mutation -%c${e?`${e} mutated a value owned by ${t}. This is strongly discouraged. Consider passing values to child components with \`bind:\`, or use a callback instead`:"Mutating a value outside the component that created it is strongly discouraged. Consider passing values to child components with `bind:`, or use a callback instead"} -https://svelte.dev/e/ownership_invalid_mutation`,ao,so):console.warn("https://svelte.dev/e/ownership_invalid_mutation")}function Gl(e){se?console.warn(`%c[svelte] state_proxy_equality_mismatch -%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${e}\` will produce unexpected results -https://svelte.dev/e/state_proxy_equality_mismatch`,ao,so):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}var ao,so,Wr=v(()=>{mt();ao="font-weight: bold",so="font-weight: normal"});function $r(e){ge=e}function wt(e){if(e===null)throw ps(),Fi;return De=e}function Vt(){return wt(fr(De))}function Te(e){if(ge){if(fr(De)!==null)throw ps(),Fi;De=e}}function wr(e=1){if(ge){for(var t=e,r=De;t--;)r=fr(r);De=r}}function oo(){for(var e=0,t=De;;){if(t.nodeType===8){var r=t.data;if(r===as){if(e===0)return t;e-=1}else(r===va||r===is)&&(e+=1)}var n=fr(t);t.remove(),t=n}}var ge,De,Et=v(()=>{bt();Wr();Gr();ge=!1});function er(e,t=null,r){var n=null;if(se&&gi&&(n=$i("CreatedAt")),typeof e!="object"||e===null||xr in e)return e;let i=Ta(e);if(i!==mp&&i!==Q_)return e;var a=new Map,o=fn(e),l=Mt(0);o&&a.set("length",Mt(e.length,n));var d;if(se)if(d={parent:t,owners:null},r){let p=r.v?.[ss]?.owners;d.owners=p?new Set(p):null}else d.owners=t===null?Pe!==null?new Set([Pe.function]):null:new Set;return new Proxy(e,{defineProperty(p,g,E){(!("value"in E)||E.configurable===!1||E.enumerable===!1||E.writable===!1)&&cb();var _=a.get(g);return _===void 0?(_=Mt(E.value,n),a.set(g,_)):oe(_,er(E.value,d)),!0},deleteProperty(p,g){var E=a.get(g);if(E===void 0)g in p&&a.set(g,Mt(Pt,n));else{if(o&&typeof g=="string"){var _=a.get("length"),y=Number(g);Number.isInteger(y)&&y<_.v&&oe(_,y)}oe(E,Pt),xb(l)}return!0},get(p,g,E){if(se&&g===ss)return d;if(g===xr)return e;var _=a.get(g),y=g in p;if(_===void 0&&(!y||Kr(p,g)?.writable)&&(_=Mt(er(y?p[g]:Pt,d),n),a.set(g,_)),_!==void 0){var C=q(_);if(se){var k=C?.[ss];k&&k?.parent!==d&&Cp(d,k)}return C===Pt?void 0:C}return Reflect.get(p,g,E)},getOwnPropertyDescriptor(p,g){var E=Reflect.getOwnPropertyDescriptor(p,g);if(E&&"value"in E){var _=a.get(g);_&&(E.value=q(_))}else if(E===void 0){var y=a.get(g),C=y?.v;if(y!==void 0&&C!==Pt)return{enumerable:!0,configurable:!0,value:C,writable:!0}}return E},has(p,g){if(se&&g===ss||g===xr)return!0;var E=a.get(g),_=E!==void 0&&E.v!==Pt||Reflect.has(p,g);if(E!==void 0||Oe!==null&&(!_||Kr(p,g)?.writable)){E===void 0&&(E=Mt(_?er(p[g],d):Pt,n),a.set(g,E));var y=q(E);if(y===Pt)return!1}return _},set(p,g,E,_){var y=a.get(g),C=g in p;if(o&&g==="length")for(var k=E;k=H.v&&oe(H,R+1)}xb(l)}return!0},ownKeys(p){q(l);var g=Reflect.ownKeys(p).filter(y=>{var C=a.get(y);return C===void 0||C.v!==Pt});for(var[E,_]of a)_.v!==Pt&&!(E in p)&&g.push(E);return g},setPrototypeOf(){lb()}})}function xb(e,t=1){oe(e,e.v+t)}function Ql(e){return e!==null&&typeof e=="object"&&xr in e?e[xr]:e}var uo=v(()=>{mt();Ge();Ot();it();Uu();yr();Nt();bt();hn();to();Bi()});function Ab(){let e=Array.prototype,t=Array.__svelte_cleanup;t&&t();let{indexOf:r,lastIndexOf:n,includes:i}=e;e.indexOf=function(a,o){let l=r.call(this,a,o);if(l===-1){for(let d=o??0;d{e.indexOf=r,e.lastIndexOf=n,e.includes=i}}var Ip=v(()=>{Wr();uo()});function Xl(){if(Np===void 0){Np=window,wb=document,Vu=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype;Sb=Kr(t,"firstChild").get,Cb=Kr(t,"nextSibling").get,e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0,Text.prototype.__t=void 0,se&&(e.__svelte_meta=null,Ab())}}function Qr(e=""){return document.createTextNode(e)}function qt(e){return Sb.call(e)}function fr(e){return Cb.call(e)}function xe(e,t){if(!ge)return qt(e);var r=qt(De);if(r===null)r=De.appendChild(Qr());else if(t&&r.nodeType!==3){var n=Qr();return r?.before(n),wt(n),n}return wt(r),r}function Sr(e,t){if(!ge){var r=qt(e);return r instanceof Comment&&r.data===""?fr(r):r}if(t&&De?.nodeType!==3){var n=Qr();return De?.before(n),wt(n),n}return De}function Ye(e,t=1,r=!1){let n=ge?De:e;for(var i;t--;)i=n,n=fr(n);if(!ge)return n;var a=n?.nodeType;if(r&&a!==3){var o=Qr();return n===null?i?.after(o):n.before(o),wt(o),o}return wt(n),n}function qu(e){e.textContent=""}var Np,wb,Vu,Sb,Cb,Gr=v(()=>{Et();mt();Ip();it()});function kp(e){fs=e}function tr(e){$e=e}function Wt(e){Oe=e}function _b(e){Gn=e}function bb(e){pn=e}function Hu(){return++Rb}function Ui(e){var t=e.f;if(t&2048)return!0;if(t&4096){var r=e.deps,n=(t&256)!==0;if(r!==null){var i,a,o=(t&512)!==0,l=n&&Oe!==null&&!Vi,d=r.length;if(o||l){var p=e,g=p.parent;for(i=0;ie.wv)return!0}(!n||Oe!==null&&!Vi)&&Ar(e,1024)}return!1}function Nb(e,t){for(var r=t;r!==null;){if(r.f&128)try{r.fn(e);return}catch{r.f^=128}r=r.parent}throw Zl=!1,e}function Ob(e){return(e.f&16384)===0&&(e.parent===null||(e.parent.f&128)===0)}function lo(e,t,r,n){if(Zl){if(r===null&&(Zl=!1),Ob(t))throw e;return}if(r!==null&&(Zl=!0),!se||n===null||!(e instanceof Error)||Ib.has(e)){Nb(e,t);return}Ib.add(e);let i=[],a=t.fn?.name;a&&i.push(a);let o=n;for(;o!==null;){if(se){var l=o.function?.[Ht];if(l){let g=l.split("/").pop();i.push(g)}}o=o.p}let d=Vu?" ":" ";Kt(e,"message",{value:e.message+` -${i.map(g=>` -${d}in ${g}`).join("")} -`}),Kt(e,"component_stack",{value:i});let p=e.stack;if(p){let g=p.split(` -`),E=[];for(let _=0;_0)for(E.length=bn+Hr.length,_=0;_e.fn)),ef=[]}function gI(){try{ab()}catch(e){if(se&&Kt(e,"stack",{value:""}),zu!==null)if(se)try{lo(e,zu,null,null)}catch(t){throw Db(),t}else lo(e,zu,null,null);else throw se&&Db(),e}}function Op(){var e=ms;try{var t=0;for(ms=!0;Yu.length>0;){t++>1e3&&gI();var r=Yu,n=r.length;Yu=[];for(var i=0;i0;)Ku=!0,Op(),gp();return t}async function Ei(){await Promise.resolve(),fo()}function q(e){var t=e.f,r=(t&2)!==0;if($u!==null&&$u.add(e),$e!==null&&!gn){Gn!==null&&Gn.includes(e)&&fb();var n=$e.deps;e.rv{mt();it();He();Nt();On();yr();hs();hn();bt();Bi();to();Ot();Gr();Ib=new WeakSet,Zl=!1,Ku=!1,zu=null,ms=!1,fs=!1;Yu=[],ef=[],$e=null,gn=!1;Oe=null;Gn=null;Hr=null,bn=0,pn=null;Rb=1,tf=0,Vi=!1,$u=null;EI=-7169});function Fp(e){Oe===null&&$e===null&&ib(e),$e!==null&&$e.f&256&&Oe===null&&nb(),fs&&rb(e)}function vI(e,t){var r=t.last;r===null?t.last=t.first=e:(r.next=e,e.prev=r,t.last=e)}function gs(e,t,r,n=!0){var i=Oe;if(se)for(;i!==null&&i.f&262144;)i=i.parent;var a={ctx:Pe,deps:null,nodes_start:null,nodes_end:null,f:e|2048,first:null,fn:t,last:null,next:null,parent:i,prev:null,teardown:null,transitions:null,wv:0};if(se&&(a.component_function=Xr),r)try{ds(a),a.f|=32768}catch(d){throw lr(a),d}else t!==null&&io(a);var o=r&&a.deps===null&&a.first===null&&a.nodes_start===null&&a.teardown===null&&(a.f&1048704)===0;if(!o&&n&&(i!==null&&vI(a,i),$e!==null&&$e.f&2)){var l=$e;(l.effects??=[]).push(a)}return a}function Cr(e){let t=gs(8,null,!1);return Ar(t,1024),t.teardown=e,t}function vi(e){Fp("$effect");var t=Oe!==null&&(Oe.f&32)!==0&&Pe!==null&&!Pe.m;if(se&&Kt(e,"name",{value:"$effect"}),t){var r=Pe;(r.e??=[]).push({fn:e,effect:Oe,reaction:$e})}else{var n=Gt(e);return n}}function ho(e){return Fp("$effect.pre"),se&&Kt(e,"name",{value:"$effect.pre"}),zt(e)}function af(e){let t=gs(64,e,!0);return()=>{lr(t)}}function Fb(e){let t=gs(64,e,!0);return(r={})=>new Promise(n=>{r.outro?Ln(t,()=>{lr(t),n(void 0)}):(lr(t),n(void 0))})}function Gt(e){return gs(4,e,!1)}function Qt(e,t){var r=Pe,n={effect:null,ran:!1};r.l.r1.push(n),n.effect=zt(()=>{e(),!n.ran&&(n.ran=!0,oe(r.l.r2,!0),at(t))})}function Jn(){var e=Pe;zt(()=>{if(q(e.l.r2)){for(var t of e.l.r1){var r=t.effect;r.f&1024&&Ar(r,4096),Ui(r)&&ds(r),t.ran=!1}e.l.r2.v=!1}})}function zt(e){return gs(8,e,!0)}function rr(e,t=[],r=kn){let n=t.map(r),i=()=>e(...n.map(q));return se&&Kt(i,"name",{value:"{expression}"}),Ir(i)}function Ir(e,t=0){return gs(24|t,e,!0)}function nr(e,t=!0){return gs(40,e,!0,t)}function Rp(e){var t=e.teardown;if(t!==null){let r=fs,n=$e;kp(!0),tr(null);try{t.call(null)}finally{kp(r),tr(n)}}}function Lp(e,t=!1){var r=e.first;for(e.first=e.last=null;r!==null;){var n=r.next;r.f&64?r.parent=null:lr(r,t),r=n}}function Pb(e){for(var t=e.first;t!==null;){var r=t.next;t.f&32||lr(t),t=r}}function lr(e,t=!0){var r=!1;if((t||e.f&524288)&&e.nodes_start!==null){for(var n=e.nodes_start,i=e.nodes_end;n!==null;){var a=n===i?null:fr(n);n.remove(),n=a}r=!0}Lp(e,t&&!r),ju(e,0),Ar(e,16384);var o=e.transitions;if(o!==null)for(let d of o)d.stop();Rp(e);var l=e.parent;l!==null&&l.first!==null&&Pp(e),se&&(e.component_function=null),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes_start=e.nodes_end=null}function Pp(e){var t=e.parent,r=e.prev,n=e.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),t!==null&&(t.first===e&&(t.first=n),t.last===e&&(t.last=r))}function Ln(e,t){var r=[];sf(e,r,!0),Bp(r,()=>{lr(e),t&&t()})}function Bp(e,t){var r=e.length;if(r>0){var n=()=>--r||t();for(var i of e)i.out(n)}else t()}function sf(e,t,r){if(!(e.f&8192)){if(e.f^=8192,e.transitions!==null)for(let o of e.transitions)(o.is_global||r)&&t.push(o);for(var n=e.first;n!==null;){var i=n.next,a=(n.f&65536)!==0||(n.f&32)!==0;sf(n,t,a?r:!1),n=i}}}function ya(e){Bb(e,!0)}function Bb(e,t){if(e.f&8192){e.f^=8192,e.f&1024||(e.f^=1024),Ui(e)&&(Ar(e,2048),io(e));for(var r=e.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;Bb(r,i?t:!1),r=n}if(e.transitions!==null)for(let a of e.transitions)(a.is_global||t)&&a.in()}}var He=v(()=>{Ge();Nt();yr();hn();mt();it();Gr();hs();Ot()});function AI(){let e=new Error().stack;if(!e)return null;let t=[];for(let r of e.split(` -`)){let n=xI.exec(r)??yI.exec(r);n&&t.push({file:n[1],line:+n[2],column:+n[3]})}return t}function $b(){let e=AI()?.slice(4);if(!e)return null;for(let t=0;tr.line)return i.component}}return null}function Cp(e,t){if(t.owners!==null)for(;e;){if(e.owners===null){t.owners=null;break}for(let r of e.owners)t.owners.add(r);e=e.parent}}function Hb(e,t){return e.owners===null?!0:e.owners.has(t)||Ht in t&&[...e.owners].some(r=>r[Ht]===t[Ht])||e.parent!==null&&Hb(e.parent,t)}function Ub(e){return e?.owners?.values().next().value??Ub(e.parent)}function yb(e){if(SI)return;let t=$b();if(t&&!Hb(e,t)){let r=Ub(e);r[Ht]!==t[Ht]?Sp(t[Ht],r[Ht]):Sp()}}var TI,xI,yI,wI,SI,Uu=v(()=>{Nt();He();Ot();it();Wr();bt();TI={},xI=/at (?:.+ \()?(.+):(\d+):(\d+)\)?$/,yI=/@(.+):(\d+):(\d+)$/;wI=Symbol("ADD_OWNER");SI=!1});function po(e){if(se){let t=new Error(`lifecycle_outside_component -\`${e}(...)\` can only be used during component initialisation -https://svelte.dev/e/lifecycle_outside_component`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}var mo=v(()=>{mt()});function Wu(e){Pe=e}function Gu(e){Xr=e}function dr(e,t=!1,r){var n=Pe={p:Pe,c:null,d:!1,e:null,m:!1,s:e,x:null,l:null};mi&&!t&&(Pe.l={s:null,u:null,r1:[],r2:Mt(!1)}),Cr(()=>{n.d=!0}),se&&(Pe.function=r,Xr=r)}function hr(e){let t=Pe;if(t!==null){e!==void 0&&(t.x=e);let o=t.e;if(o!==null){var r=Oe,n=$e;t.e=null;try{for(var i=0;i{mt();Uu();mo();yr();Ge();He();Bi();Pe=null;Xr=null});function Vb(e){e=e.replace(NI,"");let t=5381,r=e.length;for(;r--;)t=(t<<5)-t^e.charCodeAt(r);return(t>>>0).toString(36)}function qb(e){return DI.includes(e)}function $p(e){return e?.replace(/\//g,"/\u200B")}var NI,OI,hB,DI,_s=v(()=>{NI=/\r/g;OI=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","hidden","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"],hB=[...OI,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"],DI=["touchstart","touchmove"]});var zb=v(()=>{_s();Ge();Wr()});var Hp=v(()=>{});var Yb=v(()=>{bt();Et()});function of(){Kb||(Kb=!0,document.addEventListener("reset",e=>{Promise.resolve().then(()=>{if(!e.defaultPrevented)for(let t of e.target.elements)t.__on_r?.()})},{capture:!0}))}var Kb,uf=v(()=>{Et();Gr();On();Kb=!1});function go(e){var t=$e,r=Oe;tr(null),Wt(null);try{return e()}finally{tr(t),Wt(r)}}function Up(e,t,r,n=r){e.addEventListener(t,()=>go(r));let i=e.__on_r;i?e.__on_r=()=>{i(),n(!0)}:e.__on_r=()=>n(!0),of()}var Ti=v(()=>{He();Ge();uf()});function Wb(e,t,r,n={}){function i(a){if(n.capture||_o.call(t,a),!a.cancelBubble)return go(()=>r?.call(this,a))}return e.startsWith("pointer")||e.startsWith("touch")||e==="wheel"?dn(()=>{t.addEventListener(e,i,n)}):t.addEventListener(e,i,n),i}function pr(e,t,r,n,i){var a={capture:n,passive:i},o=Wb(e,t,r,a);(t===document.body||t===window||t===document)&&Cr(()=>{t.removeEventListener(e,o,a)})}function _o(e){var t=this,r=t.ownerDocument,n=e.type,i=e.composedPath?.()||[],a=i[0]||e.target,o=0,l=e.__root;if(l){var d=i.indexOf(l);if(d!==-1&&(t===document||t===window)){e.__root=t;return}var p=i.indexOf(t);if(p===-1)return;d<=p&&(o=d)}if(a=i[o]||e.target,a!==t){Kt(e,"currentTarget",{configurable:!0,get(){return a||r}});var g=$e,E=Oe;tr(null),Wt(null);try{for(var _,y=[];a!==null;){var C=a.assignedSlot||a.parentNode||a.host||null;try{var k=a["__"+n];if(k!=null&&(!a.disabled||e.target===a))if(fn(k)){var[P,...N]=k;P.apply(a,[e,...N])}else k.call(a,e)}catch(L){_?y.push(L):_=L}if(e.cancelBubble||C===t||C===null)break;a=C}if(_){for(let L of y)queueMicrotask(()=>{throw L});throw _}}finally{e.__root=t,delete e.currentTarget,tr(g),Wt(E)}}}var jb,Vp,Xu=v(()=>{He();it();Et();On();bt();Wr();Ge();Ti();jb=new Set,Vp=new Set});function Gb(){kI=void 0}var kI,qp=v(()=>{Et();Gr();He();Nt();bt()});function Zu(e){var t=document.createElement("template");return t.innerHTML=e,t.content}var cf=v(()=>{});function Zr(e,t){var r=Oe;r.nodes_start===null&&(r.nodes_start=e,r.nodes_end=t)}function Le(e,t){var r=(t&1)!==0,n=(t&2)!==0,i,a=!e.startsWith("");return()=>{if(ge)return Zr(De,null),De;i===void 0&&(i=Zu(a?e:""+e),r||(i=qt(i)));var o=n||Vu?document.importNode(i,!0):i.cloneNode(!0);if(r){var l=qt(o),d=o.lastChild;Zr(l,d)}else Zr(o,o);return o}}function Ju(e=""){if(!ge){var t=Qr(e+"");return Zr(t,t),t}var r=De;return r.nodeType!==3&&(r.before(r=Qr()),wt(r)),Zr(r,r),r}function qi(){if(ge)return Zr(De,null),De;var e=document.createDocumentFragment(),t=document.createComment(""),r=Qr();return e.append(t,r),Zr(t,r),e}function we(e,t){if(ge){Oe.nodes_end=De,Vt();return}e!==null&&e.before(t)}var bs=v(()=>{Et();Gr();cf();Ge();bt()});function ir(e,t){var r=t==null?"":typeof t=="object"?t+"":t;r!==(e.__t??=e.nodeValue)&&(e.__t=r,e.nodeValue=r+"")}function Es(e,t){return Qb(e,t)}function Yp(e,t){Xl(),t.intro=t.intro??!1;let r=t.target,n=ge,i=De;try{for(var a=qt(r);a&&(a.nodeType!==8||a.data!==va);)a=fr(a);if(!a)throw Fi;$r(!0),wt(a),Vt();let o=Qb(e,{...t,anchor:a});if(De===null||De.nodeType!==8||De.data!==as)throw ps(),Fi;return $r(!1),o}catch(o){if(o===Fi)return t.recover===!1&&sb(),Xl(),qu(r),$r(!1),Es(e,t);throw o}finally{$r(n),wt(i),Gb()}}function Qb(e,{target:t,anchor:r,props:n={},events:i,context:a,intro:o=!0}){Xl();var l=new Set,d=E=>{for(var _=0;_{var E=r??t.appendChild(Qr());return nr(()=>{if(a){dr({});var _=Pe;_.c=a}i&&(n.$$events=i),ge&&Zr(E,null),lf=o,p=e(E,n)||{},lf=!0,ge&&(Oe.nodes_end=De),a&&hr()}),()=>{for(var _ of l){t.removeEventListener(_,_o);var y=bo.get(_);--y===0?(document.removeEventListener(_,_o),bo.delete(_)):bo.set(_,y)}Vp.delete(d),E!==r&&E.parentNode?.removeChild(E)}});return zp.set(p,g),p}function Eo(e,t){let r=zp.get(e);return r?(zp.delete(e),r(t)):(se&&Tb(),Promise.resolve())}var lf,bo,zp,vs=v(()=>{mt();Gr();bt();Ge();Ot();He();Et();it();Xu();qp();Wr();hn();bs();_s();lf=!0;bo=new Map;zp=new WeakMap});var Xb=v(()=>{bt();Nt();Et();He();yr();vs();Ge()});var Zb=v(()=>{hn();Ot();bt();Uu()});var Jb=v(()=>{bt();Fu();He()});var eE=v(()=>{mt();it();He();yr();Ge();Et();On();bt();Ot()});function tt(e,t,[r,n]=[0,0]){ge&&r===0&&Vt();var i=e,a=null,o=null,l=Pt,d=r>0?65536:0,p=!1;let g=(_,y=!0)=>{p=!0,E(y,_)},E=(_,y)=>{if(l===(l=_))return;let C=!1;if(ge&&n!==-1){if(r===0){let P=i.data;P===va?n=0:P===is?n=1/0:(n=parseInt(P.substring(1)),n!==n&&(n=l?1/0:-1))}let k=n>r;!!l===k&&(i=oo(),wt(i),$r(!1),C=!0,n=-1)}l?(a?ya(a):y&&(a=nr(()=>y(i))),o&&Ln(o,()=>{o=null})):(o?ya(o):y&&(o=nr(()=>y(i,[r+1,n]))),a&&Ln(a,()=>{a=null})),C&&$r(!0)};Ir(()=>{p=!1,t(g),p||E(null,null)},d),ge&&(i=De)}var tE=v(()=>{Nt();Et();He();bt()});var rE=v(()=>{bt();He();us();Ot();Et()});var nE=v(()=>{He();Et();Gr()});function tc(e,t){return t}function BI(e,t,r,n){for(var i=[],a=t.length,o=0;o0&&i.length===0&&r!==null;if(l){var d=r.parentNode;qu(d),d.append(r),n.clear(),Aa(e,t[0].prev,t[a-1].next)}Bp(i,()=>{for(var p=0;p{var y=r();return fn(y)?y:y==null?[]:Lu(y)});Ir(()=>{var y=q(_),C=y.length;if(E&&C===0)return;E=C===0;let k=!1;if(ge){var P=o.data===is;P!==(C===0)&&(o=oo(),wt(o),$r(!1),k=!0)}if(ge){for(var N=null,L,H=0;H0&&wt(oo())}ge||$I(y,l,o,i,t,n,r),a!==null&&(C===0?g?ya(g):g=nr(()=>a(o)):g!==null&&Ln(g,()=>{g=null})),k&&$r(!0),q(_)}),ge&&(o=De)}function $I(e,t,r,n,i,a,o){var l=(i&8)!==0,d=(i&3)!==0,p=e.length,g=t.items,E=t.first,_=E,y,C=null,k,P=[],N=[],L,H,R,B;if(l)for(B=0;B0){var Dt=i&4&&p===0?r:null;if(l){for(B=0;B{if(k!==void 0)for(R of k)R.a?.apply()}),Oe.first=t.first&&t.first.e,Oe.last=C&&C.e}function HI(e,t,r,n){n&1&&no(e.v,t),n&2?no(e.i,r):e.i=r}function sE(e,t,r,n,i,a,o,l,d,p){var g=ec,E=(d&1)!==0,_=(d&16)===0,y=E?_?_i(i):Mt(i):i,C=d&2?Mt(o):o;se&&E&&(y.debug=()=>{var P=typeof C=="number"?o:C.v;p()[P]});var k={i:C,v:y,k:a,a:null,e:null,prev:r,next:n};ec=k;try{return k.e=nr(()=>l(e,y,C,p),ge),k.e.prev=r&&r.e,k.e.next=n&&n.e,r===null?t.first=k:(r.next=k,r.e.next=k.e),n!==null&&(n.prev=k,n.e.prev=k.e),k}finally{ec=g}}function iE(e,t,r){for(var n=e.next?e.next.e.nodes_start:r,i=t?t.e.nodes_start:r,a=e.e.nodes_start;a!==n;){var o=fr(a);i.before(a),a=o}}function Aa(e,t,r){t===null?e.first=r:(t.next=r,t.e.next=r&&r.e),r!==null&&(r.prev=t,r.e.prev=t&&t.e)}var ec,ff=v(()=>{bt();Et();Gr();He();yr();it();Nt();On();Ge();mt();hs();ec=null});function UI(e,t,r){if(!t||t===Vb(String(r??"")))return;let n,i=e.__svelte_meta?.loc;i?n=`near ${i.file}:${i.line}:${i.column}`:Xr?.[Ht]&&(n=`in ${Xr[Ht]}`),vb($p(n))}function Ts(e,t,r,n,i){var a=e,o="",l;Ir(()=>{if(o===(o=t()??"")){ge&&Vt();return}l!==void 0&&(lr(l),l=void 0),o!==""&&(l=nr(()=>{if(ge){for(var d=De.data,p=Vt(),g=p;p!==null&&(p.nodeType!==8||p.data!=="");)g=p,p=fr(p);if(p===null)throw ps(),Fi;se&&!i&&UI(p.parentNode,d,o),Zr(De,g),a=wt(p);return}var E=o+"";r?E=`${E}`:n&&(E=`${E}`);var _=Zu(E);if((r||n)&&(_=qt(_)),Zr(qt(_),_.lastChild),r||n)for(;qt(_);)a.before(qt(_));else a.before(_)}))})}var oE=v(()=>{bt();He();Et();cf();bs();Wr();_s();mt();Ot();Gr()});function zi(e,t,r,n,i){ge&&Vt();var a=t.$$slots?.[r],o=!1;a===!0&&(a=t[r==="default"?"children":r],o=!0),a===void 0?i!==null&&i(e):a(e,o?()=>n:n)}var uE=v(()=>{Et()});var Wp=v(()=>{Nt();He();Ot();Et();cf();bs();Wr();hn();mt();Gr();it()});function Gp(e,t,r){ge&&Vt();var n=e,i,a;Ir(()=>{i!==(i=t())&&(a&&(Ln(a),a=null),i&&(a=nr(()=>r(n,i))))},65536),ge&&(n=De)}var cE=v(()=>{Nt();He();Et()});var lE=v(()=>{bt();Et();Gr();He();vs();ff();Ge();Ot();mt();Nt();bs();_s()});var fE=v(()=>{mt();On();Hp()});function wa(e,t,r){Gt(()=>{var n=at(()=>t(e,r?.())||{});if(r&&n?.update){var i=!1,a={};zt(()=>{var o=r();vt(o),i&&Js(a,o)&&(a=o,n.update(o))}),i=!0}if(n?.destroy)return()=>n.destroy()})}var dE=v(()=>{He();us();Ge()});var hE=v(()=>{});function pE(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var i=e.length;for(t=0;t{});function xs(e){return typeof e=="object"?mE(e):e??""}function EE(e,t,r){var n=e==null?"":""+e;if(t&&(n=n?n+" "+t:t),r){for(var i in r)if(r[i])n=n?n+" "+i:i;else if(n.length)for(var a=i.length,o=0;(o=n.indexOf(i,o))>=0;){var l=o+a;(o===0||_E.includes(n[o-1]))&&(l===n.length||_E.includes(n[l]))?n=(o===0?"":n.substring(0,o))+n.substring(l+1):o=l}}return n===""?null:n}function bE(e,t=!1){var r=t?" !important;":";",n="";for(var i in e){var a=e[i];a!=null&&a!==""&&(n+=" "+i+": "+a+r)}return n}function Qp(e){return e[0]!=="-"||e[1]!=="-"?e.toLowerCase():e}function vE(e,t){if(t){var r="",n,i;if(Array.isArray(t)?(n=t[0],i=t[1]):n=t,e){e=String(e).replaceAll(/\s*\/\*.*?\*\/\s*/g,"").trim();var a=!1,o=0,l=!1,d=[];n&&d.push(...Object.keys(n).map(Qp)),i&&d.push(...Object.keys(i).map(Qp));var p=0,g=-1;let k=e.length;for(var E=0;E{hE();gE();_E=[...` -\r\f\xA0\v\uFEFF`]});function Yi(e,t,r,n,i,a){var o=e.__className;if(ge||o!==r){var l=EE(r,n,a);(!ge||l!==e.getAttribute("class"))&&(l==null?e.removeAttribute("class"):t?e.className=l:e.setAttribute("class",l)),e.__className=r}else if(a&&i!==a)for(var d in a){var p=!!a[d];(i==null||p!==!!i[d])&&e.classList.toggle(d,p)}return a}var Xp=v(()=>{nc();Et()});function Zp(e,t={},r,n){for(var i in r){var a=r[i];t[i]!==a&&(r[i]==null?e.style.removeProperty(i):e.style.setProperty(i,a,n))}}function ic(e,t,r,n){var i=e.__style;if(ge||i!==t){var a=vE(t,n);(!ge||a!==e.getAttribute("style"))&&(a==null?e.removeAttribute("style"):e.style.cssText=a),e.__style=t}else n&&(Array.isArray(n)?(Zp(e,r?.[0],n[0]),Zp(e,r?.[1],n[1],"important")):Zp(e,r,n));return n}var Jp=v(()=>{nc();Et()});function tm(e){if(ge){var t=!1,r=()=>{if(!t){if(t=!0,e.hasAttribute("value")){var n=e.value;Ki(e,"value",null),e.value=n}if(e.hasAttribute("checked")){var i=e.checked;Ki(e,"checked",null),e.checked=i}}};e.__on_r=r,eb(r),of()}}function Ki(e,t,r,n){var i=GI(e);if(ge&&(i[t]=e.getAttribute(t),t==="src"||t==="srcset"||t==="href"&&e.nodeName==="LINK")){n||XI(e,t,r??"");return}i[t]!==(i[t]=r)&&(t==="loading"&&(e[W_]=r),r==null?e.removeAttribute(t):typeof r!="string"&&QI(e).includes(t)?e[t]=r:e.setAttribute(t,r))}function GI(e){return e.__attributes??={[jI]:e.nodeName.includes("-"),[WI]:e.namespaceURI===q_}}function QI(e){var t=TE.get(e.nodeName);if(t)return t;TE.set(e.nodeName,t=[]);for(var r,n=e,i=Element.prototype;i!==n;){r=Yl(n);for(var a in r)r[a].set&&t.push(a);n=Ta(n)}return t}function XI(e,t,r){se&&(t==="srcset"&&ZI(e,r)||em(e.getAttribute(t)??"",r)||Eb(t,e.outerHTML.replace(e.innerHTML,e.innerHTML&&"..."),String(r)))}function em(e,t){return e===t?!0:new URL(e,document.baseURI).href===new URL(t,document.baseURI).href}function xE(e){return e.split(",").map(t=>t.trim().split(" ").filter(Boolean))}function ZI(e,t){var r=xE(e.srcset),n=xE(t);return n.length===r.length&&n.every(([i,a],o)=>a===r[o][1]&&(em(r[o][0],i)||em(i,r[o][0])))}var YI,KI,jI,WI,TE,yE=v(()=>{mt();Et();it();Xu();uf();Wr();Nt();On();_s();Ge();nc();Xp();Jp();bt();YI=Symbol("class"),KI=Symbol("style"),jI=Symbol("is custom element"),WI=Symbol("is html");TE=new Map});var JI,ei,rm=v(()=>{it();mt();JI=zl?()=>performance.now():()=>Date.now(),ei={tick:e=>(zl?requestAnimationFrame:Ut)(e),now:()=>JI(),tasks:new Set}});function AE(){let e=ei.now();ei.tasks.forEach(t=>{t.c(e)||(ei.tasks.delete(t),t.f())}),ei.tasks.size!==0&&ei.tick(AE)}function wE(e){let t;return ei.tasks.size===0&&ei.tick(AE),{promise:new Promise(r=>{ei.tasks.add(t={c:e,f:r})}),abort(){ei.tasks.delete(t)}}}var SE=v(()=>{rm()});function df(e,t){go(()=>{e.dispatchEvent(new CustomEvent(t))})}function n3(e){if(e==="float")return"cssFloat";if(e==="offset")return"cssOffset";if(e.startsWith("--"))return e;let t=e.split("-");return t.length===1?t[0]:t[0]+t.slice(1).map(r=>r[0].toUpperCase()+r.slice(1)).join("")}function CE(e){let t={},r=e.split(";");for(let n of r){let[i,a]=n.split(":");if(!i||a===void 0)break;let o=n3(i.trim());t[o]=a.trim()}return t}function im(e,t,r,n){var i=(e&1)!==0,a=(e&2)!==0,o=i&&a,l=(e&4)!==0,d=o?"both":i?"in":"out",p,g=t.inert,E=t.style.overflow,_,y;function C(){var H=$e,R=Oe;tr(null),Wt(null);try{return p??=r()(t,n?.()??{},{direction:d})}finally{tr(H),Wt(R)}}var k={is_global:l,in(){if(t.inert=g,!i){y?.abort(),y?.reset?.();return}a||_?.abort(),df(t,"introstart"),_=nm(t,C(),y,1,()=>{df(t,"introend"),_?.abort(),_=p=void 0,t.style.overflow=E})},out(H){if(!a){H?.(),p=void 0;return}t.inert=!0,df(t,"outrostart"),y=nm(t,C(),_,0,()=>{df(t,"outroend"),H?.()})},stop:()=>{_?.abort(),y?.abort()}},P=Oe;if((P.transitions??=[]).push(k),i&&lf){var N=l;if(!N){for(var L=P.parent;L&&L.f&65536;)for(;(L=L.parent)&&!(L.f&16););N=!L||(L.f&32768)!==0}N&&Gt(()=>{at(()=>k.in())})}}function nm(e,t,r,n,i){var a=n===1;if(xa(t)){var o,l=!1;return dn(()=>{if(!l){var P=t({direction:a?"in":"out"});o=nm(e,P,r,n,i)}}),{abort:()=>{l=!0,o?.abort()},deactivate:()=>o.deactivate(),reset:()=>o.reset(),t:()=>o.t()}}if(r?.deactivate(),!t?.duration)return i(),{abort:Ut,deactivate:Ut,reset:Ut,t:()=>n};let{delay:d=0,css:p,tick:g,easing:E=i3}=t;var _=[];if(a&&r===void 0&&(g&&g(0,1),p)){var y=CE(p(0,1));_.push(y,y)}var C=()=>1-n,k=e.animate(_,{duration:d});return k.onfinish=()=>{var P=r?.t()??1-n;r?.abort();var N=n-P,L=t.duration*Math.abs(N),H=[];if(L>0){var R=!1;if(p)for(var B=Math.ceil(L/16.666666666666668),V=0;V<=B;V+=1){var X=P+N*E(V/B),ce=CE(p(X,1-X));H.push(ce),R||=ce.overflow==="hidden"}R&&(e.style.overflow="hidden"),C=()=>{var ve=k.currentTime;return P+N*E(ve/L)},g&&wE(()=>{if(k.playState!=="running")return!1;var ve=C();return g(ve,1-ve),!0})}k=e.animate(H,{duration:L,fill:"forwards"}),k.onfinish=()=>{C=()=>n,g?.(n,1-n),i()}},{abort:()=>{k&&(k.cancel(),k.effect=null,k.onfinish=Ut)},deactivate:()=>{i=Ut},reset:()=>{n===0&&g?.(1,0)},t:()=>C()}}var i3,IE=v(()=>{it();He();Ge();SE();vs();ff();bt();Nt();On();Ti();i3=e=>e});var NE=v(()=>{Ti()});function om(e,t,r=t){var n=bi();Up(e,"input",i=>{se&&e.type==="checkbox"&&_p();var a=i?e.defaultValue:e.value;if(a=am(e)?sm(a):a,r(a),n&&a!==(a=t())){var o=e.selectionStart,l=e.selectionEnd;e.value=a??"",l!==null&&(e.selectionStart=o,e.selectionEnd=Math.min(l,e.value.length))}}),(ge&&e.defaultValue!==e.value||at(t)==null&&e.value)&&r(am(e)?sm(e.value):e.value),zt(()=>{se&&e.type==="checkbox"&&_p();var i=t();am(e)&&i===sm(e.value)||e.type==="date"&&!i&&!e.value||i!==e.value&&(e.value=i??"")})}function am(e){var t=e.type;return t==="number"||t==="range"}function sm(e){return e===""?null:+e}var OE=v(()=>{mt();He();Ti();hn();uo();On();Et();Ge();Ot()});var DE=v(()=>{Et();He();Ti()});var kE=v(()=>{Ti()});function um(e,t,r){var n=Kr(e,t);n&&n.set&&(e[t]=r,Cr(()=>{e[t]=null}))}var RE=v(()=>{He();it()});var LE=v(()=>{He();Ti();Ge();uo()});var Sa,vo,ac,pf,PE,lm,cm,ME=v(()=>{He();Ge();lm=class{constructor(t){ku(this,pf);ku(this,Sa,new WeakMap);ku(this,vo,void 0);ku(this,ac,void 0);hp(this,ac,t)}observe(t,r){var n=Mi(this,Sa).get(t)||new Set;return n.add(r),Mi(this,Sa).set(t,n),$_(this,pf,PE).call(this).observe(t,Mi(this,ac)),()=>{var i=Mi(this,Sa).get(t);i.delete(r),i.size===0&&(Mi(this,Sa).delete(t),Mi(this,vo).unobserve(t))}}},cm=lm;Sa=new WeakMap,vo=new WeakMap,ac=new WeakMap,pf=new WeakSet,PE=function(){return Mi(this,vo)??hp(this,vo,new ResizeObserver(t=>{for(var r of t){lm.entries.set(r.target,r);for(var n of Mi(this,Sa).get(r.target)||[])n(r)}}))},ql(cm,"entries",new WeakMap)});function FE(e,t){return e===t||e?.[xr]===t}function ys(e={},t,r,n){return Gt(()=>{var i,a;return zt(()=>{i=a,a=n?.()||[],at(()=>{e!==r(...a)&&(t(e,...a),i&&FE(r(...i),e)&&t(null,...i))})}),()=>{dn(()=>{a&&FE(r(...a),e)&&t(null,...a)})}}),e}var BE=v(()=>{Nt();He();Ge();On()});var $E=v(()=>{He();Ti()});var HE=v(()=>{He();Ti()});var fm=v(()=>{it();He();Xu()});function En(e=!1){let t=Pe,r=t.l.u;if(!r)return;let n=()=>vt(t.s);if(e){let i=0,a={},o=kn(()=>{let l=!1,d=t.s;for(let p in d)d[p]!==a[p]&&(a[p]=d[p],l=!0);return l&&i++,i});n=()=>q(o)}r.b.length&&ho(()=>{UE(t,n),os(r.b)}),vi(()=>{let i=at(()=>r.m.map(X_));return()=>{for(let a of i)typeof a=="function"&&a()}}),r.a.length&&vi(()=>{UE(t,n),os(r.a)})}function UE(e,t){if(e.l.s)for(let r of e.l.s)q(r);t()}var VE=v(()=>{it();Ot();hs();He();Ge()});function Jr(e,t){var r=e.$$events?.[t.type],n=fn(r)?r.slice():r==null?[]:[r];for(var i of n)i.call(this,t)}var qE=v(()=>{yr();Ge();it()});function As(e){Pe===null&&po("onMount"),mi&&Pe.l!==null?o3(Pe).m.push(e):vi(()=>{let t=at(e);if(typeof t=="function")return t})}function mf(e){Pe===null&&po("onDestroy"),As(()=>()=>at(e))}function s3(e,t,{bubbles:r=!1,cancelable:n=!1}={}){return new CustomEvent(e,{detail:t,bubbles:r,cancelable:n})}function zE(){let e=Pe;return e===null&&po("createEventDispatcher"),(t,r,n)=>{let i=e.s.$$events?.[t];if(i){let a=fn(i)?i.slice():[i],o=s3(t,r,n);for(let l of a)l.call(e.x,o);return!o.defaultPrevented}return!0}}function o3(e){var t=e.l;return t.u??={a:[],b:[],m:[]}}var ws=v(()=>{Ge();it();Pn();hn();mo();Bi();Ot();mt();Ge();Ot();vs();Ge();Wp();if(se){let e=function(t){if(!(t in globalThis)){let r;Object.defineProperty(globalThis,t,{configurable:!0,get:()=>{if(r!==void 0)return r;ub(t)},set:n=>{r=n}})}};e("$state"),e("$effect"),e("$derived"),e("$inspect"),e("$props"),e("$bindable")}});function gf(e,t,r){if(e==null)return t(void 0),r&&r(void 0),Ut;let n=at(()=>e.subscribe(t,r));return n.unsubscribe?()=>n.unsubscribe():n}var dm=v(()=>{ws();it()});function xo(e,t=Ut){let r=null,n=new Set;function i(l){if(Js(e,l)&&(e=l,r)){let d=!To.length;for(let p of n)p[1](),To.push(p,e);if(d){for(let p=0;p{n.delete(p),n.size===0&&r&&(r(),r=null)}}return{set:i,update:a,subscribe:o}}function _f(e){let t;return gf(e,r=>t=r)(),t}var To,bf=v(()=>{it();us();dm();To=[]});function sc(e,t,r){let n=r[t]??={store:null,source:_i(void 0),unsubscribe:Ut};if(n.store!==e&&!(hm in r))if(n.unsubscribe(),n.store=e??null,e==null)n.source.v=void 0,n.unsubscribe=Ut;else{var i=!0;n.unsubscribe=gf(e,a=>{i?n.source.v=a:oe(n.source,a)}),i=!1}return e&&hm in r?_f(e):q(n.source)}function oc(){let e={};function t(){Cr(()=>{for(var r in e)e[r].unsubscribe();Kt(e,hm,{enumerable:!1,value:!0})})}return[e,t]}function pm(e){var t=Ef;try{return Ef=!1,[e(),Ef]}finally{Ef=t}}var Ef,hm,vf=v(()=>{dm();bf();it();Ge();He();yr();Ef=!1,hm=Symbol()});function mm(...e){return new Proxy({props:e},p3)}function YE(e){return e.ctx?.d??!1}function ze(e,t,r,n){var i=(r&1)!==0,a=!mi||(r&2)!==0,o=(r&8)!==0,l=(r&16)!==0,d=!1,p;o?[p,d]=pm(()=>e[t]):p=e[t];var g=xr in e||Ru in e,E=o&&(Kr(e,t)?.set??(g&&t in e&&(X=>e[t]=X)))||void 0,_=n,y=!0,C=!1,k=()=>(C=!0,y&&(y=!1,l?_=at(n):_=n),_);p===void 0&&n!==void 0&&(E&&a&&ob(t),p=k(),E&&E(p));var P;if(a)P=()=>{var X=e[t];return X===void 0?k():(y=!0,C=!1,X)};else{var N=(i?kn:Br)(()=>e[t]);N.f|=131072,P=()=>{var X=q(N);return X!==void 0&&(_=void 0),X===void 0?_:X}}if(!(r&4))return P;if(E){var L=e.$$legacy;return function(X,ce){return arguments.length>0?((!a||!ce||L||d)&&E(ce?P():X),X):P()}}var H=!1,R=!1,B=_i(p),V=kn(()=>{var X=P(),ce=q(B);return H?(H=!1,R=!0,ce):(R=!1,B.v=X)});return o&&q(V),i||(V.equals=eo),function(X,ce){if($u!==null&&(H=R,P(),q(B)),arguments.length>0){let ve=ce?q(V):a&&o?er(X):X;if(!V.equals(ve)){if(H=!0,oe(B,ve),C&&_!==void 0&&(_=ve),YE(V))return X;at(()=>q(V))}return X}return YE(V)?V.v:q(V)}}var p3,KE=v(()=>{mt();bt();it();yr();hs();Ge();us();hn();Nt();uo();vf();Bi();p3={get(e,t){let r=e.props.length;for(;r--;){let n=e.props[r];if(xa(n)&&(n=n()),typeof n=="object"&&n!==null&&t in n)return n[t]}},set(e,t,r){let n=e.props.length;for(;n--;){let i=e.props[n];xa(i)&&(i=i());let a=Kr(i,t);if(a&&a.set)return a.set(r),!0}return!1},getOwnPropertyDescriptor(e,t){let r=e.props.length;for(;r--;){let n=e.props[r];if(xa(n)&&(n=n()),typeof n=="object"&&n!==null&&t in n){let i=Kr(n,t);return i&&!i.configurable&&(i.configurable=!0),i}}},has(e,t){if(t===xr||t===Ru)return!1;for(let r of e.props)if(xa(r)&&(r=r()),r!=null&&t in r)return!0;return!1},ownKeys(e){let t=[];for(let r of e.props){xa(r)&&(r=r());for(let n in r)t.includes(n)||t.push(n)}return t}}});var jE=v(()=>{Nt();Ot();He();Ge();Et();On()});var WE=v(()=>{Ot();it();hn();bt();He();Wr();vf()});function GE(e){return new gm(e)}var gm,QE=v(()=>{Nt();He();yr();vs();Ge();mo();it();Wr();mt();bt();Ot();fm();gm=class{#e;#t;constructor(t){var r=new Map,n=(a,o)=>{var l=_i(o);return r.set(a,l),l};let i=new Proxy({...t.props||{},$$events:{}},{get(a,o){return q(r.get(o)??n(o,Reflect.get(a,o)))},has(a,o){return o===Ru?!0:(q(r.get(o)??n(o,Reflect.get(a,o))),Reflect.has(a,o))},set(a,o,l){return oe(r.get(o)??n(o,l),l),Reflect.set(a,o,l)}});this.#t=(t.hydrate?Yp:Es)(t.component,{target:t.target,anchor:t.anchor,props:i,context:t.context,intro:t.intro??!1,recover:t.recover}),(!t?.props?.$$host||t.sync===!1)&&fo(),this.#e=i.$$events;for(let a of Object.keys(this.#t))a==="$set"||a==="$destroy"||a==="$on"||Kt(this,a,{get(){return this.#t[a]},set(o){this.#t[a]=o},enumerable:!0});this.#t.$set=a=>{Object.assign(i,a)},this.#t.$destroy=()=>{Eo(this.#t)}}$set(t){this.#t.$set(t)}$on(t,r){this.#e[t]=this.#e[t]||[];let n=(...i)=>r.call(this,...i);return this.#e[t].push(n),()=>{this.#e[t]=this.#e[t].filter(i=>i!==n)}}$destroy(){this.#t.$destroy()}}});function _m(e,t,r,n){let i=r[e]?.type;if(t=i==="Boolean"&&typeof t!="boolean"?t!=null:t,!n||!r[e])return t;if(n==="toAttribute")switch(i){case"Object":case"Array":return t==null?null:JSON.stringify(t);case"Boolean":return t?"":null;case"Number":return t??null;default:return t}else switch(i){case"Object":case"Array":return t&&JSON.parse(t);case"Boolean":return t;case"Number":return t!=null?+t:t;default:return t}}function x3(e){let t={};return e.childNodes.forEach(r=>{t[r.slot||"default"]=!0}),t}var T3,XE=v(()=>{QE();He();bs();it();typeof HTMLElement=="function"&&(T3=class extends HTMLElement{$$ctor;$$s;$$c;$$cn=!1;$$d={};$$r=!1;$$p_d={};$$l={};$$l_u=new Map;$$me;constructor(e,t,r){super(),this.$$ctor=e,this.$$s=t,r&&this.attachShadow({mode:"open"})}addEventListener(e,t,r){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(t),this.$$c){let n=this.$$c.$on(e,t);this.$$l_u.set(t,n)}super.addEventListener(e,t,r)}removeEventListener(e,t,r){if(super.removeEventListener(e,t,r),this.$$c){let n=this.$$l_u.get(t);n&&(n(),this.$$l_u.delete(t))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(n){return i=>{let a=document.createElement("slot");n!=="default"&&(a.name=n),we(i,a)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let t={},r=x3(this);for(let n of this.$$s)n in r&&(n==="default"&&!this.$$d.children?(this.$$d.children=e(n),t.default=!0):t[n]=e(n));for(let n of this.attributes){let i=this.$$g_p(n.name);i in this.$$d||(this.$$d[i]=_m(i,n.value,this.$$p_d,"toProp"))}for(let n in this.$$p_d)!(n in this.$$d)&&this[n]!==void 0&&(this.$$d[n]=this[n],delete this[n]);this.$$c=GE({component:this.$$ctor,target:this.shadowRoot||this,props:{...this.$$d,$$slots:t,$$host:this}}),this.$$me=af(()=>{zt(()=>{this.$$r=!0;for(let n of pp(this.$$c)){if(!this.$$p_d[n]?.reflect)continue;this.$$d[n]=this.$$c[n];let i=_m(n,this.$$d[n],this.$$p_d,"toAttribute");i==null?this.removeAttribute(this.$$p_d[n].attribute||n):this.setAttribute(this.$$p_d[n].attribute||n,i)}this.$$r=!1})});for(let n in this.$$l)for(let i of this.$$l[n]){let a=this.$$c.$on(n,i);this.$$l_u.set(i,a)}this.$$l={}}}attributeChangedCallback(e,t,r){this.$$r||(e=this.$$g_p(e),this.$$d[e]=_m(e,r,this.$$p_d,"toProp"),this.$$c?.$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 pp(this.$$p_d).find(t=>this.$$p_d[t].attribute===e||!this.$$p_d[t].attribute&&t.toLowerCase()===e)||e}})});var ZE=v(()=>{_s();bp();mo();mo()});var JE=v(()=>{Nt();Fu();Wr();Ge()});var Pn=v(()=>{bt();Ot();zb();Hp();Yb();Xb();Uu();Zb();to();Jb();eE();tE();rE();nE();ff();oE();uE();Wp();cE();lE();qp();fE();dE();yE();Xp();Xu();uf();Jp();IE();NE();OE();DE();kE();RE();LE();ME();BE();$E();HE();Et();fm();VE();qE();bs();hs();He();yr();KE();vf();jE();vs();Ge();WE();rm();uo();XE();Gr();nc();Fu();it();ZE();Ip();JE()});var yi=v(()=>{Bi();hb()});var Tf,ev=v(()=>{Tf=class{constructor(){this.handlers=new Map;this.disabled=[]}on(t,r,n){if(t.includes("@")||r.includes("@"))throw new Error("Invalid context/event name - Cannot contain @");this.handlers.set(`${t}@${r}`,n)}off(t,r){if(r)this.handlers.delete(`${t}@${r}`);else for(let[n]of this.handlers.entries())n.startsWith(`${t}@`)&&this.handlers.delete(n)}disable(t){this.enable(t),this.disabled.push(t)}enable(t){this.disabled=this.disabled.filter(r=>r!==t)}emit(t,...r){let n=[...this.handlers.entries()].filter(([i,a])=>!this.disabled.includes(i.split("@")[0]));for(let[i,a]of n)i.endsWith(`@${t}`)&&a(...r)}}});var tv=v(()=>{yr()});var rv=v(()=>{Ge();He();yr();tv()});var bm=v(()=>{He();bf();rv();bf()});function Em(e){av=e}function vm(){return av}var nv,iv,uc,Ss,Me,xf,Ca,av,A3,yf,sv,en=v(()=>{ev();bm();nv=/[\u4e00-\u9fa5]/,iv=100,uc=300,Ss="omnisearch-disabled",Me=new Tf,xf={ToggleExcerpts:"toggle-excerpts"},Ca=xo(0),av=!1;A3=/[|\t\n\r\^"= -#%-*,.`\/<>:;?@[-\]_{}\u00A0\u00A1\u00A7\u00AB\u00B6\u00B7\u00BB\u00BF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u1680\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2000-\u200A\u2010-\u2029\u202F-\u2043\u2045-\u2051\u2053-\u205F\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4F\u3000-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]/.toString().slice(1,-1),yf=new RegExp(`${A3}+`,"u"),sv=/[|\[\]\(\)<>\{\} \t\n\r]/u});var ov=Pi((cc,Tm)=>{(function(e,t){if(typeof cc=="object"&&typeof Tm=="object")Tm.exports=t();else if(typeof define=="function"&&define.amd)define([],t);else{var r=t();for(var n in r)(typeof cc=="object"?cc:e)[n]=r[n]}})(typeof self<"u"?self:cc,function(){return function(e){var t={};function r(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,r),i.l=!0,i.exports}return r.m=e,r.c=t,r.d=function(n,i,a){r.o(n,i)||Object.defineProperty(n,i,{enumerable:!0,get:a})},r.r=function(n){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(n,"__esModule",{value:!0})},r.t=function(n,i){if(1&i&&(n=r(n)),8&i||4&i&&typeof n=="object"&&n&&n.__esModule)return n;var a=Object.create(null);if(r.r(a),Object.defineProperty(a,"default",{enumerable:!0,value:n}),2&i&&typeof n!="string")for(var o in n)r.d(a,o,function(l){return n[l]}.bind(null,o));return a},r.n=function(n){var i=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(i,"a",i),i},r.o=function(n,i){return Object.prototype.hasOwnProperty.call(n,i)},r.p="",r(r.s=0)}([function(e,t,r){"use strict";r.r(t),r.d(t,"md5",function(){return k});var n="0123456789abcdef".split(""),i=function(P){for(var N="",L=0;L<4;L++)N+=n[P>>8*L+4&15]+n[P>>8*L&15];return N},a=function(P){for(var N=P.length,L=0;L>>32-ce,ve)}(N=function(X,ce,ve,Re){return ce=o(o(ce,X),o(ve,Re))}(P,N,H,B),R,L)},d=function(P,N,L,H,R,B,V,X){return l(L&H|~L&R,N,L,B,V,X,P)},p=function(P,N,L,H,R,B,V,X){return l(L&R|H&~R,N,L,B,V,X,P)},g=function(P,N,L,H,R,B,V,X){return l(L^H^R,N,L,B,V,X,P)},E=function(P,N,L,H,R,B,V,X){return l(H^(L|~R),N,L,B,V,X,P)},_=function(P,N,L){L===void 0&&(L=o);var H=P[0],R=P[1],B=P[2],V=P[3],X=d.bind(null,L);H=X(H,R,B,V,N[0],7,-680876936),V=X(V,H,R,B,N[1],12,-389564586),B=X(B,V,H,R,N[2],17,606105819),R=X(R,B,V,H,N[3],22,-1044525330),H=X(H,R,B,V,N[4],7,-176418897),V=X(V,H,R,B,N[5],12,1200080426),B=X(B,V,H,R,N[6],17,-1473231341),R=X(R,B,V,H,N[7],22,-45705983),H=X(H,R,B,V,N[8],7,1770035416),V=X(V,H,R,B,N[9],12,-1958414417),B=X(B,V,H,R,N[10],17,-42063),R=X(R,B,V,H,N[11],22,-1990404162),H=X(H,R,B,V,N[12],7,1804603682),V=X(V,H,R,B,N[13],12,-40341101),B=X(B,V,H,R,N[14],17,-1502002290),R=X(R,B,V,H,N[15],22,1236535329);var ce=p.bind(null,L);H=ce(H,R,B,V,N[1],5,-165796510),V=ce(V,H,R,B,N[6],9,-1069501632),B=ce(B,V,H,R,N[11],14,643717713),R=ce(R,B,V,H,N[0],20,-373897302),H=ce(H,R,B,V,N[5],5,-701558691),V=ce(V,H,R,B,N[10],9,38016083),B=ce(B,V,H,R,N[15],14,-660478335),R=ce(R,B,V,H,N[4],20,-405537848),H=ce(H,R,B,V,N[9],5,568446438),V=ce(V,H,R,B,N[14],9,-1019803690),B=ce(B,V,H,R,N[3],14,-187363961),R=ce(R,B,V,H,N[8],20,1163531501),H=ce(H,R,B,V,N[13],5,-1444681467),V=ce(V,H,R,B,N[2],9,-51403784),B=ce(B,V,H,R,N[7],14,1735328473),R=ce(R,B,V,H,N[12],20,-1926607734);var ve=g.bind(null,L);H=ve(H,R,B,V,N[5],4,-378558),V=ve(V,H,R,B,N[8],11,-2022574463),B=ve(B,V,H,R,N[11],16,1839030562),R=ve(R,B,V,H,N[14],23,-35309556),H=ve(H,R,B,V,N[1],4,-1530992060),V=ve(V,H,R,B,N[4],11,1272893353),B=ve(B,V,H,R,N[7],16,-155497632),R=ve(R,B,V,H,N[10],23,-1094730640),H=ve(H,R,B,V,N[13],4,681279174),V=ve(V,H,R,B,N[0],11,-358537222),B=ve(B,V,H,R,N[3],16,-722521979),R=ve(R,B,V,H,N[6],23,76029189),H=ve(H,R,B,V,N[9],4,-640364487),V=ve(V,H,R,B,N[12],11,-421815835),B=ve(B,V,H,R,N[15],16,530742520),R=ve(R,B,V,H,N[2],23,-995338651);var Re=E.bind(null,L);H=Re(H,R,B,V,N[0],6,-198630844),V=Re(V,H,R,B,N[7],10,1126891415),B=Re(B,V,H,R,N[14],15,-1416354905),R=Re(R,B,V,H,N[5],21,-57434055),H=Re(H,R,B,V,N[12],6,1700485571),V=Re(V,H,R,B,N[3],10,-1894986606),B=Re(B,V,H,R,N[10],15,-1051523),R=Re(R,B,V,H,N[1],21,-2054922799),H=Re(H,R,B,V,N[8],6,1873313359),V=Re(V,H,R,B,N[15],10,-30611744),B=Re(B,V,H,R,N[6],15,-1560198380),R=Re(R,B,V,H,N[13],21,1309151649),H=Re(H,R,B,V,N[4],6,-145523070),V=Re(V,H,R,B,N[11],10,-1120210379),B=Re(B,V,H,R,N[2],15,718787259),R=Re(R,B,V,H,N[9],21,-343485551),P[0]=L(H,P[0]),P[1]=L(R,P[1]),P[2]=L(B,P[2]),P[3]=L(V,P[3])},y=function(P){for(var N=[],L=0;L<64;L+=4)N[L>>2]=P.charCodeAt(L)+(P.charCodeAt(L+1)<<8)+(P.charCodeAt(L+2)<<16)+(P.charCodeAt(L+3)<<24);return N},C=function(P,N){var L,H=P.length,R=[1732584193,-271733879,-1732584194,271733878];for(L=64;L<=H;L+=64)_(R,y(P.substring(L-64,L)),N);var B=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],V=(P=P.substring(L-64)).length;for(L=0;L>2]|=P.charCodeAt(L)<<(L%4<<3);if(B[L>>2]|=128<<(L%4<<3),L>55)for(_(R,B,N),L=16;L--;)B[L]=0;return B[14]=8*H,_(R,B,N),R};function k(P){var N;return a(C("hello"))!=="5d41402abc4b2a76b9719d911017c592"&&(N=function(L,H){var R=(65535&L)+(65535&H);return(L>>16)+(H>>16)+(R>>16)<<16|65535&R}),a(C(P,N))}}])})});function lc(e){let t=e.split("/");return t.pop(),t.join("/")}function xm(e){return new Promise(t=>{setTimeout(t,e)})}function Af(e,t){return e.headings?.filter(r=>r.level===t).map(r=>r.heading)??[]}function wf(e,t){return(e+t)%t}function uv(e){return e.replace(/(\*|_)+(.+?)(\*|_)+/g,(t,r,n)=>n)}function cv(e){return e?.frontmatter?(0,ji.parseFrontMatterAliases)(e.frontmatter)??[]:[]}function lv(e){let t=e?(0,ji.getAllTags)(e)??[]:[];return t=[...new Set(t.reduce((r,n)=>[...r,...n.split("/").filter(i=>i).map(i=>i.startsWith("#")?i:`#${i}`),n],[]))],t}function Wi(e,t=!1){if(e==null)return"";if(t){e=e.replace(/([^\u0621-\u063A\u0641-\u064A\u0660-\u0669a-zA-Z 0-9])/g,"").replace(/(آ|إ|أ)/g,"\u0627").replace(/(ة)/g,"\u0647").replace(/(ئ|ؤ)/g,"\u0621").replace(/(ى)/g,"\u064A");for(let r=0;r<10;r++)e.replace(String.fromCharCode(1632+r),String.fromCharCode(48+r))}return e=e.replaceAll("`","[__omnisearch__backtick__]"),e=e.replaceAll("^","[__omnisearch__caret__]"),e=e.normalize("NFD").replace(N3,"").normalize("NFC"),e=e.replaceAll("[__omnisearch__backtick__]","`"),e=e.replaceAll("[__omnisearch__caret__]","^"),e}function vn(){return ji.Platform.isMacOS?"\u2318":"Ctrl"}function Sf(){return ji.Platform.isMacOS?"\u2325":"Alt"}function Mn(e){let t=Cs(e);return t==="png"||t==="jpg"||t==="jpeg"||t==="webp"||t==="gif"}function ti(e){return Cs(e)==="pdf"}function fv(e){let t=Cs(e);return t==="docx"||t==="xlsx"}function Ai(e){return e.endsWith(".canvas")}function fc(e){return e.endsWith(".excalidraw")}function dc(e){return e.endsWith(".loom")}function Cs(e){let t=e.split(".");return t[t.length-1]??""}function dv(e,t){let r=[],n=0,i=e.length;for(;nr):[]}function Am(e){return e.includes("-")?e.split("-").filter(t=>t):[]}function Ke(...e){pv(console.debug,...e)}function Gi(...e){pv(console.warn,...e)}function wm(e){hv=e}function pv(e,...t){hv&&e(...t)}var ji,w3,S3,C3,I3,N3,hv,hc,Nr=v(()=>{ji=require("obsidian");en();w3=require("crypto"),S3=ln(ov());C3=["\\u30FC","\\u309A","\\u3099"],I3=C3.join("|"),N3=new RegExp(`(?!${I3})\\p{Diacritic}`,"gu");hv=!1;hc=(()=>{let e=0,t=!1;return setTimeout(()=>{e>0&&--e},1e3),(r=!1)=>{(++e>=5||r)&&!t&&(t=!0,new ji.Notice("Omnisearch \u26A0\uFE0F There might be an issue with your cache. You should clean it in Omnisearch settings and restart Obsidian.",5e3))}})()});function mc(e,t){dr(t,!1);let r=ze(t,"initialValue",8,""),n=ze(t,"placeholder",8,""),i=ze(t,"plugin",8),a=!1,o=ft(""),l=ft(),d=zE();function p(N){oe(o,N)}function g(N){N&&!a&&!q(o)&&(a=!0,oe(o,N),E())}function E(N){Ei().then(async()=>(pc.Platform.isMobileApp&&await xm(200),q(l).focus(),Ei())).then(async()=>{pc.Platform.isMobileApp&&await xm(200),q(l).select()})}let _=(0,pc.debounce)(()=>{i().searchHistory.addToHistory(""),d("input",q(o))},300);Qt(()=>vt(r()),()=>{g(r())}),Jn(),En();var y=O3(),C=xe(y),k=xe(C);tm(k),ys(k,N=>oe(l,N),()=>q(l)),Gt(()=>om(k,()=>q(o),N=>oe(o,N))),Gt(()=>pr("compositionend",k,N=>Em(!1))),Gt(()=>pr("compositionstart",k,N=>Em(!0))),Gt(()=>pr("input",k,_)),wa(k,N=>E?.(N)),Te(C);var P=Ye(C,2);return zi(P,t,"default",{},null),Te(y),rr(()=>Ki(k,"placeholder",n())),we(e,y),um(t,"setInputValue",p),hr({setInputValue:p})}var pc,O3,Sm=v(()=>{Wn();yi();Pn();pc=require("obsidian");en();ws();Nr();O3=Le('
    ')});function gc(e,t){var r=D3(),n=xe(r);zi(n,t,"default",{},null),Te(r),pr("mousedown",r,i=>i.preventDefault()),we(e,r)}var D3,Cm=v(()=>{Wn();yi();Pn();D3=Le('
    ')});async function Cf(e,t,r=0,n=!1,i=!1){let a=!1;e.workspace.iterateAllLeaves(d=>{d.view instanceof Im.MarkdownView&&!n&&d.getViewState().state?.file===t.path&&d.getViewState()?.pinned&&(e.workspace.setActiveLeaf(d,{focus:!0}),a=!0)}),a||await e.workspace.openLinkText(t.path,"",i?"split":n);let o=e.workspace.getActiveViewOfType(Im.MarkdownView);if(!o)return;let l=o.editor.offsetToPos(r);o.editor.setCursor(l),o.editor.scrollIntoView({from:{line:l.line-10,ch:0},to:{line:l.line+10,ch:0}})}async function mv(e,t,r=!1){try{let n;switch(e.vault.getConfig("newFileLocation")){case"current":n=(e.workspace.getActiveFile()?.parent?.path??"")+"/";break;case"folder":n=e.vault.getConfig("newFileFolderPath")+"/";break;default:n="";break}await e.workspace.openLinkText(`${n}${t}.md`,"",r)}catch(n){throw n.message="OmniSearch - Could not create note: "+n.message,console.error(n),n}}function gv(e,t,r){return(r.links??[]).map(n=>{let i=Nm(n.link);return e.metadataCache.getFirstLinkpathDest(i,t.path)?"":n.link}).filter(n=>!!n)}function Nm(e){return e.split(/[\^#]+/)[0]}var Im,_c=v(()=>{Im=require("obsidian")});function ar(e){let t=new DocumentFragment;return t.createSpan({},r=>{r.innerHTML=e}),t}function If(e){return e.loadLocalStorage(Ss)==="1"}async function ke(e){await e.saveData(Or)}function Qi(){return!_v.Platform.isIosApp&&Or.useCache}var _v,yo,mr=v(()=>{_v=require("obsidian");en();Ao();yo='Needs a restart to fully take effect.'});var k3,Nf,Om=v(()=>{k3=typeof global=="object"&&global&&global.Object===Object&&global,Nf=k3});var R3,L3,Yt,ri=v(()=>{Om();R3=typeof self=="object"&&self&&self.Object===Object&&self,L3=Nf||R3||Function("return this")(),Yt=L3});var P3,Ur,wo=v(()=>{ri();P3=Yt.Symbol,Ur=P3});function B3(e){var t=M3.call(e,bc),r=e[bc];try{e[bc]=void 0;var n=!0}catch{}var i=F3.call(e);return n&&(t?e[bc]=r:delete e[bc]),i}var bv,M3,F3,bc,Ev,vv=v(()=>{wo();bv=Object.prototype,M3=bv.hasOwnProperty,F3=bv.toString,bc=Ur?Ur.toStringTag:void 0;Ev=B3});function U3(e){return H3.call(e)}var $3,H3,Tv,xv=v(()=>{$3=Object.prototype,H3=$3.toString;Tv=U3});function z3(e){return e==null?e===void 0?q3:V3:yv&&yv in Object(e)?Ev(e):Tv(e)}var V3,q3,yv,ni,So=v(()=>{wo();vv();xv();V3="[object Null]",q3="[object Undefined]",yv=Ur?Ur.toStringTag:void 0;ni=z3});function Y3(e){return e!=null&&typeof e=="object"}var ii,Co=v(()=>{ii=Y3});function j3(e){return typeof e=="symbol"||ii(e)&&ni(e)==K3}var K3,ai,Io=v(()=>{So();Co();K3="[object Symbol]";ai=j3});function W3(e,t){for(var r=-1,n=e==null?0:e.length,i=Array(n);++r{No=W3});var G3,Ft,si=v(()=>{G3=Array.isArray,Ft=G3});function Sv(e){if(typeof e=="string")return e;if(Ft(e))return No(e,Sv)+"";if(ai(e))return wv?wv.call(e):"";var t=e+"";return t=="0"&&1/e==-Q3?"-0":t}var Q3,Av,wv,Cv,Iv=v(()=>{wo();Dm();si();Io();Q3=1/0,Av=Ur?Ur.prototype:void 0,wv=Av?Av.toString:void 0;Cv=Sv});function Z3(e){for(var t=e.length;t--&&X3.test(e.charAt(t)););return t}var X3,Nv,Ov=v(()=>{X3=/\s/;Nv=Z3});function eN(e){return e&&e.slice(0,Nv(e)+1).replace(J3,"")}var J3,Dv,kv=v(()=>{Ov();J3=/^\s+/;Dv=eN});function tN(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Tn,Is=v(()=>{Tn=tN});function sN(e){if(typeof e=="number")return e;if(ai(e))return Rv;if(Tn(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=Tn(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=Dv(e);var r=nN.test(e);return r||iN.test(e)?aN(e.slice(2),r?2:8):rN.test(e)?Rv:+e}var Rv,rN,nN,iN,aN,km,Lv=v(()=>{kv();Is();Io();Rv=0/0,rN=/^[-+]0x[0-9a-f]+$/i,nN=/^0b[01]+$/i,iN=/^0o[0-7]+$/i,aN=parseInt;km=sN});function oN(e){return e}var Ia,Ec=v(()=>{Ia=oN});function dN(e){if(!Tn(e))return!1;var t=ni(e);return t==cN||t==lN||t==uN||t==fN}var uN,cN,lN,fN,Of,Rm=v(()=>{So();Is();uN="[object AsyncFunction]",cN="[object Function]",lN="[object GeneratorFunction]",fN="[object Proxy]";Of=dN});var hN,Df,Pv=v(()=>{ri();hN=Yt["__core-js_shared__"],Df=hN});function pN(e){return!!Mv&&Mv in e}var Mv,Fv,Bv=v(()=>{Pv();Mv=function(){var e=/[^.]+$/.exec(Df&&Df.keys&&Df.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();Fv=pN});function _N(e){if(e!=null){try{return gN.call(e)}catch{}try{return e+""}catch{}}return""}var mN,gN,Xi,Lm=v(()=>{mN=Function.prototype,gN=mN.toString;Xi=_N});function wN(e){if(!Tn(e)||Fv(e))return!1;var t=Of(e)?AN:EN;return t.test(Xi(e))}var bN,EN,vN,TN,xN,yN,AN,$v,Hv=v(()=>{Rm();Bv();Is();Lm();bN=/[\\^$.*+?()[\]{}|]/g,EN=/^\[object .+?Constructor\]$/,vN=Function.prototype,TN=Object.prototype,xN=vN.toString,yN=TN.hasOwnProperty,AN=RegExp("^"+xN.call(yN).replace(bN,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");$v=wN});function SN(e,t){return e?.[t]}var Uv,Vv=v(()=>{Uv=SN});function CN(e,t){var r=Uv(e,t);return $v(r)?r:void 0}var tn,Na=v(()=>{Hv();Vv();tn=CN});var IN,kf,qv=v(()=>{Na();ri();IN=tn(Yt,"WeakMap"),kf=IN});function NN(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var zv,Yv=v(()=>{zv=NN});function RN(e){var t=0,r=0;return function(){var n=kN(),i=DN-(n-r);if(r=n,i>0){if(++t>=ON)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var ON,DN,kN,Kv,jv=v(()=>{ON=800,DN=16,kN=Date.now;Kv=RN});function LN(e){return function(){return e}}var Wv,Gv=v(()=>{Wv=LN});var PN,Pm,Qv=v(()=>{Na();PN=function(){try{var e=tn(Object,"defineProperty");return e({},"",{}),e}catch{}}(),Pm=PN});var MN,Xv,Zv=v(()=>{Gv();Qv();Ec();MN=Pm?function(e,t){return Pm(e,"toString",{configurable:!0,enumerable:!1,value:Wv(t),writable:!0})}:Ia,Xv=MN});var FN,Jv,e1=v(()=>{Zv();jv();FN=Kv(Xv),Jv=FN});function HN(e,t){var r=typeof e;return t=t??BN,!!t&&(r=="number"||r!="symbol"&&$N.test(e))&&e>-1&&e%1==0&&e{BN=9007199254740991,$N=/^(?:0|[1-9]\d*)$/;Oo=HN});function UN(e,t){return e===t||e!==e&&t!==t}var Do,Lf=v(()=>{Do=UN});function VN(e,t,r){return t=t1(t===void 0?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=t1(n.length-t,0),o=Array(a);++i{Yv();t1=Math.max;r1=VN});function qN(e,t){return Jv(r1(e,t,Ia),e+"")}var i1,a1=v(()=>{Ec();n1();e1();i1=qN});function YN(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=zN}var zN,ko,Pf=v(()=>{zN=9007199254740991;ko=YN});function KN(e){return e!=null&&ko(e.length)&&!Of(e)}var Oa,vc=v(()=>{Rm();Pf();Oa=KN});function jN(e,t,r){if(!Tn(r))return!1;var n=typeof t;return(n=="number"?Oa(r)&&Oo(t,r.length):n=="string"&&t in r)?Do(r[t],e):!1}var Mm,s1=v(()=>{Lf();vc();Rf();Is();Mm=jN});function GN(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||WN;return e===r}var WN,o1,u1=v(()=>{WN=Object.prototype;o1=GN});function QN(e,t){for(var r=-1,n=Array(e);++r{c1=QN});function ZN(e){return ii(e)&&ni(e)==XN}var XN,Fm,f1=v(()=>{So();Co();XN="[object Arguments]";Fm=ZN});var d1,JN,eO,tO,Ro,Mf=v(()=>{f1();Co();d1=Object.prototype,JN=d1.hasOwnProperty,eO=d1.propertyIsEnumerable,tO=Fm(function(){return arguments}())?Fm:function(e){return ii(e)&&JN.call(e,"callee")&&!eO.call(e,"callee")},Ro=tO});function rO(){return!1}var h1,p1=v(()=>{h1=rO});var _1,m1,nO,g1,iO,aO,Tc,Bm=v(()=>{ri();p1();_1=typeof exports=="object"&&exports&&!exports.nodeType&&exports,m1=_1&&typeof module=="object"&&module&&!module.nodeType&&module,nO=m1&&m1.exports===_1,g1=nO?Yt.Buffer:void 0,iO=g1?g1.isBuffer:void 0,aO=iO||h1,Tc=aO});function OO(e){return ii(e)&&ko(e.length)&&!!yt[ni(e)]}var sO,oO,uO,cO,lO,fO,dO,hO,pO,mO,gO,_O,bO,EO,vO,TO,xO,yO,AO,wO,SO,CO,IO,NO,yt,b1,E1=v(()=>{So();Pf();Co();sO="[object Arguments]",oO="[object Array]",uO="[object Boolean]",cO="[object Date]",lO="[object Error]",fO="[object Function]",dO="[object Map]",hO="[object Number]",pO="[object Object]",mO="[object RegExp]",gO="[object Set]",_O="[object String]",bO="[object WeakMap]",EO="[object ArrayBuffer]",vO="[object DataView]",TO="[object Float32Array]",xO="[object Float64Array]",yO="[object Int8Array]",AO="[object Int16Array]",wO="[object Int32Array]",SO="[object Uint8Array]",CO="[object Uint8ClampedArray]",IO="[object Uint16Array]",NO="[object Uint32Array]",yt={};yt[TO]=yt[xO]=yt[yO]=yt[AO]=yt[wO]=yt[SO]=yt[CO]=yt[IO]=yt[NO]=!0;yt[sO]=yt[oO]=yt[EO]=yt[uO]=yt[vO]=yt[cO]=yt[lO]=yt[fO]=yt[dO]=yt[hO]=yt[pO]=yt[mO]=yt[gO]=yt[_O]=yt[bO]=!1;b1=OO});function DO(e){return function(t){return e(t)}}var Ff,$m=v(()=>{Ff=DO});var v1,xc,kO,Hm,RO,Um,T1=v(()=>{Om();v1=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xc=v1&&typeof module=="object"&&module&&!module.nodeType&&module,kO=xc&&xc.exports===v1,Hm=kO&&Nf.process,RO=function(){try{var e=xc&&xc.require&&xc.require("util").types;return e||Hm&&Hm.binding&&Hm.binding("util")}catch{}}(),Um=RO});var x1,LO,Bf,Vm=v(()=>{E1();$m();T1();x1=Um&&Um.isTypedArray,LO=x1?Ff(x1):b1,Bf=LO});function FO(e,t){var r=Ft(e),n=!r&&Ro(e),i=!r&&!n&&Tc(e),a=!r&&!n&&!i&&Bf(e),o=r||n||i||a,l=o?c1(e.length,String):[],d=l.length;for(var p in e)(t||MO.call(e,p))&&!(o&&(p=="length"||i&&(p=="offset"||p=="parent")||a&&(p=="buffer"||p=="byteLength"||p=="byteOffset")||Oo(p,d)))&&l.push(p);return l}var PO,MO,y1,A1=v(()=>{l1();Mf();si();Bm();Rf();Vm();PO=Object.prototype,MO=PO.hasOwnProperty;y1=FO});function BO(e,t){return function(r){return e(t(r))}}var w1,S1=v(()=>{w1=BO});var $O,C1,I1=v(()=>{S1();$O=w1(Object.keys,Object),C1=$O});function VO(e){if(!o1(e))return C1(e);var t=[];for(var r in Object(e))UO.call(e,r)&&r!="constructor"&&t.push(r);return t}var HO,UO,N1,O1=v(()=>{u1();I1();HO=Object.prototype,UO=HO.hasOwnProperty;N1=VO});function qO(e){return Oa(e)?y1(e):N1(e)}var Lo,$f=v(()=>{A1();O1();vc();Lo=qO});function KO(e,t){if(Ft(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||ai(e)?!0:YO.test(e)||!zO.test(e)||t!=null&&e in Object(t)}var zO,YO,Po,Hf=v(()=>{si();Io();zO=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,YO=/^\w*$/;Po=KO});var jO,Zi,yc=v(()=>{Na();jO=tn(Object,"create"),Zi=jO});function WO(){this.__data__=Zi?Zi(null):{},this.size=0}var D1,k1=v(()=>{yc();D1=WO});function GO(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var R1,L1=v(()=>{R1=GO});function JO(e){var t=this.__data__;if(Zi){var r=t[e];return r===QO?void 0:r}return ZO.call(t,e)?t[e]:void 0}var QO,XO,ZO,P1,M1=v(()=>{yc();QO="__lodash_hash_undefined__",XO=Object.prototype,ZO=XO.hasOwnProperty;P1=JO});function rD(e){var t=this.__data__;return Zi?t[e]!==void 0:tD.call(t,e)}var eD,tD,F1,B1=v(()=>{yc();eD=Object.prototype,tD=eD.hasOwnProperty;F1=rD});function iD(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Zi&&t===void 0?nD:t,this}var nD,$1,H1=v(()=>{yc();nD="__lodash_hash_undefined__";$1=iD});function Mo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t{k1();L1();M1();B1();H1();Mo.prototype.clear=D1;Mo.prototype.delete=R1;Mo.prototype.get=P1;Mo.prototype.has=F1;Mo.prototype.set=$1;qm=Mo});function aD(){this.__data__=[],this.size=0}var V1,q1=v(()=>{V1=aD});function sD(e,t){for(var r=e.length;r--;)if(Do(e[r][0],t))return r;return-1}var Da,Ac=v(()=>{Lf();Da=sD});function cD(e){var t=this.__data__,r=Da(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():uD.call(t,r,1),--this.size,!0}var oD,uD,z1,Y1=v(()=>{Ac();oD=Array.prototype,uD=oD.splice;z1=cD});function lD(e){var t=this.__data__,r=Da(t,e);return r<0?void 0:t[r][1]}var K1,j1=v(()=>{Ac();K1=lD});function fD(e){return Da(this.__data__,e)>-1}var W1,G1=v(()=>{Ac();W1=fD});function dD(e,t){var r=this.__data__,n=Da(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var Q1,X1=v(()=>{Ac();Q1=dD});function Fo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t{q1();Y1();j1();G1();X1();Fo.prototype.clear=V1;Fo.prototype.delete=z1;Fo.prototype.get=K1;Fo.prototype.has=W1;Fo.prototype.set=Q1;ka=Fo});var hD,Ra,Uf=v(()=>{Na();ri();hD=tn(Yt,"Map"),Ra=hD});function pD(){this.size=0,this.__data__={hash:new qm,map:new(Ra||ka),string:new qm}}var Z1,J1=v(()=>{U1();wc();Uf();Z1=pD});function mD(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var eT,tT=v(()=>{eT=mD});function gD(e,t){var r=e.__data__;return eT(t)?r[typeof t=="string"?"string":"hash"]:r.map}var La,Sc=v(()=>{tT();La=gD});function _D(e){var t=La(this,e).delete(e);return this.size-=t?1:0,t}var rT,nT=v(()=>{Sc();rT=_D});function bD(e){return La(this,e).get(e)}var iT,aT=v(()=>{Sc();iT=bD});function ED(e){return La(this,e).has(e)}var sT,oT=v(()=>{Sc();sT=ED});function vD(e,t){var r=La(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var uT,cT=v(()=>{Sc();uT=vD});function Bo(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t{J1();nT();aT();oT();cT();Bo.prototype.clear=Z1;Bo.prototype.delete=rT;Bo.prototype.get=iT;Bo.prototype.has=sT;Bo.prototype.set=uT;Ns=Bo});function zm(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(TD);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(zm.Cache||Ns),r}var TD,lT,fT=v(()=>{Vf();TD="Expected a function";zm.Cache=Ns;lT=zm});function yD(e){var t=lT(e,function(n){return r.size===xD&&r.clear(),n}),r=t.cache;return t}var xD,dT,hT=v(()=>{fT();xD=500;dT=yD});var AD,wD,SD,pT,mT=v(()=>{hT();AD=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,wD=/\\(\\)?/g,SD=dT(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(AD,function(r,n,i,a){t.push(i?a.replace(wD,"$1"):n||r)}),t}),pT=SD});function CD(e){return e==null?"":Cv(e)}var qf,Ym=v(()=>{Iv();qf=CD});function ID(e,t){return Ft(e)?e:Po(e,t)?[e]:pT(qf(e))}var zf,Km=v(()=>{si();Hf();mT();Ym();zf=ID});function OD(e){if(typeof e=="string"||ai(e))return e;var t=e+"";return t=="0"&&1/e==-ND?"-0":t}var ND,Pa,Cc=v(()=>{Io();ND=1/0;Pa=OD});function DD(e,t){t=zf(t,e);for(var r=0,n=t.length;e!=null&&r{Km();Cc();$o=DD});function kD(e,t,r){var n=e==null?void 0:$o(e,t);return n===void 0?r:n}var gT,_T=v(()=>{Yf();gT=kD});function RD(e,t){for(var r=-1,n=t.length,i=e.length;++r{Kf=RD});function LD(e){return Ft(e)||Ro(e)||!!(bT&&e&&e[bT])}var bT,ET,vT=v(()=>{wo();Mf();si();bT=Ur?Ur.isConcatSpreadable:void 0;ET=LD});function TT(e,t,r,n,i){var a=-1,o=e.length;for(r||(r=ET),i||(i=[]);++a0&&r(l)?t>1?TT(l,t-1,r,n,i):Kf(i,l):n||(i[i.length]=l)}return i}var xT,yT=v(()=>{jm();vT();xT=TT});function PD(){this.__data__=new ka,this.size=0}var AT,wT=v(()=>{wc();AT=PD});function MD(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var ST,CT=v(()=>{ST=MD});function FD(e){return this.__data__.get(e)}var IT,NT=v(()=>{IT=FD});function BD(e){return this.__data__.has(e)}var OT,DT=v(()=>{OT=BD});function HD(e,t){var r=this.__data__;if(r instanceof ka){var n=r.__data__;if(!Ra||n.length<$D-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Ns(n)}return r.set(e,t),this.size=r.size,this}var $D,kT,RT=v(()=>{wc();Uf();Vf();$D=200;kT=HD});function Ho(e){var t=this.__data__=new ka(e);this.size=t.size}var Uo,Wm=v(()=>{wc();wT();CT();NT();DT();RT();Ho.prototype.clear=AT;Ho.prototype.delete=ST;Ho.prototype.get=IT;Ho.prototype.has=OT;Ho.prototype.set=kT;Uo=Ho});function UD(e,t){for(var r=-1,n=e==null?0:e.length,i=0,a=[];++r{LT=UD});function VD(){return[]}var MT,FT=v(()=>{MT=VD});var qD,zD,BT,YD,$T,HT=v(()=>{PT();FT();qD=Object.prototype,zD=qD.propertyIsEnumerable,BT=Object.getOwnPropertySymbols,YD=BT?function(e){return e==null?[]:(e=Object(e),LT(BT(e),function(t){return zD.call(e,t)}))}:MT,$T=YD});function KD(e,t,r){var n=t(e);return Ft(e)?n:Kf(n,r(e))}var UT,VT=v(()=>{jm();si();UT=KD});function jD(e){return UT(e,Lo,$T)}var Gm,qT=v(()=>{VT();HT();$f();Gm=jD});var WD,jf,zT=v(()=>{Na();ri();WD=tn(Yt,"DataView"),jf=WD});var GD,Wf,YT=v(()=>{Na();ri();GD=tn(Yt,"Promise"),Wf=GD});var QD,Gf,KT=v(()=>{Na();ri();QD=tn(Yt,"Set"),Gf=QD});var jT,XD,WT,GT,QT,XT,ZD,JD,ek,tk,rk,Os,Qm,ZT=v(()=>{zT();Uf();YT();KT();qv();So();Lm();jT="[object Map]",XD="[object Object]",WT="[object Promise]",GT="[object Set]",QT="[object WeakMap]",XT="[object DataView]",ZD=Xi(jf),JD=Xi(Ra),ek=Xi(Wf),tk=Xi(Gf),rk=Xi(kf),Os=ni;(jf&&Os(new jf(new ArrayBuffer(1)))!=XT||Ra&&Os(new Ra)!=jT||Wf&&Os(Wf.resolve())!=WT||Gf&&Os(new Gf)!=GT||kf&&Os(new kf)!=QT)&&(Os=function(e){var t=ni(e),r=t==XD?e.constructor:void 0,n=r?Xi(r):"";if(n)switch(n){case ZD:return XT;case JD:return jT;case ek:return WT;case tk:return GT;case rk:return QT}return t});Qm=Os});var nk,Xm,JT=v(()=>{ri();nk=Yt.Uint8Array,Xm=nk});function ak(e){return this.__data__.set(e,ik),this}var ik,ex,tx=v(()=>{ik="__lodash_hash_undefined__";ex=ak});function sk(e){return this.__data__.has(e)}var rx,nx=v(()=>{rx=sk});function Qf(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Ns;++t{Vf();tx();nx();Qf.prototype.add=Qf.prototype.push=ex;Qf.prototype.has=rx;ix=Qf});function ok(e,t){for(var r=-1,n=e==null?0:e.length;++r{sx=ok});function uk(e,t){return e.has(t)}var ux,cx=v(()=>{ux=uk});function fk(e,t,r,n,i,a){var o=r&ck,l=e.length,d=t.length;if(l!=d&&!(o&&d>l))return!1;var p=a.get(e),g=a.get(t);if(p&&g)return p==t&&g==e;var E=-1,_=!0,y=r&lk?new ix:void 0;for(a.set(e,t),a.set(t,e);++E{ax();ox();cx();ck=1,lk=2;Xf=fk});function dk(e){var t=-1,r=Array(e.size);return e.forEach(function(n,i){r[++t]=[i,n]}),r}var lx,fx=v(()=>{lx=dk});function hk(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var dx,hx=v(()=>{dx=hk});function Ck(e,t,r,n,i,a,o){switch(r){case Sk:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case wk:return!(e.byteLength!=t.byteLength||!a(new Xm(e),new Xm(t)));case gk:case _k:case vk:return Do(+e,+t);case bk:return e.name==t.name&&e.message==t.message;case Tk:case yk:return e==t+"";case Ek:var l=lx;case xk:var d=n&pk;if(l||(l=dx),e.size!=t.size&&!d)return!1;var p=o.get(e);if(p)return p==t;n|=mk,o.set(e,t);var g=Xf(l(e),l(t),n,i,a,o);return o.delete(e),g;case Ak:if(Jm)return Jm.call(e)==Jm.call(t)}return!1}var pk,mk,gk,_k,bk,Ek,vk,Tk,xk,yk,Ak,wk,Sk,px,Jm,mx,gx=v(()=>{wo();JT();Lf();Zm();fx();hx();pk=1,mk=2,gk="[object Boolean]",_k="[object Date]",bk="[object Error]",Ek="[object Map]",vk="[object Number]",Tk="[object RegExp]",xk="[object Set]",yk="[object String]",Ak="[object Symbol]",wk="[object ArrayBuffer]",Sk="[object DataView]",px=Ur?Ur.prototype:void 0,Jm=px?px.valueOf:void 0;mx=Ck});function Dk(e,t,r,n,i,a){var o=r&Ik,l=Gm(e),d=l.length,p=Gm(t),g=p.length;if(d!=g&&!o)return!1;for(var E=d;E--;){var _=l[E];if(!(o?_ in t:Ok.call(t,_)))return!1}var y=a.get(e),C=a.get(t);if(y&&C)return y==t&&C==e;var k=!0;a.set(e,t),a.set(t,e);for(var P=o;++E{qT();Ik=1,Nk=Object.prototype,Ok=Nk.hasOwnProperty;_x=Dk});function Lk(e,t,r,n,i,a){var o=Ft(e),l=Ft(t),d=o?vx:Qm(e),p=l?vx:Qm(t);d=d==Ex?Zf:d,p=p==Ex?Zf:p;var g=d==Zf,E=p==Zf,_=d==p;if(_&&Tc(e)){if(!Tc(t))return!1;o=!0,g=!1}if(_&&!g)return a||(a=new Uo),o||Bf(e)?Xf(e,t,r,n,i,a):mx(e,t,d,r,n,i,a);if(!(r&kk)){var y=g&&Tx.call(e,"__wrapped__"),C=E&&Tx.call(t,"__wrapped__");if(y||C){var k=y?e.value():e,P=C?t.value():t;return a||(a=new Uo),i(k,P,r,n,a)}}return _?(a||(a=new Uo),_x(e,t,r,n,i,a)):!1}var kk,Ex,vx,Zf,Rk,Tx,xx,yx=v(()=>{Wm();Zm();gx();bx();ZT();si();Bm();Vm();kk=1,Ex="[object Arguments]",vx="[object Array]",Zf="[object Object]",Rk=Object.prototype,Tx=Rk.hasOwnProperty;xx=Lk});function Ax(e,t,r,n,i){return e===t?!0:e==null||t==null||!ii(e)&&!ii(t)?e!==e&&t!==t:xx(e,t,r,n,Ax,i)}var Jf,e0=v(()=>{yx();Co();Jf=Ax});function Fk(e,t,r,n){var i=r.length,a=i,o=!n;if(e==null)return!a;for(e=Object(e);i--;){var l=r[i];if(o&&l[2]?l[1]!==e[l[0]]:!(l[0]in e))return!1}for(;++i{Wm();e0();Pk=1,Mk=2;wx=Fk});function Bk(e){return e===e&&!Tn(e)}var ed,t0=v(()=>{Is();ed=Bk});function $k(e){for(var t=Lo(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,ed(i)]}return t}var Cx,Ix=v(()=>{t0();$f();Cx=$k});function Hk(e,t){return function(r){return r==null?!1:r[e]===t&&(t!==void 0||e in Object(r))}}var td,r0=v(()=>{td=Hk});function Uk(e){var t=Cx(e);return t.length==1&&t[0][2]?td(t[0][0],t[0][1]):function(r){return r===e||wx(r,e,t)}}var Nx,Ox=v(()=>{Sx();Ix();r0();Nx=Uk});function Vk(e,t){return e!=null&&t in Object(e)}var Dx,kx=v(()=>{Dx=Vk});function qk(e,t,r){t=zf(t,e);for(var n=-1,i=t.length,a=!1;++n{Km();Mf();si();Rf();Pf();Cc();Rx=qk});function zk(e,t){return e!=null&&Rx(e,t,Dx)}var Px,Mx=v(()=>{kx();Lx();Px=zk});function jk(e,t){return Po(e)&&ed(t)?td(Pa(e),t):function(r){var n=gT(r,e);return n===void 0&&n===t?Px(r,e):Jf(t,n,Yk|Kk)}}var Yk,Kk,Fx,Bx=v(()=>{e0();_T();Mx();Hf();t0();r0();Cc();Yk=1,Kk=2;Fx=jk});function Wk(e){return function(t){return t?.[e]}}var $x,Hx=v(()=>{$x=Wk});function Gk(e){return function(t){return $o(t,e)}}var Ux,Vx=v(()=>{Yf();Ux=Gk});function Qk(e){return Po(e)?$x(Pa(e)):Ux(e)}var qx,zx=v(()=>{Hx();Vx();Hf();Cc();qx=Qk});function Xk(e){return typeof e=="function"?e:e==null?Ia:typeof e=="object"?Ft(e)?Fx(e[0],e[1]):Nx(e):qx(e)}var Yx,Kx=v(()=>{Ox();Bx();Ec();si();zx();Yx=Xk});function Zk(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),l=o.length;l--;){var d=o[e?l:++i];if(r(a[d],d,a)===!1)break}return t}}var jx,Wx=v(()=>{jx=Zk});var Jk,Gx,Qx=v(()=>{Wx();Jk=jx(),Gx=Jk});function e6(e,t){return e&&Gx(e,t,Lo)}var Xx,Zx=v(()=>{Qx();$f();Xx=e6});function t6(e,t){return function(r,n){if(r==null)return r;if(!Oa(r))return e(r,n);for(var i=r.length,a=t?i:-1,o=Object(r);(t?a--:++a{vc();Jx=t6});var r6,ty,ry=v(()=>{Zx();ey();r6=Jx(Xx),ty=r6});var n6,rd,ny=v(()=>{ri();n6=function(){return Yt.Date.now()},rd=n6});function o6(e,t,r){var n,i,a,o,l,d,p=0,g=!1,E=!1,_=!0;if(typeof e!="function")throw new TypeError(i6);t=km(t)||0,Tn(r)&&(g=!!r.leading,E="maxWait"in r,a=E?a6(km(r.maxWait)||0,t):a,_="trailing"in r?!!r.trailing:_);function y(V){var X=n,ce=i;return n=i=void 0,p=V,o=e.apply(ce,X),o}function C(V){return p=V,l=setTimeout(N,t),g?y(V):o}function k(V){var X=V-d,ce=V-p,ve=t-X;return E?s6(ve,a-ce):ve}function P(V){var X=V-d,ce=V-p;return d===void 0||X>=t||X<0||E&&ce>=a}function N(){var V=rd();if(P(V))return L(V);l=setTimeout(N,k(V))}function L(V){return l=void 0,_&&n?y(V):(n=i=void 0,o)}function H(){l!==void 0&&clearTimeout(l),p=0,n=d=i=l=void 0}function R(){return l===void 0?o:L(rd())}function B(){var V=rd(),X=P(V);if(n=arguments,i=this,d=V,X){if(l===void 0)return C(d);if(E)return clearTimeout(l),l=setTimeout(N,t),y(d)}return l===void 0&&(l=setTimeout(N,t)),o}return B.cancel=H,B.flush=R,B}var i6,a6,s6,Ic,iy=v(()=>{Is();ny();Lv();i6="Expected a function",a6=Math.max,s6=Math.min;Ic=o6});function c6(e){return e=qf(e),e&&u6.test(e)?e.replace(ay,"\\$&"):e}var ay,u6,Nc,sy=v(()=>{Ym();ay=/[\\^$.*+?()[\]{}|]/g,u6=RegExp(ay.source);Nc=c6});function l6(e,t){var r=-1,n=Oa(e)?Array(e.length):[];return ty(e,function(i,a,o){n[++r]=t(i,a,o)}),n}var oy,uy=v(()=>{ry();vc();oy=l6});function f6(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var cy,ly=v(()=>{cy=f6});function d6(e,t){if(e!==t){var r=e!==void 0,n=e===null,i=e===e,a=ai(e),o=t!==void 0,l=t===null,d=t===t,p=ai(t);if(!l&&!p&&!a&&e>t||a&&o&&d&&!l&&!p||n&&o&&d||!r&&d||!i)return 1;if(!n&&!a&&!p&&e{Io();fy=d6});function h6(e,t,r){for(var n=-1,i=e.criteria,a=t.criteria,o=i.length,l=r.length;++n=l)return d;var p=r[n];return d*(p=="desc"?-1:1)}}return e.index-t.index}var hy,py=v(()=>{dy();hy=h6});function p6(e,t,r){t.length?t=No(t,function(a){return Ft(a)?function(o){return $o(o,a.length===1?a[0]:a)}:a}):t=[Ia];var n=-1;t=No(t,Ff(Yx));var i=oy(e,function(a,o,l){var d=No(t,function(p){return p(a)});return{criteria:d,index:++n,value:a}});return cy(i,function(a,o){return hy(a,o,r)})}var my,gy=v(()=>{Dm();Yf();Kx();uy();ly();$m();py();Ec();si();my=p6});var m6,n0,_y=v(()=>{yT();gy();a1();s1();m6=i1(function(e,t){if(e==null)return[];var r=t.length;return r>1&&Mm(e,t[0],t[1])?t=[]:r>2&&Mm(t[0],t[1],t[2])&&(t=[t[0]]),my(e,xT(t,1),[])}),n0=m6});var Oc=v(()=>{iy();sy();_y();});function by(e,t,r){let n=e.getTextExtractor(),i=e.getAIImageAnalyzer(),a=e.database,o=Ic(async()=>{await a.clearCache()},1e3);new Ji.Setting(r).setName("Indexing").setHeading().setDesc(ar(`\u26A0\uFE0F Changing indexing settings will clear the cache, and requires a restart of Obsidian.

    - ${n?`\u{1F44D} You have installed Text Extractor, Omnisearch can use it to index PDFs and images contents. -
    Text extraction only works on desktop, but the cache can be synchronized with your mobile device.`:'\u26A0\uFE0F Omnisearch requires Text Extractor to index PDFs and images.'} - ${i?'
    \u{1F44D} You have installed AI Image Analyzer, Omnisearch can use it to index images contents with ai.':'
    \u26A0\uFE0F Omnisearch requires AI Image Analyzer to index images with ai.'}`)),new Ji.Setting(r).setName(`PDFs content indexing ${n?"":"\u26A0\uFE0F Disabled"}`).setDesc(ar("Omnisearch will use Text Extractor to index the content of your PDFs.")).addToggle(p=>p.setValue(t.PDFIndexing).onChange(async g=>{await a.clearCache(),t.PDFIndexing=g,await ke(e)})).setDisabled(!n),new Ji.Setting(r).setName(`Images OCR indexing ${n?"":"\u26A0\uFE0F Disabled"}`).setDesc(ar("Omnisearch will use Text Extractor to OCR your images and index their content.")).addToggle(p=>p.setValue(t.imagesIndexing).onChange(async g=>{await a.clearCache(),t.imagesIndexing=g,await ke(e)})).setDisabled(!n);let l=new DocumentFragment;l.createSpan({},p=>{p.innerHTML='Omnisearch will use Text Extractor to index the content of your office documents (currently
    .docx
    and
    .xlsx
    ).'}),new Ji.Setting(r).setName(`Documents content indexing ${n?"":"\u26A0\uFE0F Disabled"}`).setDesc(l).addToggle(p=>p.setValue(t.officeIndexing).onChange(async g=>{await a.clearCache(),t.officeIndexing=g,await ke(e)})).setDisabled(!n);let d=new DocumentFragment;d.createSpan({},p=>{p.innerHTML="Omnisearch will use AI Image Analyzer to index the content of your images with ai."}),new Ji.Setting(r).setName(`Images AI indexing ${i?"":"\u26A0\uFE0F Disabled"}`).setDesc(d).addToggle(p=>p.setValue(t.aiImageIndexing).onChange(async g=>{await a.clearCache(),t.aiImageIndexing=g,await ke(e)})).setDisabled(!i),new Ji.Setting(r).setName("Index paths of unsupported files").setDesc(ar(` - Omnisearch can index filenames of "unsupported" files, such as e.g.
    .mp4
    - or non-extracted PDFs & images.
    - "Obsidian setting" will respect the value of "Files & Links > Detect all file extensions".`)).addDropdown(p=>{p.addOptions({yes:"Yes",no:"No",default:"Obsidian setting"}).setValue(t.unsupportedFilesIndexing).onChange(async g=>{await o(),t.unsupportedFilesIndexing=g,await ke(e)})}),new Ji.Setting(r).setName("Set frontmatter property key as title").setDesc(ar(`If you have a custom property in your notes that you want to use as the title in search results. If you set this to '#heading', then use the first heading from a file as the title.
    - Leave empty to disable.`)).addText(p=>{p.setValue(t.displayTitle).onChange(async g=>{await o(),t.displayTitle=g,await ke(e)})}),new Ji.Setting(r).setName("Additional TEXT files to index").setDesc(ar(`In addition to standard md files, Omnisearch can also index other PLAINTEXT files.
    - Add extensions separated by a space, without the dot. Example: "txt org csv".
    - \u26A0\uFE0F Using extensions of non-plaintext files (like .pptx) WILL cause crashes, - because Omnisearch will try to index their content.`)).addText(p=>{p.setValue(t.indexedFileTypes.join(" ")).setPlaceholder("Example: txt org csv").onChange(async g=>{await a.clearCache(),t.indexedFileTypes=g.split(" "),await ke(e)})})}var Ji,Ey=v(()=>{Ji=require("obsidian");mr();mr();Oc()});function vy(e,t,r){let n=e.database;new rn.Setting(r).setName("Behavior").setHeading(),new rn.Setting(r).setName("Save index to cache").setDesc("Enable caching to speed up indexing time. In rare cases, the cache write may cause a crash in Obsidian. This option will disable itself if it happens.").addToggle(i=>i.setValue(t.useCache).onChange(async a=>{t.useCache=a,await ke(e)})),new rn.Setting(r).setName("Show previous query results").setDesc("Re-executes the previous query when opening Omnisearch.").addToggle(i=>i.setValue(t.showPreviousQueryResults).onChange(async a=>{t.showPreviousQueryResults=a,await ke(e)})),new rn.Setting(r).setName(`Respect Obsidian's "Excluded Files"`).setDesc(`By default, files that are in Obsidian's "Options > Files & Links > Excluded Files" list are downranked in results. - Enable this option to completely hide them.`).addToggle(i=>i.setValue(t.hideExcluded).onChange(async a=>{t.hideExcluded=a,await ke(e)})),new rn.Setting(r).setName("Folders to downrank in search results").setDesc("Folders to downrank in search results. Files in these folders will be downranked in results. They will still be indexed for tags, unlike excluded files. Folders should be comma delimited.").addText(i=>{i.setValue(t.downrankedFoldersFilters.join(",")).setPlaceholder("Example: src,p2/dir").onChange(async a=>{let o=a.split(",");o=o.map(l=>l.trim()),t.downrankedFoldersFilters=o,await ke(e)})}),new rn.Setting(r).setName("Split CamelCaseWords").setDesc(ar(`Enable this if you want to be able to search for CamelCaseWords as separate words.
    - \u26A0\uFE0F Changing this setting will clear the cache.
    - ${yo}`)).addToggle(i=>i.setValue(t.splitCamelCase).onChange(async a=>{await n.clearCache(),t.splitCamelCase=a,await ke(e)})),new rn.Setting(r).setName("Simpler search").setDesc(`Enable this if Obsidian often freezes while making searches. - Words shorter than 3 characters won't be used as prefixes; this can reduce search delay but will return fewer results.`).addToggle(i=>i.setValue(t.simpleSearch).onChange(async a=>{t.simpleSearch=a,await ke(e)})),rn.Platform.isIosApp||new rn.Setting(r).setName("Tokenize URLs").setDesc(`Enable this if you want to be able to search for URLs as separate words. - This setting has a strong impact on indexing performance, and can crash Obsidian under certain conditions.`).addToggle(i=>i.setValue(t.tokenizeUrls).onChange(async a=>{t.tokenizeUrls=a,await ke(e)})),new rn.Setting(r).setName("Open in new pane").setDesc("Open and create files in a new pane instead of the current pane.").addToggle(i=>i.setValue(t.openInNewPane).onChange(async a=>{t.openInNewPane=a,await ke(e)})),new rn.Setting(r).setName("Set Vim like navigation keys").setDesc(`Navigate down the results with ${vn()} + J/N, or navigate up with ${vn()} + K/P.`).addToggle(i=>i.setValue(t.vimLikeNavigationShortcut).onChange(async a=>{t.vimLikeNavigationShortcut=a,await ke(e)})),new rn.Setting(r).setName("Fuzziness").setDesc("Define the level of fuzziness for the search. The higher the fuzziness, the more results you'll get.").addDropdown(i=>i.addOptions({0:"Exact match",1:"Not too fuzzy",2:"Fuzzy enough"}).setValue(t.fuzziness).onChange(async a=>{["0","1","2"].includes(a)||(a="2"),t.fuzziness=a,await ke(e)}))}var rn,Ty=v(()=>{rn=require("obsidian");mr();mr();Nr()});function xy(e,t,r){new Ma.Setting(r).setName("User Interface").setHeading(),new Ma.Setting(r).setName("Show ribbon button").setDesc("Add a button on the sidebar to open the Vault search modal.").addToggle(n=>n.setValue(t.ribbonIcon).onChange(async i=>{t.ribbonIcon=i,await ke(e),i?e.addRibbonButton():e.removeRibbonButton()})),new Ma.Setting(r).setName("Show excerpts").setDesc("Shows the contextual part of the note that matches the search. Disable this to only show filenames in results.").addToggle(n=>n.setValue(t.showExcerpt).onChange(async i=>{Fa.set(i)})),new Ma.Setting(r).setName("Show embed references").setDesc(ar(`Some results are embedded in other notes.
    - This setting controls the maximum number of embeds to show in the search results. Set to 0 to disable.
    - Also works with Text Extractor for embedded images and documents.`)).addSlider(n=>{n.setLimits(0,10,1).setValue(t.maxEmbeds).setDynamicTooltip().onChange(async i=>{t.maxEmbeds=i,await ke(e)})}),new Ma.Setting(r).setName("Render line return in excerpts").setDesc("Activate this option to render line returns in result excerpts.").addToggle(n=>n.setValue(t.renderLineReturnInExcerpts).onChange(async i=>{t.renderLineReturnInExcerpts=i,await ke(e)})),new Ma.Setting(r).setName('Show "Create note" button').setDesc(ar(`Shows a button next to the search input, to create a note. - Acts the same as the shift \u21B5 shortcut, can be useful for mobile device users.`)).addToggle(n=>n.setValue(t.showCreateButton).onChange(async i=>{t.showCreateButton=i,await ke(e)})),new Ma.Setting(r).setName("Highlight matching words in results").setDesc("Will highlight matching results when enabled. See README for more customization options.").addToggle(n=>n.setValue(t.highlight).onChange(async i=>{t.highlight=i,await ke(e)}))}var Ma,yy=v(()=>{Ma=require("obsidian");Ao();mr();mr()});function wy(e,t,r,n){function i(o,l){o.setLimits(1,10,.5).setValue(t[l]).setDynamicTooltip().onChange(async d=>{t[l]=d,await ke(e)})}let a=Dc(e.app);new Fn.Setting(r).setName("Results weighting").setHeading(),new Fn.Setting(r).setName(`File name & declared aliases (default: ${a.weightBasename})`).addSlider(o=>i(o,"weightBasename")),new Fn.Setting(r).setName(`File directory (default: ${a.weightDirectory})`).addSlider(o=>i(o,"weightDirectory")),new Fn.Setting(r).setName(`Headings level 1 (default: ${a.weightH1})`).addSlider(o=>i(o,"weightH1")),new Fn.Setting(r).setName(`Headings level 2 (default: ${a.weightH2})`).addSlider(o=>i(o,"weightH2")),new Fn.Setting(r).setName(`Headings level 3 (default: ${a.weightH3})`).addSlider(o=>i(o,"weightH3")),new Fn.Setting(r).setName(`Tags (default: ${a.weightUnmarkedTags})`).addSlider(o=>i(o,"weightUnmarkedTags")),new Fn.Setting(r).setName("Header properties fields").setDesc('You can set custom weights for values of header properties (e.g. "keywords"). Weights under 1.0 will downrank the results.');for(let o=0;o{p.setPlaceholder("Property name").setValue(l.name).onChange(async g=>{l.name=g,await ke(e)})}).addSlider(p=>{p.setLimits(.1,5,.1).setValue(l.weight).setDynamicTooltip().onChange(async g=>{l.weight=g,await ke(e)})}).addButton(p=>{p.setButtonText("Remove"),p.onClick(async()=>{t.weightCustomProperties.splice(o,1),await ke(e),n()})})}new Fn.Setting(r).addButton(o=>{o.setButtonText("Add a new property"),o.onClick(l=>{t.weightCustomProperties.push({name:"",weight:1}),n()})}),new Fn.Setting(r).setName("Recency boost (experimental)").setDesc("Files that have been modified more recently than [selected cutoff] are given a higher rank.").addDropdown(o=>o.addOptions({["0"]:"Disabled",["1"]:"24 hours",["2"]:"7 days",["3"]:"30 days"}).setValue(t.recencyBoost).onChange(async l=>{t.recencyBoost=l,await ke(e)}))}var Fn,Sy=v(()=>{Fn=require("obsidian");Ao();mr();en()});function Cy(e,t,r){Ds.Platform.isMobile||(new Ds.Setting(r).setName("API Access Through HTTP").setHeading().setDesc(ar('Omnisearch can be used through a simple HTTP server (more information).')),new Ds.Setting(r).setName("Enable the HTTP server").addToggle(n=>n.setValue(t.httpApiEnabled).onChange(async i=>{t.httpApiEnabled=i,i?e.apiHttpServer.listen(t.httpApiPort):e.apiHttpServer.close(),await ke(e)})),new Ds.Setting(r).setName("HTTP Port").addText(n=>{n.setValue(t.httpApiPort).setPlaceholder("51361").onChange(async i=>{parseInt(i)>65535&&(i=t.httpApiPort,n.setValue(t.httpApiPort)),t.httpApiPort=i,t.httpApiEnabled&&(e.apiHttpServer.close(),e.apiHttpServer.listen(t.httpApiPort)),await ke(e)})}),new Ds.Setting(r).setName("Show a notification when the server starts").setDesc("Will display a notification if the server is enabled, at Obsidian startup.").addToggle(n=>n.setValue(t.httpApiNotice).onChange(async i=>{t.httpApiNotice=i,await ke(e)})))}var Ds,Iy=v(()=>{Ds=require("obsidian");mr();mr()});function Ny(e,t,r){let n=e.database;new wi.Setting(r).setName("Danger Zone").setHeading(),new wi.Setting(r).setName("Ignore diacritics").setDesc(ar(`Normalize diacritics in search terms. Words like "br\xFBl\xE9e" or "\u017Elu\u0165ou\u010Dk\xFD" will be indexed as "brulee" and "zlutoucky".
    - \u26A0\uFE0F You probably should NOT disable this.
    - \u26A0\uFE0F Changing this setting will clear the cache.
    - ${yo}`)).addToggle(a=>a.setValue(t.ignoreDiacritics).onChange(async o=>{await n.clearCache(),t.ignoreDiacritics=o,await ke(e)})),new wi.Setting(r).setName("Ignore Arabic diacritics (beta)").addToggle(a=>a.setValue(t.ignoreArabicDiacritics).onChange(async o=>{await n.clearCache(),t.ignoreArabicDiacritics=o,await ke(e)}));let i=new DocumentFragment;i.createSpan({},a=>{a.innerHTML=`Disable Omnisearch on this device only.
    - ${yo}`}),new wi.Setting(r).setName("Disable on this device").setDesc(i).addToggle(a=>a.setValue(If(e.app)).onChange(async o=>{o?(e.app.saveLocalStorage(Ss,"1"),new wi.Notice("Omnisearch - Disabled. Please restart Obsidian.")):(e.app.saveLocalStorage(Ss),new wi.Notice("Omnisearch - Enabled. Please restart Obsidian."))})),new wi.Setting(r).setName("Force save the cache").setDesc(ar(`Omnisearch has a security feature that automatically disables cache writing if it cannot fully perform the operation.
    - Use this option to force the cache to be saved, even if it causes a crash.
    - \u26A0\uFE0F Enabling this setting could lead to crash loops`)).addToggle(a=>a.setValue(t.DANGER_forceSaveCache).onChange(async o=>{t.DANGER_forceSaveCache=o,await ke(e)})),Qi()&&new wi.Setting(r).setName("Clear cache data").setDesc(ar(`Erase all Omnisearch cache data. - Use this if Omnisearch results are inconsistent, missing, or appear outdated.
    - ${yo}`)).addButton(a=>{a.setButtonText("Clear cache"),a.onClick(async()=>{await n.clearCache()})})}var wi,Oy=v(()=>{wi=require("obsidian");mr();mr();mr();en()});function Dc(e){return{useCache:!0,hideExcluded:!1,recencyBoost:"0",downrankedFoldersFilters:[],ignoreDiacritics:!0,ignoreArabicDiacritics:!1,indexedFileTypes:[],displayTitle:"",PDFIndexing:!1,officeIndexing:!1,imagesIndexing:!1,aiImageIndexing:!1,unsupportedFilesIndexing:"default",splitCamelCase:!1,openInNewPane:!1,vimLikeNavigationShortcut:e.vault.getConfig("vimMode"),ribbonIcon:!0,showExcerpt:!0,maxEmbeds:5,renderLineReturnInExcerpts:!0,showCreateButton:!1,highlight:!0,showPreviousQueryResults:!0,simpleSearch:!1,tokenizeUrls:!1,fuzziness:"1",weightBasename:10,weightDirectory:7,weightH1:6,weightH2:5,weightH3:4,weightUnmarkedTags:2,weightCustomProperties:[],httpApiEnabled:!1,httpApiPort:"51361",httpApiNotice:!0,welcomeMessage:"",verboseLogging:!1,DANGER_httpHost:null,DANGER_forceSaveCache:!1}}async function Dy(e){return Or=Object.assign({},Dc(e.app),await e.loadData()),Fa.set(Or.showExcerpt),wm(Or.verboseLogging),Or}var kc,Fa,nd,Or,Ao=v(()=>{kc=require("obsidian");bm();en();Nr();Ey();mr();Ty();yy();Sy();Iy();Oy();Fa=xo(!1),nd=class extends kc.PluginSettingTab{constructor(r){super(r.app,r);this.plugin=r,Fa.subscribe(async n=>{Or.showExcerpt=n,await ke(this.plugin)})}display(){let{containerEl:r}=this,n=this.plugin.database;if(r.empty(),this.app.loadLocalStorage(Ss)=="1"){let a=r.createEl("span");a.innerHTML='\u26A0\uFE0F OMNISEARCH IS DISABLED \u26A0\uFE0F'}r.createEl("h1",{text:"Omnisearch"});let i=r.createDiv();i.innerHTML=` - - Buy Me a Coffee at ko-fi.com - `,by(this.plugin,Or,r),r.createEl("hr"),vy(this.plugin,Or,r),r.createEl("hr"),xy(this.plugin,Or,r),r.createEl("hr"),wy(this.plugin,Or,r,this.display),r.createEl("hr"),Cy(this.plugin,Or,r),r.createEl("hr"),Ny(this.plugin,Or,r),r.createEl("hr"),new kc.Setting(r).setName("Debugging").setHeading(),new kc.Setting(r).setName("Enable verbose logging").setDesc('Adds a LOT of logs for debugging purposes. You also need to enable "Verbose" logging in the console to see these logs.').addToggle(a=>a.setValue(Or.verboseLogging).onChange(async o=>{Or.verboseLogging=o,wm(o),await ke(this.plugin)}))}}});function i0(e){var t=g6();we(e,t)}var g6,ky=v(()=>{Wn();yi();Pn();g6=Le('')});function Rc(e,t){let r=ze(t,"id",8),n=ze(t,"selected",8,!1),i=ze(t,"glyph",8,!1),a=ze(t,"cssClass",8,"");var o=_6();let l;var d=xe(o);{var p=E=>{i0(E,{})};tt(d,E=>{i()&&E(p)})}var g=Ye(d,2);zi(g,t,"default",{},null),Te(o),rr(E=>{Ki(o,"data-result-id",r()),l=Yi(o,1,`suggestion-item omnisearch-result ${a()??""}`,null,l,E)},[()=>({"is-selected":n()})],Br),pr("mousemove",o,function(E){Jr.call(this,t,E)}),pr("click",o,function(E){Jr.call(this,t,E)}),pr("keypress",o,function(E){Jr.call(this,t,E)}),pr("auxclick",o,function(E){Jr.call(this,t,E)}),we(e,o)}var _6,a0=v(()=>{Wn();yi();Pn();ky();_6=Le("
    ")});function ad(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}var Ry,id,s0=v(()=>{en();Nr();Ry=require("obsidian");Oc();id=class{constructor(t){this.plugin=t}highlightText(t,r){let n=`suggestion-highlight omnisearch-highlight ${this.plugin.settings.highlight?"omnisearch-default-highlight":""}`;if(!r.length)return t;try{return t.replace(new RegExp(`(${r.map(i=>Nc(i.match)).join("|")})`,"giu"),`$1`)}catch(i){return console.error("Omnisearch - Error in highlightText()",i),t}}stringsToRegex(t){if(!t.length)return/^$/g;t.sort((n,i)=>i.length-n.length);let r=`(${t.map(n=>`\\b${Nc(n)}\\b|${Nc(n)}`).join("|")})`;return new RegExp(`${r}`,"gui")}getMatches(t,r,n){r=r.map(ad);let i=this.stringsToRegex(r),a=t;this.plugin.settings.ignoreDiacritics&&(t=Wi(t,this.plugin.settings.ignoreArabicDiacritics));let o=new Date().getTime(),l=null,d=[],p=0;for(;(l=i.exec(t))!==null;){if(++p>=100||new Date().getTime()-o>50){Gi("Stopped getMatches at",p,"results");break}let g=l.index,E=g+l[0].length,_=a.substring(g,E).trim();_&&l.index>=0&&d.push({match:_,offset:l.index})}if(n&&(n.query.text.length>1||n.getExactTerms().length>0)){let g=t.indexOf(n.getBestStringForExcerpt());g>-1&&d.find(E=>E.offset===g)&&d.unshift({offset:g,match:n.getBestStringForExcerpt()})}return d}makeExcerpt(t,r){let n=this.plugin.settings;try{let i=r??-1,a=Math.max(0,i-iv),o=Math.min(t.length,i+uc);if(i>-1?t=(a>0?"\u2026":"")+t.slice(a,o).trim()+(op).join(` -`);let d=t.lastIndexOf(` -`,i-a);d>0&&(t=t.slice(d))}return t=ad(t),n.renderLineReturnInExcerpts&&(t=t.trim().replaceAll(` -`,"
    ")),t}catch(i){return new Ry.Notice("Omnisearch - Error while creating excerpt, see developer console"),console.error("Omnisearch - Error while creating excerpt"),console.error(i),""}}}});async function Ly(e){let t=e.app;if(!t.plugins.getPlugin("obsidian-icon-folder"))return{};let n=`${t.vault.configDir}/plugins/obsidian-icon-folder/data.json`;try{let i=await t.vault.adapter.read(n),a=JSON.parse(i),o={};for(let l in a){let d=(0,Vo.normalizePath)(l);o[d]=a[l]}return o}catch(i){return Gi("Failed to read data.json:",i),{}}}async function Py(e){let t={Li:"lucide-icons"},r="icons",n=e.app,i=n.plugins.getPlugin("obsidian-icon-folder");if(i){r=i.settings?.iconPacksPath||"icons";let o=`${n.vault.configDir}/${r}`;try{let l=await n.vault.adapter.list(o);if(l.folders&&l.folders.length>0)for(let d of l.folders){let p=d.split("/"),g=p[p.length-1],E=b6(g);t[E]=g}}catch(l){Gi("Failed to list icon packs:",l)}}return{prefixToIconPack:t,iconsPath:r}}function b6(e){if(e.includes("-")){let t=e.split("-"),r=t[0].charAt(0).toUpperCase();for(let n=1;n${ad(o)}`;let l=n[a];if(!l)return Gi(`No icon pack found for prefix: ${a}`),null;if(l==="lucide-icons"){let d=o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),p=(0,Vo.getIcon)(d);return p?p.outerHTML:(Gi(`Lucide icon not found: ${d}`),null)}else{if(!r)return Gi("Icons path is not set. Cannot load icon SVG."),null;let d=`${t.app.vault.configDir}/${r}/${l}/${o}.svg`;try{return await t.app.vault.adapter.read(d)}catch(p){return Gi(`Failed to load icon SVG for ${e} at ${d}:`,p),null}}}function c0(e,t){let r="file";Mn(e)?r="image":ti(e)?r="file-text":(Ai(e)||fc(e))&&(r="layout-dashboard");let n=(0,Vo.getIcon)(r);return n?n.outerHTML:""}var Vo,My=v(()=>{Vo=require("obsidian");Nr();s0()});function l0(e,t){dr(t,!1);let[r,n]=oc(),i=()=>sc(Fa,"$showExcerpt",r),a=ft(),o=ft(),l=ft(),d=ft(),p=ze(t,"selected",8,!1),g=ze(t,"note",8),E=ze(t,"plugin",8),_=ft(null),y=ft(""),C=ft(""),k={},P=ft(null),N=ft(null),L={},H,R=ft(!1);As(async()=>{k=await Ly(E());let qe=await Py(E());L=qe.prefixToIconPack,H=qe.iconsPath,oe(R,!0)});async function B(){let qe=o0(q(C),k);qe?oe(P,await u0(qe,E(),H,L)):oe(P,c0("folder",E()));let St=o0(g().path,k);St?oe(N,await u0(St,E(),H,L)):oe(N,c0(g().path,E()))}function V(qe,St){return qe.innerHTML=St,{update(Dt){qe.innerHTML=Dt},destroy(){qe.innerHTML=""}}}let X=null,ce=null,ve=ft(null);Qt(()=>(vt(g()),q(R),lc),()=>{g()&&g().path&&q(R)&&(async()=>(oe(y,g().displayTitle||g().basename),oe(C,lc(g().path)),await B()))()}),Qt(()=>(Mn,vt(g()),vt(E()),oi.TFile),()=>{if(oe(_,null),Mn(g().path)){let qe=E().app.vault.getAbstractFileByPath(g().path);qe instanceof oi.TFile&&oe(_,E().app.vault.getResourcePath(qe))}}),Qt(()=>(vt(g()),lc,oi.setIcon,Mn,ti,Ai,fc,q(ve)),()=>{oe(y,g().displayTitle||g().basename),oe(C,lc(g().path)),X&&(0,oi.setIcon)(X,"folder-open"),ce&&(Mn(g().path)?(0,oi.setIcon)(ce,"image"):ti(g().path)?(0,oi.setIcon)(ce,"file-text"):Ai(g().path)||fc(g().path)?(0,oi.setIcon)(ce,"layout-dashboard"):(0,oi.setIcon)(ce,"file")),q(ve)&&(0,oi.setIcon)(q(ve),"corner-down-right")}),Qt(()=>(vt(E()),q(y),vt(g())),()=>{oe(a,E().textProcessor.getMatches(q(y),g().foundWords))}),Qt(()=>(vt(E()),q(C),vt(g())),()=>{oe(o,E().textProcessor.getMatches(q(C),g().foundWords))}),Qt(()=>(vt(E()),vt(g())),()=>{oe(l,E().textProcessor.makeExcerpt(g().content,g().matches[0]?.offset??-1))}),Qt(()=>{},()=>{oe(d,!1)}),Jn(),En();let Re=Br(()=>g().isEmbed?"omnisearch-result__embed":"");Rc(e,{get glyph(){return q(d)},get id(){return g().path},get cssClass(){return` ${q(Re)??""}`},get selected(){return p()},$$events:{auxclick(qe){Jr.call(this,t,qe)},click(qe){Jr.call(this,t,qe)},mousemove(qe){Jr.call(this,t,qe)}},children:(qe,St)=>{var Dt=N6(),Se=xe(Dt),et=xe(Se),je=xe(et);{var lt=rt=>{var ct=v6();ys(ct,Xt=>oe(ve,Xt),()=>q(ve)),we(rt,ct)},F=rt=>{var ct=qi(),Xt=Sr(ct);{var Er=Pr=>{var zr=T6();wa(zr,(Ct,$t)=>V?.(Ct,$t),()=>q(N)),we(Pr,zr)};tt(Xt,Pr=>{q(N)&&Pr(Er)})}we(rt,ct)};tt(je,rt=>{g().isEmbed?rt(lt):rt(F,!1)})}var K=Ye(je,2),te=xe(K);Ts(te,()=>E().textProcessor.highlightText(q(y),q(a)),!1,!1),Te(K);var fe=Ye(K,2);{var Fe=rt=>{var ct=x6(),Xt=xe(ct);Te(ct),rr(Er=>ir(Xt,`.${Er??""}`),[()=>Cs(g().path)],Br),we(rt,ct)};tt(fe,rt=>{g().displayTitle||rt(Fe)})}var Je=Ye(fe,2);{var Ue=rt=>{var ct=y6(),Xt=xe(ct);Te(ct),rr(()=>ir(Xt,`${g().matches.length??""}\xA0${(g().matches.length>1?"matches":"match")??""}`)),we(rt,ct)};tt(Je,rt=>{g().matches.length>0&&rt(Ue)})}Te(et),Te(Se);var ot=Ye(Se,2);{var ut=rt=>{var ct=w6(),Xt=xe(ct);{var Er=Ct=>{var $t=A6();wa($t,(Di,me)=>V?.(Di,me),()=>q(P)),we(Ct,$t)};tt(Xt,Ct=>{q(P)&&Ct(Er)})}var Pr=Ye(Xt,2),zr=xe(Pr);Ts(zr,()=>E().textProcessor.highlightText(q(C),q(o)),!1,!1),Te(Pr),Te(ct),we(rt,ct)};tt(ot,rt=>{q(C)&&rt(ut)})}var _t=Ye(ot,2);{var qr=rt=>{var ct=I6(),Xt=xe(ct);{var Er=Ct=>{var $t=S6(),Di=xe($t);Ts(Di,()=>E().textProcessor.highlightText(q(l),g().matches),!1,!1),Te($t),we(Ct,$t)};tt(Xt,Ct=>{i()&&Ct(Er)})}var Pr=Ye(Xt,2);{var zr=Ct=>{var $t=C6(),Di=xe($t);Te($t),rr(()=>Ki(Di,"src",q(_))),we(Ct,$t)};tt(Pr,Ct=>{q(_)&&Ct(zr)})}Te(ct),we(rt,ct)};tt(_t,rt=>{g().isEmbed||rt(qr)})}Te(Dt),we(qe,Dt)},$$slots:{default:!0}}),hr(),n()}var oi,v6,T6,x6,y6,A6,w6,S6,C6,I6,N6,Fy=v(()=>{Wn();yi();Pn();Ao();Nr();a0();oi=require("obsidian");ws();My();v6=Le(''),T6=Le(''),x6=Le(' '),y6=Le(' '),A6=Le(''),w6=Le('
    '),S6=Le('
    '),C6=Le('
    '),I6=Le('
    '),N6=Le('
    ')});var By=Pi(sd=>{sd.parse=function(e,t){if(t?t.offsets=typeof t.offsets>"u"?!0:t.offsets:t={offsets:!0},e||(e=""),e.indexOf(":")===-1&&!t.tokenize)return e;if(!t.keywords&&!t.ranges&&!t.tokenize)return e;var r={text:[]};t.offsets&&(r.offsets=[]);for(var n={},i=[],a=/(\S+:'(?:[^'\\]|\\.)*')|(\S+:"(?:[^"\\]|\\.)*")|(-?"(?:[^"\\]|\\.)*")|(-?'(?:[^'\\]|\\.)*')|\S+|\S+:\S+/g,o;(o=a.exec(e))!==null;){var _=o[0],l=_.indexOf(":");if(l!==-1){var d=_.split(":"),p=_.slice(0,l),g=_.slice(l+1);g=g.replace(/^\"|\"$|^\'|\'$/g,""),g=(g+"").replace(/\\(.?)/g,function(V,X){switch(X){case"\\":return"\\";case"0":return"\0";case"":return"";default:return X}}),i.push({keyword:p,value:g,offsetStart:o.index,offsetEnd:o.index+_.length})}else{var E=!1;_[0]==="-"&&(E=!0,_=_.slice(1)),_=_.replace(/^\"|\"$|^\'|\'$/g,""),_=(_+"").replace(/\\(.?)/g,function(V,X){switch(X){case"\\":return"\\";case"0":return"\0";case"":return"";default:return X}}),E?n.text?(n.text instanceof Array||(n.text=[n.text]),n.text.push(_)):n.text=_:i.push({text:_,offsetStart:o.index,offsetEnd:o.index+_.length})}}i.reverse();for(var _;_=i.pop();)if(_.text)r.text.push(_.text),t.offsets&&r.offsets.push(_);else{var p=_.keyword;t.keywords=t.keywords||[];var y=!1,C=!1;if(!/^-/.test(p))y=t.keywords.indexOf(p)!==-1;else if(p[0]==="-"){var k=p.slice(1);y=t.keywords.indexOf(k)!==-1,y&&(p=k,C=!0)}t.ranges=t.ranges||[];var P=t.ranges.indexOf(p)!==-1;if(y){t.offsets&&r.offsets.push({keyword:p,value:_.value,offsetStart:C?_.offsetStart+1:_.offsetStart,offsetEnd:_.offsetEnd});var N=_.value;if(N.length){var L=N.split(",");C?n[p]?n[p]instanceof Array?L.length>1?n[p]=n[p].concat(L):n[p].push(N):(n[p]=[n[p]],n[p].push(N)):L.length>1?n[p]=L:t.alwaysArray?n[p]=[N]:n[p]=N:r[p]?r[p]instanceof Array?L.length>1?r[p]=r[p].concat(L):r[p].push(N):(r[p]=[r[p]],r[p].push(N)):L.length>1?r[p]=L:t.alwaysArray?r[p]=[N]:r[p]=N}}else if(P){t.offsets&&r.offsets.push(_);var N=_.value,H=N.split("-");r[p]={},H.length===2?(r[p].from=H[0],r[p].to=H[1]):!H.length%2||(r[p].from=N)}else{var R=_.keyword+":"+_.value;r.text.push(R),t.offsets&&r.offsets.push({text:R,offsetStart:_.offsetStart,offsetEnd:_.offsetEnd})}}return r.text.length?t.tokenize||(r.text=r.text.join(" ").trim()):delete r.text,r.exclude=n,r};sd.stringify=function(e,t,r){if(t||(t={offsets:!0}),!e)return"";if(typeof e=="string")return e;if(Array.isArray(e))return e.join(" ");if(!Object.keys(e).length)return"";if(Object.keys(e).length===3&&e.text&&e.offsets&&e.exclude&&typeof e.text=="string")return e.text;r||(r="");var n=function(l){return l.indexOf(" ")>-1?JSON.stringify(l):l},i=function(l){return r+l},a=[];if(e.text){var o=[];typeof e.text=="string"?o.push(e.text):o.push.apply(o,e.text),o.length>0&&a.push(o.map(n).map(i).join(" "))}return t.keywords&&t.keywords.forEach(function(l){if(e[l]){var d=[];typeof e[l]=="string"?d.push(e[l]):d.push.apply(d,e[l]),d.length>0&&a.push(i(l+":"+d.map(n).join(",")))}}),t.ranges&&t.ranges.forEach(function(l){if(e[l]){var d=e[l].from,p=e[l].to;p&&(d=d+"-"+p),d&&a.push(i(l+":"+d))}}),e.exclude&&Object.keys(e.exclude).length>0&&a.push(sd.stringify(e.exclude,t,"-")),a.join(" ")}});var Hy=Pi((Jee,$y)=>{$y.exports=By()});var Uy,f0,ea,od=v(()=>{Nr();Uy=ln(Hy()),f0=["ext","path"],ea=class{#e;constructor(t="",r){r.ignoreDiacritics&&(t=Wi(t,r.ignoreArabicDiacritics));let n=(0,Uy.parse)(t.toLowerCase(),{tokenize:!0,keywords:f0});n.text=n.text??[],n.exclude=n.exclude??{},n.exclude.text=n.exclude.text??[],Array.isArray(n.exclude.text)||(n.exclude.text=[n.exclude.text]),n.exclude.text=n.exclude.text.filter(a=>a.length);for(let a of f0){let o=n[a];o&&(n[a]=Array.isArray(o)?o:[o]);let l=n.exclude[a];l&&(n.exclude[a]=Array.isArray(l)?l:[l])}this.query=n;let i=this.query.text.filter(a=>a.startsWith(".")).map(a=>a.slice(1));this.query.ext=[...new Set([...i,...this.query.ext??[]])],this.query.text=this.query.text.filter(a=>!a.startsWith(".")),this.#e=t.match(/"([^"]+)"/g)?.map(a=>a.replace(/"/g,""))??[]}isEmpty(){for(let t of f0)if(this.query[t]?.length||this.query.text.length)return!1;return!0}segmentsToStr(){return this.query.text.join(" ")}getTags(){return this.query.text.filter(t=>t.startsWith("#"))}getTagsWithoutHashtag(){return this.getTags().map(t=>t.replace(/^#/,""))}getExactTerms(){return[...new Set([...this.query.text.filter(t=>t.split(" ").length>1),...this.#e].map(t=>t.toLowerCase()))]}getBestStringForExcerpt(){return this.#e.length?this.#e.sort((t,r)=>r.length-t.length)[0]??"":this.segmentsToStr()}}});var Vy=Pi(ud=>{function d0(e){"@babel/helpers - typeof";return d0=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},d0(e)}(function(e,t){if(typeof define=="function"&&define.amd)define(["exports"],t);else if(typeof ud<"u")t(ud);else{var r={exports:{}};t(r.exports),e.CancelablePromise=r.exports}})(typeof globalThis<"u"?globalThis:typeof self<"u"?self:ud,function(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CancelablePromise=void 0,e.cancelable=St,e.default=void 0,e.isCancelablePromise=Dt;function t(F,K){if(typeof K!="function"&&K!==null)throw new TypeError("Super expression must either be null or a function");F.prototype=Object.create(K&&K.prototype,{constructor:{value:F,writable:!0,configurable:!0}}),Object.defineProperty(F,"prototype",{writable:!1}),K&&r(F,K)}function r(F,K){return r=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(fe,Fe){return fe.__proto__=Fe,fe},r(F,K)}function n(F){var K=o();return function(){var fe=l(F),Fe;if(K){var Je=l(this).constructor;Fe=Reflect.construct(fe,arguments,Je)}else Fe=fe.apply(this,arguments);return i(this,Fe)}}function i(F,K){if(K&&(d0(K)==="object"||typeof K=="function"))return K;if(K!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return a(F)}function a(F){if(F===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return F}function o(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function l(F){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(te){return te.__proto__||Object.getPrototypeOf(te)},l(F)}function d(F,K){var te=typeof Symbol<"u"&&F[Symbol.iterator]||F["@@iterator"];if(!te){if(Array.isArray(F)||(te=p(F))||K&&F&&typeof F.length=="number"){te&&(F=te);var fe=0,Fe=function(){};return{s:Fe,n:function(){return fe>=F.length?{done:!0}:{done:!1,value:F[fe++]}},e:function(_t){throw _t},f:Fe}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. -In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var Je=!0,Ue=!1,ot;return{s:function(){te=te.call(F)},n:function(){var _t=te.next();return Je=_t.done,_t},e:function(_t){Ue=!0,ot=_t},f:function(){try{!Je&&te.return!=null&&te.return()}finally{if(Ue)throw ot}}}}function p(F,K){if(F){if(typeof F=="string")return g(F,K);var te=Object.prototype.toString.call(F).slice(8,-1);if(te==="Object"&&F.constructor&&(te=F.constructor.name),te==="Map"||te==="Set")return Array.from(F);if(te==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(te))return g(F,K)}}function g(F,K){(K==null||K>F.length)&&(K=F.length);for(var te=0,fe=new Array(K);te`opacity: ${a*i}`}}var O6,zy=v(()=>{mt();Wr();O6=e=>e});function cd(e,t){dr(t,!1);let r=ze(t,"placeholder",8,null),n=ze(t,"placeholderProps",8,null),i="svelte-lazy-placeholder";En();var a=qi(),o=Sr(a);{var l=d=>{var p=k6();Yi(p,1,xs(i));var g=xe(p);{var E=y=>{var C=D6(),k=xe(C,!0);Te(C),rr(()=>ir(k,r())),we(y,C)},_=(y,C)=>{{var k=P=>{var N=qi(),L=Sr(N);Gp(L,r,(H,R)=>{R(H,mm(n))}),we(P,N)};tt(y,P=>{["function","object"].includes(typeof r())&&P(k)},C)}};tt(g,y=>{typeof r()=="string"?y(E):y(_,!1)})}Te(p),we(d,p)};tt(o,d=>{r()&&d(l)})}we(e,a),hr()}var D6,k6,Yy=v(()=>{Wn();yi();Pn();D6=Le("
    "),k6=Le("
    ")});function h0(e,t){dr(t,!1);let r=ft(),n=ze(t,"keep",8,!1),i=ze(t,"height",8,0),a=ze(t,"offset",8,150),o=ze(t,"fadeOption",24,()=>({delay:0,duration:400})),l=ze(t,"resetHeightDelay",8,0),d=ze(t,"onload",8,null),p=ze(t,"placeholder",8,null),g=ze(t,"placeholderProps",8,null),E=ze(t,"class",8,""),_="svelte-lazy"+(E()?" "+E():""),y="svelte-lazy-content",C=ce(),k=ft(!1),P=ft(!0);function N(F){ve(F);let K=L(F);V(K),setTimeout(()=>{K()});let te=H(F,K);return{destroy:()=>{X(K),te.unobserve(F)}}}function L(F){return Dt(te=>{let fe=F.getBoundingClientRect().top,Fe=F.getBoundingClientRect().bottom,Je=St(te)+a();fe<=Je&&Fe>0?B(F):n()||R(F)},200)}function H(F,K){let te=new IntersectionObserver(fe=>{fe[0].isIntersecting&&B(F)});return te.observe(F),te}function R(F){ve(F),oe(k,!1)}function B(F,K){q(k)||(oe(k,!0),Re(F),d()&&d()(F))}function V(F){document.addEventListener("scroll",F,!0),window.addEventListener("resize",F)}function X(F){document.removeEventListener("scroll",F,!0),window.removeEventListener("resize",F)}function ce(){return typeof i()=="number"?i()+"px":i()}function ve(F){i()&&(F.style.height=ce())}function Re(F){setTimeout(()=>{qe(F)||(F.style.height="auto")},l())}function qe(F){let K=F.querySelector("img");return K?K.complete?K.naturalHeight===0:(oe(P,!1),F.addEventListener("load",()=>{oe(P,!0),F.style.height="auto"},{capture:!0,once:!0}),F.addEventListener("error",()=>{oe(P,!0)},{capture:!0,once:!0}),!0):!1}function St(F){return F?.target?.getBoundingClientRect?F.target.getBoundingClientRect().bottom:window.innerHeight}function Dt(F,K,te){let fe,Fe,Je,Ue=null,ot=0;te||(te={});let ut=function(){ot=te.leading===!1?0:new Date,Ue=null,Je=F.apply(fe,Fe),Ue||(fe=Fe=null)};return function(_t){let qr=new Date;!ot&&te.leading===!1&&(ot=qr);let rt=K-(qr-ot);return fe=this,Fe=arguments,rt<=0||rt>K?(Ue&&(clearTimeout(Ue),Ue=null),ot=qr,Je=F.apply(fe,Fe),Ue||(fe=Fe=null)):!Ue&&te.trailing!==!1&&(Ue=setTimeout(ut,rt)),Je}}Qt(()=>q(P),()=>{oe(r,q(P)?"":"display: none")}),Jn(),En();var Se=L6();Yi(Se,1,xs(_)),ic(Se,`height: ${C??""}`);var et=xe(Se);{var je=F=>{var K=R6(),te=Sr(K);Yi(te,1,xs(y));var fe=xe(te);zi(fe,t,"default",{},Ue=>{var ot=Ju("Lazy load content");we(Ue,ot)}),Te(te);var Fe=Ye(te,2);{var Je=Ue=>{cd(Ue,{get placeholder(){return p()},get placeholderProps(){return g()}})};tt(Fe,Ue=>{!q(P)&&p()&&Ue(Je)})}rr(()=>ic(te,q(r))),im(1,te,()=>qy,()=>o()||{}),we(F,K)},lt=(F,K)=>{{var te=fe=>{cd(fe,{get placeholder(){return p()},get placeholderProps(){return g()}})};tt(F,fe=>{p()&&fe(te)},K)}};tt(et,F=>{q(k)?F(je):F(lt,!1)})}Te(Se),wa(Se,F=>N?.(F)),we(e,Se),hr()}var R6,L6,Ky=v(()=>{Wn();yi();Pn();zy();Yy();R6=Le("
    ",1),L6=Le("
    ")});function p0(e,t){dr(t,!0);let[r,n]=oc(),i=()=>sc(Ca,"$indexingStep",r),a=Xn(0),o=0,l=Xn(er(t.previousQuery??"")),d=Xn(er([])),p,g=Xn(""),E=Xn(!0),_,y=Xn(""),C=Xn(""),k=Xn(""),P=Xn(""),N=`${vn()} ${Sf()} \u21B5`,L=kn(()=>q(d)[q(a)]);vi(()=>{t.plugin.settings.openInNewPane?(oe(y,"\u21B5"),oe(C,vn()+" \u21B5"),oe(k,"Shift \u21B5"),oe(P,vn()+" Shift \u21B5")):(oe(y,vn()+" \u21B5"),oe(C,"\u21B5"),oe(k,vn()+" Shift \u21B5"),oe(P,"Shift \u21B5"))}),vi(()=>{q(l)?X():(oe(E,!1),oe(d,er([])))}),vi(()=>{switch(i()){case 1:oe(g,"Loading cache...");break;case 2:oe(g,"Reading files...");break;case 3:oe(g,"Indexing files...");break;case 4:X(),oe(g,"Updating cache...");break;default:X(),oe(g,"");break}}),As(async()=>{Me.enable("vault"),Me.on("vault","enter",ve),Me.on("vault","open-in-background",Re),Me.on("vault","create-note",je),Me.on("vault","open-in-new-pane",qe),Me.on("vault","insert-link",lt),Me.on("vault","tab",F),Me.on("vault","arrow-up",()=>K(-1)),Me.on("vault","arrow-down",()=>K(1)),Me.on("vault","prev-search-history",H),Me.on("vault","next-search-history",R),Me.on("vault","open-in-new-leaf",St),await t.plugin.notesIndexer.refreshIndex(),await X()}),mf(()=>{Me.disable("vault")});async function H(){let Ne=(await t.plugin.searchHistory.getHistory()).filter(kt=>kt);++o>=Ne.length&&(o=0),oe(l,er(Ne[o])),_?.setInputValue(q(l)??"")}async function R(){let Ne=(await t.plugin.searchHistory.getHistory()).filter(kt=>kt);--o<0&&(o=Ne.length?Ne.length-1:0),oe(l,er(Ne[o])),_?.setInputValue(q(l)??"")}let B=null;async function V(){oe(E,!0),B&&(B.cancel(),B=null),p=new ea(q(l),{ignoreDiacritics:t.plugin.settings.ignoreDiacritics,ignoreArabicDiacritics:t.plugin.settings.ignoreArabicDiacritics}),B=(0,Wy.cancelable)(new Promise(Ne=>{Ne(t.plugin.searchEngine.getSuggestions(p))})),oe(d,er(await B)),oe(a,0),await te(),oe(E,!1)}let X=Ic(V,0);function ce(Ne){q(L)&&(Ne?.ctrlKey?qe():ve(),t.modal.close())}function ve(){q(L)&&(Se(q(L)),t.modal.close())}function Re(){q(L)&&Se(q(L),!0)}function qe(){q(L)&&(Se(q(L),!0),t.modal.close())}function St(){q(L)&&(Se(q(L),!0,!0),t.modal.close())}function Dt(){q(l)&&t.plugin.searchHistory.addToHistory(q(l))}function Se(Ne,kt=!1,Rt=!1){Dt();let ur=Ne.matches?.[0]?.offset??0;Cf(t.plugin.app,Ne,ur,kt,Rt)}async function et(Ne){await je()}async function je(Ne){if(q(l)){try{await mv(t.plugin.app,q(l),Ne?.newLeaf)}catch(kt){new Si.Notice(kt.message);return}t.modal.close()}}function lt(){if(!q(L))return;let Ne=t.plugin.app.vault.getMarkdownFiles().find(ki=>ki.path===q(L).path),kt=t.plugin.app.workspace.getActiveFile(),Rt=t.plugin.app.workspace.getActiveViewOfType(Si.MarkdownView);if(!Rt?.editor){new Si.Notice("Omnisearch - Error - No active editor",3e3);return}let ur;if(Ne&&kt)ur=t.plugin.app.fileManager.generateMarkdownLink(Ne,kt.path,"",q(L).displayTitle);else{let ki=q(L).displayTitle===""?"":`|${q(L).displayTitle}`;ur=`[[${q(L).basename}.${Cs(q(L).path)}${ki}]]`}let Sn=Rt.editor.getCursor();Rt.editor.replaceRange(ur,Sn,Sn),Sn.ch+=ur.length,Rt.editor.setCursor(Sn),t.modal.close()}function F(){if(!(q(L)&&(ti(q(L)?.path)||!q(L)?.matches.length)))if(Dt(),t.modal.close(),q(L)){let Ne=t.plugin.app.vault.getAbstractFileByPath(q(L).path);Ne&&Ne instanceof Si.TFile&&new ks(t.plugin,Ne,q(l)).open()}else{let Ne=t.plugin.app.workspace.getActiveViewOfType(Si.MarkdownView);Ne?.file&&new ks(t.plugin,Ne.file,q(l)).open()}}function K(Ne){oe(a,er(wf(q(a)+Ne,q(d).length))),te()}async function te(){await Ei(),q(L)&&activeWindow.document.querySelector(`[data-result-id="${q(L).path}"]`)?.scrollIntoView({behavior:"auto",block:"nearest"})}var fe=q6(),Fe=Sr(fe);ys(mc(Fe,{get plugin(){return t.plugin},get initialValue(){return q(l)},placeholder:"Omnisearch - Vault",$$events:{input:Ne=>oe(l,er(Ne.detail))},children:(Ne,kt)=>{var Rt=B6(),ur=xe(Rt);{var Sn=cr=>{var Zt=M6();pr("click",Zt,et),we(cr,Zt)};tt(ur,cr=>{t.plugin.settings.showCreateButton&&cr(Sn)})}var ki=Ye(ur,2);{var Eu=cr=>{var Zt=F6();pr("click",Zt,F),we(cr,Zt)};tt(ki,cr=>{Si.Platform.isMobile&&cr(Eu)})}Te(Rt),we(Ne,Rt)},$$slots:{default:!0}}),Ne=>_=Ne,()=>_);var Je=Ye(Fe,2);{var Ue=Ne=>{var kt=$6(),Rt=xe(kt);Te(kt),rr(()=>ir(Rt,`\u23F3 Work in progress: ${q(g)??""}`)),we(Ne,kt)};tt(Je,Ne=>{q(g)&&Ne(Ue)})}var ot=Ye(Je,2);gc(ot,{children:(Ne,kt)=>{var Rt=V6(),ur=Sr(Rt);rc(ur,17,()=>q(d),tc,(Zt,la,Cn)=>{h0(Zt,{height:100,offset:500,keep:!0,fadeOption:{delay:0,duration:0},children:(Yn,Kn)=>{let un=kn(()=>Cn===q(a));l0(Yn,{get plugin(){return t.plugin},get selected(){return q(un)},get note(){return q(la)},$$events:{mousemove:Xa=>oe(a,er(Cn)),click:ce,auxclick:Xa=>{Xa.button==1&&qe()}}})},$$slots:{default:!0}})});var Sn=Ye(ur,2),ki=xe(Sn);{var Eu=Zt=>{var la=U6(),Cn=Ye(Sr(la));{var Yn=Kn=>{var un=H6();wr(2),we(Kn,un)};tt(Cn,Kn=>{t.plugin.settings.simpleSearch&&q(l).split(yf).some(un=>un.length<3)&&Kn(Yn)})}we(Zt,la)},cr=(Zt,la)=>{{var Cn=Yn=>{var Kn=Ju("Searching...");we(Yn,Kn)};tt(Zt,Yn=>{q(E)&&Yn(Cn)},la)}};tt(ki,Zt=>{!q(d).length&&q(l)&&!q(E)?Zt(Eu):Zt(cr,!1)})}Te(Sn),we(Ne,Rt)},$$slots:{default:!0}});var ut=Ye(ot,2),_t=Ye(xe(ut),2),qr=xe(_t),rt=xe(qr);Te(qr),wr(2),Te(_t);var ct=Ye(_t,2),Xt=xe(ct),Er=xe(Xt,!0);Te(Xt),wr(2),Te(ct);var Pr=Ye(ct,4),zr=xe(Pr),Ct=xe(zr,!0);Te(zr),wr(2),Te(Pr);var $t=Ye(Pr,2),Di=xe($t);Di.textContent=N,wr(2),Te($t);var me=Ye($t,2),gu=xe(me),Ih=xe(gu);Te(gu),wr(2),Te(me);var ca=Ye(me,2),nt=xe(ca),Qa=xe(nt,!0);Te(nt),wr(2),Te(ca);var _u=Ye(ca,2),fi=xe(_u),Nh=xe(fi,!0);Te(fi),wr(2),Te(_u);var bu=Ye(_u,2),bl=xe(bu),Oh=xe(bl);Te(bl),wr(2),Te(bu);var Ks=Ye(bu,2),on=xe(Ks),El=xe(on);Te(on),wr(2),Te(Ks),wr(2),Te(ut),rr((Ne,kt,Rt,ur)=>{ir(rt,`${Ne??""} \u2191\u2193`),ir(Er,q(C)),ir(Ct,q(y)),ir(Ih,`${kt??""} o`),ir(Qa,q(P)),ir(Nh,q(k)),ir(Oh,`${Rt??""} \u21B5`),ir(El,`${ur??""} g`)},[Sf,vn,Sf,vn]),we(e,fe),hr(),n()}var Si,Wy,M6,F6,B6,$6,H6,U6,V6,q6,Gy=v(()=>{Wn();Pn();Si=require("obsidian");ws();Sm();Cm();en();_c();Nr();Lc();Fy();od();Wy=ln(Vy());Oc();Ky();M6=Le(""),F6=Le(""),B6=Le('
    '),$6=Le('
    '),H6=Le(`
    You have enabled "Simpler Search" in the settings, try to type more - characters.`,1),U6=Le("We found 0 results for your search here. ",1),V6=Le('
    ',1),q6=Le('
    \u2191\u2193to navigate
    to cycle history
    to open
    Tab to switch to In-File Search
    to open in a new pane
    to open in a new split
    to open in the background
    to create
    to create in a new pane
    to insert a link
    to toggle excerpts
    Escto close
    ',1)});function m0(e,t){dr(t,!1);let r=ft(),n=ze(t,"plugin",8),i=ze(t,"offset",8),a=ze(t,"note",8),o=ze(t,"index",8,0),l=ze(t,"selected",8,!1);Qt(()=>(vt(n()),vt(a()),vt(i())),()=>{oe(r,n().textProcessor.makeExcerpt(a()?.content??"",i()))}),Jn(),En();let d=Br(()=>o().toString());Rc(e,{get id(){return q(d)},get selected(){return l()},$$events:{auxclick(p){Jr.call(this,t,p)},click(p){Jr.call(this,t,p)},mousemove(p){Jr.call(this,t,p)}},children:(p,g)=>{var E=z6(),_=xe(E);Ts(_,()=>n().textProcessor.highlightText(q(r),a().matches),!1,!1),Te(E),we(p,E)},$$slots:{default:!0}}),hr()}var z6,Qy=v(()=>{Wn();yi();Pn();a0();z6=Le('
    ')});function g0(e,t){dr(t,!1);let r=ze(t,"plugin",8),n=ze(t,"modal",8),i=ze(t,"parent",8,null),a=ze(t,"singleFilePath",8,""),o=ze(t,"previousQuery",8),l=ft(),d=ft([]),p=ft(0),g=ft(),E=ft();As(()=>{Me.enable("infile"),Me.on("infile","enter",N),Me.on("infile","open-in-new-pane",P),Me.on("infile","arrow-up",()=>C(-1)),Me.on("infile","arrow-down",()=>C(1)),Me.on("infile","tab",L)}),mf(()=>{Me.disable("infile")});function _(Se){let et=[],je=-1,lt=0;for(;++lt<100;){let F=y(Se,je,uc);if(!F.length)break;je=F.last().offset,et.push(F)}return et}function y(Se,et,je){let lt=Se.find(F=>F.offset>et);return lt?Se.filter(F=>F.offset>et&&F.offset<=lt.offset+je):[]}function C(Se){oe(p,wf(q(p)+Se,q(d).length)),k()}async function k(){await Ei(),document.querySelector(`[data-result-id="${q(p)}"]`)?.scrollIntoView({behavior:"auto",block:"nearest"})}async function P(){return N(!0)}async function N(Se=!1){if(q(g)){n().close(),i()&&i().close();let et=r().textProcessor.stringsToRegex(q(g).foundWords);et.exec(q(g).content),await Cf(r().app,q(g),et.lastIndex,Se);let je=r().app.workspace.getActiveViewOfType(ld.MarkdownView);if(!je)return;let lt=q(d)[q(p)]??0,F=je.editor.offsetToPos(lt);F.ch=0,je.editor.setCursor(F),je.editor.scrollIntoView({from:{line:F.line-10,ch:0},to:{line:F.line+10,ch:0}})}}function L(){new ta(r(),q(l)??o()).open(),n().close()}Qt(()=>vt(o()),()=>{oe(l,o()??"")}),Qt(()=>(q(l),q(E),ea,vt(r()),vt(a())),()=>{(async()=>(q(l)&&(oe(E,new ea(q(l),{ignoreDiacritics:r().settings.ignoreDiacritics,ignoreArabicDiacritics:r().settings.ignoreArabicDiacritics})),oe(g,(await r().searchEngine.getSuggestions(q(E),{singleFilePath:a()}))[0]??null)),oe(p,0),await k()))()}),Qt(()=>(q(g),q(E)),()=>{if(q(g)){let Se=_(q(g).matches),et=q(E).getExactTerms();et.length&&(Se=Se.filter(je=>et.every(lt=>je.some(F=>F.match.includes(lt))))),oe(d,Se.map(je=>Math.round(je.first().offset)))}}),Jn(),En();var H=Q6(),R=Sr(H);mc(R,{get plugin(){return r()},placeholder:"Omnisearch - File",get initialValue(){return o()},$$events:{input:Se=>oe(l,Se.detail)},children:(Se,et)=>{var je=K6(),lt=xe(je);{var F=K=>{var te=Y6();pr("click",te,L),we(K,te)};tt(lt,K=>{ld.Platform.isMobile&&K(F)})}Te(je),we(Se,je)},$$slots:{default:!0}});var B=Ye(R,2);gc(B,{children:(Se,et)=>{var je=qi(),lt=Sr(je);{var F=te=>{var fe=qi(),Fe=Sr(fe);rc(Fe,1,()=>q(d),tc,(Je,Ue,ot)=>{let ut=Br(()=>ot===q(p));m0(Je,{get plugin(){return r()},get offset(){return q(Ue)},get note(){return q(g)},index:ot,get selected(){return q(ut)},$$events:{mousemove:_t=>oe(p,ot),click:_t=>N(_t.ctrlKey),auxclick:_t=>{_t.button==1&&N(!0)}}})}),we(te,fe)},K=te=>{var fe=j6();we(te,fe)};tt(lt,te=>{q(d).length&&q(g)?te(F):te(K,!1)})}we(Se,je)},$$slots:{default:!0}});var V=Ye(B,2),X=Ye(xe(V),6),ce=Ye(xe(X),2);{var ve=Se=>{var et=W6();we(Se,et)},Re=Se=>{var et=G6();we(Se,et)};tt(ce,Se=>{i()?Se(ve):Se(Re,!1)})}Te(X);var qe=Ye(X,2),St=xe(qe),Dt=xe(St);Te(St),wr(2),Te(qe),Te(V),rr(Se=>ir(Dt,`${Se??""} \u21B5`),[vn],Br),we(e,H),hr()}var ld,Y6,K6,j6,W6,G6,Q6,Xy=v(()=>{Wn();yi();Pn();Sm();en();Nr();ws();ld=require("obsidian");Cm();Lc();Qy();od();_c();Y6=Le(""),K6=Le('
    '),j6=Le('
    We found 0 results for your search here.
    '),W6=Le("to go back to Vault Search"),G6=Le("to close"),Q6=Le('
    \u2191\u2193to navigate
    \u21B5to open
    tab to switch to Vault Search
    esc
    to open in a new pane
    ',1)});var dd,fd,ta,ks,Lc=v(()=>{dd=require("obsidian");Gy();Xy();en();ws();fd=class extends dd.Modal{constructor(t){super(t.app);let r=t.settings;this.modalEl.replaceChildren(),this.modalEl.addClass("omnisearch-modal","prompt"),this.modalEl.removeClass("modal"),this.modalEl.tabIndex=-1,this.scope.register([],"ArrowDown",d=>{d.preventDefault(),Me.emit("arrow-down")}),this.scope.register([],"ArrowUp",d=>{d.preventDefault(),Me.emit("arrow-up")});for(let d of[{k:"J",dir:"down"},{k:"K",dir:"up"}])for(let p of["Ctrl","Mod"])this.scope.register([p],d.k,g=>{r.vimLikeNavigationShortcut&&Me.emit("arrow-"+d.dir)});for(let d of[{k:"N",dir:"down"},{k:"P",dir:"up"}])for(let p of["Ctrl","Mod"])this.scope.register([p],d.k,g=>{r.vimLikeNavigationShortcut&&Me.emit("arrow-"+d.dir)});let n,i,a,o,l=["Mod","Alt"];r.openInNewPane?(n=["Mod"],i=[],a=["Mod","Shift"],o=["Shift"]):(n=[],i=["Mod"],a=["Shift"],o=["Mod","Shift"]),this.scope.register(i,"Enter",d=>{d.preventDefault(),Me.emit("open-in-new-pane")}),this.scope.register(l,"Enter",d=>{d.preventDefault(),Me.emit("open-in-new-leaf")}),this.scope.register(["Alt"],"Enter",d=>{d.preventDefault(),Me.emit("insert-link")}),this.scope.register(a,"Enter",d=>{d.preventDefault(),Me.emit("create-note")}),this.scope.register(o,"Enter",d=>{d.preventDefault(),Me.emit("create-note",{newLeaf:!0})}),this.scope.register(n,"Enter",d=>{vm()||(d.preventDefault(),Me.emit("enter"))}),this.scope.register(["Mod"],"O",d=>{vm()||(d.preventDefault(),Me.emit("open-in-background"))}),this.scope.register([],"Tab",d=>{d.preventDefault(),Me.emit("tab")}),this.scope.register(["Alt"],"ArrowDown",d=>{d.preventDefault(),Me.emit("next-search-history")}),this.scope.register(["Alt"],"ArrowUp",d=>{d.preventDefault(),Me.emit("prev-search-history")}),this.scope.register(["Mod"],"G",d=>{Me.emit(xf.ToggleExcerpts)})}},ta=class extends fd{constructor(t,r){super(t);let n=t.app.workspace.getActiveViewOfType(dd.MarkdownView)?.editor.getSelection();t.searchHistory.getHistory().then(i=>{let a=t.settings.showPreviousQueryResults?i[0]:null,o=Es(p0,{target:this.modalEl,props:{plugin:t,modal:this,previousQuery:r||n||a||""}});this.onClose=()=>{Eo(o)}})}},ks=class extends fd{constructor(t,r,n="",i){super(t);let a=Es(g0,{target:this.modalEl,props:{plugin:t,modal:this,singleFilePath:r.path,parent:i,previousQuery:n}});i&&i.containerEl.toggleVisibility(!1),this.onClose=()=>{i&&i.containerEl.toggleVisibility(!0),Eo(a)}}}});function X6(e,t){return t.map(r=>{let{score:n,path:i,basename:a,foundWords:o,matches:l,content:d}=r,p=e.textProcessor.makeExcerpt(d,l[0]?.offset??-1);return{score:n,vault:e.app.vault.getName(),path:i,basename:a,foundWords:o,matches:l.map(E=>({match:E.match,offset:E.offset})),excerpt:p}})}function eA(){Jy=!0,hd.forEach(e=>e())}function tA(e){if(Zy)return;Zy=!0,e.registerObsidianProtocolHandler("omnisearch",r=>{new ta(e,r.query).open()});let t=_0(e);globalThis.omnisearch=t,e.app.plugins.plugins.omnisearch.api=t}function _0(e){return{async search(t){let r=new ea(t,{ignoreDiacritics:e.settings.ignoreDiacritics,ignoreArabicDiacritics:e.settings.ignoreArabicDiacritics}),n=await e.searchEngine.getSuggestions(r);return X6(e,n)},registerOnIndexed(t){hd.push(t),Jy&&t()},unregisterOnIndexed(t){hd=hd.filter(r=>r!==t)},refreshIndex:e.notesIndexer.refreshIndex}}var Jy,hd,Zy,b0=v(()=>{od();Lc();Jy=!1,hd=[];Zy=!1});var rA=Pi((E0,v0)=>{(function(e,t){typeof E0=="object"&&typeof v0<"u"?v0.exports=t():typeof define=="function"&&define.amd?define(t):(e=typeof globalThis<"u"?globalThis:e||self,e.Dexie=t())})(E0,function(){"use strict";var e=function(s,u){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(f,h){f.__proto__=h}||function(f,h){for(var m in h)Object.prototype.hasOwnProperty.call(h,m)&&(f[m]=h[m])},e(s,u)};function t(s,u){if(typeof u!="function"&&u!==null)throw new TypeError("Class extends value "+String(u)+" is not a constructor or null");e(s,u);function f(){this.constructor=s}s.prototype=u===null?Object.create(u):(f.prototype=u.prototype,new f)}var r=function(){return r=Object.assign||function(u){for(var f,h=1,m=arguments.length;h"u"?a:Reflect.ownKeys)(u).forEach(function(f){y(s,f,u[f])})}var _=Object.defineProperty;function y(s,u,f,h){_(s,u,l(f&&g(f,"get")&&typeof f.get=="function"?{get:f.get,set:f.set,configurable:!0}:{value:f,configurable:!0,writable:!0},h))}function C(s){return{from:function(u){return s.prototype=Object.create(u.prototype),y(s.prototype,"constructor",s),{extend:E.bind(null,s.prototype)}}}}var k=Object.getOwnPropertyDescriptor;function P(s,u){var f=k(s,u),h;return f||(h=d(s))&&P(h,u)}var N=[].slice;function L(s,u,f){return N.call(s,u,f)}function H(s,u){return u(s)}function R(s){if(!s)throw new Error("Assertion Failed")}function B(s){i.setImmediate?setImmediate(s):setTimeout(s,0)}function V(s,u){return s.reduce(function(f,h,m){var b=u(h,m);return b&&(f[b[0]]=b[1]),f},{})}function X(s,u){if(typeof u=="string"&&g(s,u))return s[u];if(!u)return s;if(typeof u!="string"){for(var f=[],h=0,m=u.length;h=0&&s.splice(f,1),f>=0}var ot={};function ut(s){var u,f,h,m;if(arguments.length===1){if(o(s))return s.slice();if(this===ot&&typeof s=="string")return[s];if(m=Je(s)){for(f=[];h=m.next(),!h.done;)f.push(h.value);return f}if(s==null)return[s];if(u=s.length,typeof u=="number"){for(f=new Array(u);u--;)f[u]=s[u];return f}return[s]}for(u=arguments.length,f=new Array(u);u--;)f[u]=arguments[u];return f}var _t=typeof Symbol<"u"?function(s){return s[Symbol.toStringTag]==="AsyncFunction"}:function(){return!1},qr=["Modify","Bulk","OpenFailed","VersionChange","Schema","Upgrade","InvalidTable","MissingAPI","NoSuchDatabase","InvalidArgument","SubTransaction","Unsupported","Internal","DatabaseClosed","PrematureCommit","ForeignAwait"],rt=["Unknown","Constraint","Data","TransactionInactive","ReadOnly","Version","NotFound","InvalidState","InvalidAccess","Abort","Timeout","QuotaExceeded","Syntax","DataClone"],ct=qr.concat(rt),Xt={VersionChanged:"Database version changed by other database connection",DatabaseClosed:"Database has been closed",Abort:"Transaction aborted",TransactionInactive:"Transaction has already completed or failed",MissingAPI:"IndexedDB API missing. Please visit https://tinyurl.com/y2uuvskb"};function Er(s,u){this.name=s,this.message=u}C(Er).from(Error).extend({toString:function(){return this.name+": "+this.message}});function Pr(s,u){return s+". Errors: "+Object.keys(u).map(function(f){return u[f].toString()}).filter(function(f,h,m){return m.indexOf(f)===h}).join(` -`)}function zr(s,u,f,h){this.failures=u,this.failedKeys=h,this.successCount=f,this.message=Pr(s,u)}C(zr).from(Er);function Ct(s,u){this.name="BulkError",this.failures=Object.keys(u).map(function(f){return u[f]}),this.failuresByPos=u,this.message=Pr(s,this.failures)}C(Ct).from(Er);var $t=ct.reduce(function(s,u){return s[u]=u+"Error",s},{}),Di=Er,me=ct.reduce(function(s,u){var f=u+"Error";function h(m,b){this.name=f,m?typeof m=="string"?(this.message="".concat(m).concat(b?` - `+b:""),this.inner=b||null):typeof m=="object"&&(this.message="".concat(m.name," ").concat(m.message),this.inner=m):(this.message=Xt[u]||f,this.inner=null)}return C(h).from(Di),s[u]=h,s},{});me.Syntax=SyntaxError,me.Type=TypeError,me.Range=RangeError;var gu=rt.reduce(function(s,u){return s[u+"Error"]=me[u],s},{});function Ih(s,u){if(!s||s instanceof Er||s instanceof TypeError||s instanceof SyntaxError||!s.name||!gu[s.name])return s;var f=new gu[s.name](u||s.message,s);return"stack"in s&&y(f,"stack",{get:function(){return this.inner.stack}}),f}var ca=ct.reduce(function(s,u){return["Syntax","Type","Range"].indexOf(u)===-1&&(s[u+"Error"]=me[u]),s},{});ca.ModifyError=zr,ca.DexieError=Er,ca.BulkError=Ct;function nt(){}function Qa(s){return s}function _u(s,u){return s==null||s===Qa?u:function(f){return u(s(f))}}function fi(s,u){return function(){s.apply(this,arguments),u.apply(this,arguments)}}function Nh(s,u){return s===nt?u:function(){var f=s.apply(this,arguments);f!==void 0&&(arguments[0]=f);var h=this.onsuccess,m=this.onerror;this.onsuccess=null,this.onerror=null;var b=u.apply(this,arguments);return h&&(this.onsuccess=this.onsuccess?fi(h,this.onsuccess):h),m&&(this.onerror=this.onerror?fi(m,this.onerror):m),b!==void 0?b:f}}function bu(s,u){return s===nt?u:function(){s.apply(this,arguments);var f=this.onsuccess,h=this.onerror;this.onsuccess=this.onerror=null,u.apply(this,arguments),f&&(this.onsuccess=this.onsuccess?fi(f,this.onsuccess):f),h&&(this.onerror=this.onerror?fi(h,this.onerror):h)}}function bl(s,u){return s===nt?u:function(f){var h=s.apply(this,arguments);l(f,h);var m=this.onsuccess,b=this.onerror;this.onsuccess=null,this.onerror=null;var T=u.apply(this,arguments);return m&&(this.onsuccess=this.onsuccess?fi(m,this.onsuccess):m),b&&(this.onerror=this.onerror?fi(b,this.onerror):b),h===void 0?T===void 0?void 0:T:l(h,T)}}function Oh(s,u){return s===nt?u:function(){return u.apply(this,arguments)===!1?!1:s.apply(this,arguments)}}function Ks(s,u){return s===nt?u:function(){var f=s.apply(this,arguments);if(f&&typeof f.then=="function"){for(var h=this,m=arguments.length,b=new Array(m);m--;)b[m]=arguments[m];return f.then(function(){return u.apply(h,b)})}return u.apply(this,arguments)}}var on=typeof location<"u"&&/^(http|https):\/\/(localhost|127\.0\.0\.1)/.test(location.href);function El(s,u){on=s}var Ne={},kt=100,Rt=typeof Promise>"u"?[]:function(){var s=Promise.resolve();if(typeof crypto>"u"||!crypto.subtle)return[s,d(s),s];var u=crypto.subtle.digest("SHA-512",new Uint8Array([0]));return[u,d(u),s]}(),ur=Rt[0],Sn=Rt[1],ki=Rt[2],Eu=Sn&&Sn.then,cr=ur&&ur.constructor,Zt=!!ki;function la(){queueMicrotask(jS)}var Cn=function(s,u){vu.push([s,u]),Kn&&(la(),Kn=!1)},Yn=!0,Kn=!0,un=[],Xa=[],Dh=Qa,fa={id:"global",global:!0,ref:0,unhandleds:[],onunhandled:nt,pgp:!1,env:{},finalize:nt},be=fa,vu=[],Za=0,vl=[];function de(s){if(typeof this!="object")throw new TypeError("Promises must be constructed via new");this._listeners=[],this._lib=!1;var u=this._PSD=be;if(typeof s!="function"){if(s!==Ne)throw new TypeError("Not a function");this._state=arguments[1],this._value=arguments[2],this._state===!1&&Rh(this,this._value);return}this._state=null,this._value=null,++u.ref,s_(this,s)}var kh={get:function(){var s=be,u=Al;function f(h,m){var b=this,T=!s.global&&(s!==be||u!==Al),A=T&&!ha(),S=new de(function(O,$){Lh(b,new a_(c_(h,s,T,A),c_(m,s,T,A),O,$,s))});return this._consoleTask&&(S._consoleTask=this._consoleTask),S}return f.prototype=Ne,f},set:function(s){y(this,"then",s&&s.prototype===Ne?kh:{get:function(){return s},set:kh.set})}};E(de.prototype,{then:kh,_then:function(s,u){Lh(this,new a_(null,null,s,u,be))},catch:function(s){if(arguments.length===1)return this.then(null,s);var u=arguments[0],f=arguments[1];return typeof u=="function"?this.then(null,function(h){return h instanceof u?f(h):Tl(h)}):this.then(null,function(h){return h&&h.name===u?f(h):Tl(h)})},finally:function(s){return this.then(function(u){return de.resolve(s()).then(function(){return u})},function(u){return de.resolve(s()).then(function(){return Tl(u)})})},timeout:function(s,u){var f=this;return s<1/0?new de(function(h,m){var b=setTimeout(function(){return m(new me.Timeout(u))},s);f.then(h,m).finally(clearTimeout.bind(null,b))}):this}}),typeof Symbol<"u"&&Symbol.toStringTag&&y(de.prototype,Symbol.toStringTag,"Dexie.Promise"),fa.env=u_();function a_(s,u,f,h,m){this.onFulfilled=typeof s=="function"?s:null,this.onRejected=typeof u=="function"?u:null,this.resolve=f,this.reject=h,this.psd=m}E(de,{all:function(){var s=ut.apply(null,arguments).map(wl);return new de(function(u,f){s.length===0&&u([]);var h=s.length;s.forEach(function(m,b){return de.resolve(m).then(function(T){s[b]=T,--h||u(s)},f)})})},resolve:function(s){if(s instanceof de)return s;if(s&&typeof s.then=="function")return new de(function(f,h){s.then(f,h)});var u=new de(Ne,!0,s);return u},reject:Tl,race:function(){var s=ut.apply(null,arguments).map(wl);return new de(function(u,f){s.map(function(h){return de.resolve(h).then(u,f)})})},PSD:{get:function(){return be},set:function(s){return be=s}},totalEchoes:{get:function(){return Al}},newPSD:da,usePSD:Ja,scheduler:{get:function(){return Cn},set:function(s){Cn=s}},rejectionMapper:{get:function(){return Dh},set:function(s){Dh=s}},follow:function(s,u){return new de(function(f,h){return da(function(m,b){var T=be;T.unhandleds=[],T.onunhandled=b,T.finalize=fi(function(){var A=this;WS(function(){A.unhandleds.length===0?m():b(A.unhandleds[0])})},T.finalize),s()},u,f,h)})}}),cr&&(cr.allSettled&&y(de,"allSettled",function(){var s=ut.apply(null,arguments).map(wl);return new de(function(u){s.length===0&&u([]);var f=s.length,h=new Array(f);s.forEach(function(m,b){return de.resolve(m).then(function(T){return h[b]={status:"fulfilled",value:T}},function(T){return h[b]={status:"rejected",reason:T}}).then(function(){return--f||u(h)})})})}),cr.any&&typeof AggregateError<"u"&&y(de,"any",function(){var s=ut.apply(null,arguments).map(wl);return new de(function(u,f){s.length===0&&f(new AggregateError([]));var h=s.length,m=new Array(h);s.forEach(function(b,T){return de.resolve(b).then(function(A){return u(A)},function(A){m[T]=A,--h||f(new AggregateError(m))})})})}),cr.withResolvers&&(de.withResolvers=cr.withResolvers));function s_(s,u){try{u(function(f){if(s._state===null){if(f===s)throw new TypeError("A promise cannot be resolved with itself.");var h=s._lib&&js();f&&typeof f.then=="function"?s_(s,function(m,b){f instanceof de?f._then(m,b):f.then(m,b)}):(s._state=!0,s._value=f,o_(s)),h&&Ws()}},Rh.bind(null,s))}catch(f){Rh(s,f)}}function Rh(s,u){if(Xa.push(u),s._state===null){var f=s._lib&&js();u=Dh(u),s._state=!1,s._value=u,GS(s),o_(s),f&&Ws()}}function o_(s){var u=s._listeners;s._listeners=[];for(var f=0,h=u.length;f0;)for(s=vu,vu=[],f=s.length,u=0;u0);Yn=!0,Kn=!0}function Ph(){var s=un;un=[],s.forEach(function(h){h._PSD.onunhandled.call(null,h._value,h)});for(var u=vl.slice(0),f=u.length;f;)u[--f]()}function WS(s){function u(){s(),vl.splice(vl.indexOf(u),1)}vl.push(u),++Za,Cn(function(){--Za===0&&Ph()},[])}function GS(s){un.some(function(u){return u._value===s._value})||un.push(s)}function QS(s){for(var u=un.length;u;)if(un[--u]._value===s._value){un.splice(u,1);return}}function Tl(s){return new de(Ne,!1,s)}function At(s,u){var f=be;return function(){var h=js(),m=be;try{return pa(f,!0),s.apply(this,arguments)}catch(b){u&&u(b)}finally{pa(m,!1),h&&Ws()}}}var Jt={awaits:0,echoes:0,id:0},XS=0,xl=[],yl=0,Al=0,ZS=0;function da(s,u,f,h){var m=be,b=Object.create(m);b.parent=m,b.ref=0,b.global=!1,b.id=++ZS,fa.env,b.env=Zt?{Promise:de,PromiseProp:{value:de,configurable:!0,writable:!0},all:de.all,race:de.race,allSettled:de.allSettled,any:de.any,resolve:de.resolve,reject:de.reject}:{},u&&l(b,u),++m.ref,b.finalize=function(){--this.parent.ref||this.parent.finalize()};var T=Ja(b,s,f,h);return b.ref===0&&b.finalize(),T}function Gs(){return Jt.id||(Jt.id=++XS),++Jt.awaits,Jt.echoes+=kt,Jt.id}function ha(){return Jt.awaits?(--Jt.awaits===0&&(Jt.id=0),Jt.echoes=Jt.awaits*kt,!0):!1}(""+Eu).indexOf("[native code]")===-1&&(Gs=ha=nt);function wl(s){return Jt.echoes&&s&&s.constructor===cr?(Gs(),s.then(function(u){return ha(),u},function(u){return ha(),Lt(u)})):s}function JS(s){++Al,(!Jt.echoes||--Jt.echoes===0)&&(Jt.echoes=Jt.awaits=Jt.id=0),xl.push(be),pa(s,!0)}function eC(){var s=xl[xl.length-1];xl.pop(),pa(s,!1)}function pa(s,u){var f=be;if((u?Jt.echoes&&(!yl++||s!==be):yl&&(!--yl||s!==be))&&queueMicrotask(u?JS.bind(null,s):eC),s!==be&&(be=s,f===fa&&(fa.env=u_()),Zt)){var h=fa.env.Promise,m=s.env;(f.global||s.global)&&(Object.defineProperty(i,"Promise",m.PromiseProp),h.all=m.all,h.race=m.race,h.resolve=m.resolve,h.reject=m.reject,m.allSettled&&(h.allSettled=m.allSettled),m.any&&(h.any=m.any))}}function u_(){var s=i.Promise;return Zt?{Promise:s,PromiseProp:Object.getOwnPropertyDescriptor(i,"Promise"),all:s.all,race:s.race,allSettled:s.allSettled,any:s.any,resolve:s.resolve,reject:s.reject}:{}}function Ja(s,u,f,h,m){var b=be;try{return pa(s,!0),u(f,h,m)}finally{pa(b,!1)}}function c_(s,u,f,h){return typeof s!="function"?s:function(){var m=be;f&&Gs(),pa(u,!0);try{return s.apply(this,arguments)}finally{pa(m,!1),h&&queueMicrotask(ha)}}}function Mh(s){Promise===cr&&Jt.echoes===0?yl===0?s():enqueueNativeMicroTask(s):setTimeout(s,0)}var Lt=de.reject;function Fh(s,u,f,h){if(!s.idbdb||!s._state.openComplete&&!be.letThrough&&!s._vip){if(s._state.openComplete)return Lt(new me.DatabaseClosed(s._state.dbOpenError));if(!s._state.isBeingOpened){if(!s._state.autoOpen)return Lt(new me.DatabaseClosed);s.open().catch(nt)}return s._state.dbReadyPromise.then(function(){return Fh(s,u,f,h)})}else{var m=s._createTransaction(u,f,s._dbSchema);try{m.create(),s._state.PR1398_maxLoop=3}catch(b){return b.name===$t.InvalidState&&s.isOpen()&&--s._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),s.close({disableAutoOpen:!1}),s.open().then(function(){return Fh(s,u,f,h)})):Lt(b)}return m._promise(u,function(b,T){return da(function(){return be.trans=m,h(b,T,m)})}).then(function(b){if(u==="readwrite")try{m.idbtrans.commit()}catch{}return u==="readonly"?b:m._completion.then(function(){return b})})}}var l_="4.0.11",es=String.fromCharCode(65535),Bh=-1/0,Ri="Invalid key provided. Keys must be of type string, number, Date or Array.",f_="String expected.",Qs=[],Sl="__dbnames",$h="readonly",Hh="readwrite";function ts(s,u){return s?u?function(){return s.apply(this,arguments)&&u.apply(this,arguments)}:s:u}var d_={type:3,lower:-1/0,lowerOpen:!1,upper:[[]],upperOpen:!1};function Cl(s){return typeof s=="string"&&!/\./.test(s)?function(u){return u[s]===void 0&&s in u&&(u=F(u),delete u[s]),u}:function(u){return u}}function h_(){throw me.Type()}function We(s,u){try{var f=p_(s),h=p_(u);if(f!==h)return f==="Array"?1:h==="Array"?-1:f==="binary"?1:h==="binary"?-1:f==="string"?1:h==="string"?-1:f==="Date"?1:h!=="Date"?NaN:-1;switch(f){case"number":case"Date":case"string":return s>u?1:s=0})){for(var D=0;D0){var b=m.valueMapper,T=Il(m,m.table.core.schema);return m.table.core.query({trans:h,limit:m.limit,values:!0,query:{index:T,range:m.range}}).then(function(S){var O=S.result;return b?O.map(b):O})}else{var A=[];return Nl(m,function(S){return A.push(S)},h,m.table.core).then(function(){return A})}},u)},s.prototype.offset=function(u){var f=this._ctx;return u<=0?this:(f.offset+=u,Xs(f)?Vh(f,function(){var h=u;return function(m,b){return h===0?!0:h===1?(--h,!1):(b(function(){m.advance(h),h=0}),!1)}}):Vh(f,function(){var h=u;return function(){return--h<0}}),this)},s.prototype.limit=function(u){return this._ctx.limit=Math.min(this._ctx.limit,u),Vh(this._ctx,function(){var f=u;return function(h,m,b){return--f<=0&&m(b),f>=0}},!0),this},s.prototype.until=function(u,f){return Uh(this._ctx,function(h,m,b){return u(h.value)?(m(b),f):!0}),this},s.prototype.first=function(u){return this.limit(1).toArray(function(f){return f[0]}).then(u)},s.prototype.last=function(u){return this.reverse().first(u)},s.prototype.filter=function(u){return Uh(this._ctx,function(f){return u(f.value)}),iC(this._ctx,u),this},s.prototype.and=function(u){return this.filter(u)},s.prototype.or=function(u){return new this.db.WhereClause(this._ctx.table,u,this)},s.prototype.reverse=function(){return this._ctx.dir=this._ctx.dir==="prev"?"next":"prev",this._ondirectionchange&&this._ondirectionchange(this._ctx.dir),this},s.prototype.desc=function(){return this.reverse()},s.prototype.eachKey=function(u){var f=this._ctx;return f.keysOnly=!f.isMatch,this.each(function(h,m){u(m.key,m)})},s.prototype.eachUniqueKey=function(u){return this._ctx.unique="unique",this.eachKey(u)},s.prototype.eachPrimaryKey=function(u){var f=this._ctx;return f.keysOnly=!f.isMatch,this.each(function(h,m){u(m.primaryKey,m)})},s.prototype.keys=function(u){var f=this._ctx;f.keysOnly=!f.isMatch;var h=[];return this.each(function(m,b){h.push(b.key)}).then(function(){return h}).then(u)},s.prototype.primaryKeys=function(u){var f=this._ctx;if(f.dir==="next"&&Xs(f,!0)&&f.limit>0)return this._read(function(m){var b=Il(f,f.table.core.schema);return f.table.core.query({trans:m,values:!1,limit:f.limit,query:{index:b,range:f.range}})}).then(function(m){var b=m.result;return b}).then(u);f.keysOnly=!f.isMatch;var h=[];return this.each(function(m,b){h.push(b.primaryKey)}).then(function(){return h}).then(u)},s.prototype.uniqueKeys=function(u){return this._ctx.unique="unique",this.keys(u)},s.prototype.firstKey=function(u){return this.limit(1).keys(function(f){return f[0]}).then(u)},s.prototype.lastKey=function(u){return this.reverse().firstKey(u)},s.prototype.distinct=function(){var u=this._ctx,f=u.index&&u.table.schema.idxByName[u.index];if(!f||!f.multi)return this;var h={};return Uh(this._ctx,function(m){var b=m.primaryKey.toString(),T=g(h,b);return h[b]=!0,!T}),this},s.prototype.modify=function(u){var f=this,h=this._ctx;return this._write(function(m){var b;if(typeof u=="function")b=u;else{var T=a(u),A=T.length;b=function(Q){for(var Z=!1,re=0;re0&&S.mutate({trans:m,type:"add",values:le}).then(function(ye){for(var It in ye.failures)pe.splice(parseInt(It),1);J(le.length,ye)})).then(function(){return(Ae.length>0||Z&&typeof u=="object")&&S.mutate({trans:m,type:"put",keys:Ve,values:Ae,criteria:Z,changeSpec:typeof u!="function"&&u,isAdditionalChunk:G>0}).then(function(ye){return J(Ae.length,ye)})}).then(function(){return(pe.length>0||Z&&u===qh)&&S.mutate({trans:m,type:"delete",keys:pe,criteria:Z,isAdditionalChunk:G>0}).then(function(ye){return J(pe.length,ye)})}).then(function(){return Q.length>G+ue&&re(G+W)})})};return re(0).then(function(){if(M.length>0)throw new zr("Error modifying one or more objects",M,z,j);return Q.length})})})},s.prototype.delete=function(){var u=this._ctx,f=u.range;return Xs(u)&&(u.isPrimKey||f.type===3)?this._write(function(h){var m=u.table.core.schema.primaryKey,b=f;return u.table.core.count({trans:h,query:{index:m,range:b}}).then(function(T){return u.table.core.mutate({trans:h,type:"deleteRange",range:b}).then(function(A){var S=A.failures;A.lastResult,A.results;var O=A.numFailures;if(O)throw new zr("Could not delete some values",Object.keys(S).map(function($){return S[$]}),T-O);return T-O})})}):this.modify(qh)},s}(),qh=function(s,u){return u.value=null};function sC(s){return xu(aC.prototype,function(f,h){this.db=s;var m=d_,b=null;if(h)try{m=h()}catch(O){b=O}var T=f._ctx,A=T.table,S=A.hook.reading.fire;this._ctx={table:A,index:T.index,isPrimKey:!T.index||A.schema.primKey.keyPath&&T.index===A.schema.primKey.name,range:m,keysOnly:!1,dir:"next",unique:"",algorithm:null,filter:null,replayFilter:null,justLimit:!0,isMatch:null,offset:0,limit:1/0,error:b,or:T.or,valueMapper:S!==Qa?S:null}})}function oC(s,u){return su?-1:s===u?0:1}function cn(s,u,f){var h=s instanceof v_?new s.Collection(s):s;return h._ctx.error=f?new f(u):new TypeError(u),h}function Zs(s){return new s.Collection(s,function(){return E_("")}).limit(0)}function cC(s){return s==="next"?function(u){return u.toUpperCase()}:function(u){return u.toLowerCase()}}function lC(s){return s==="next"?function(u){return u.toLowerCase()}:function(u){return u.toUpperCase()}}function fC(s,u,f,h,m,b){for(var T=Math.min(s.length,h.length),A=-1,S=0;S=0?s.substr(0,A)+u[A]+f.substr(A+1):null;m(s[S],O)<0&&(A=S)}return T0)&&(re=ue)}return j(re!==null?function(){z.continue(re+$)}:J),!1}),ie}function ma(s,u,f,h){return{type:2,lower:s,upper:u,lowerOpen:f,upperOpen:h}}function E_(s){return{type:1,lower:s,upper:s}}var v_=function(){function s(){}return Object.defineProperty(s.prototype,"Collection",{get:function(){return this._ctx.table.db.Collection},enumerable:!1,configurable:!0}),s.prototype.between=function(u,f,h,m){h=h!==!1,m=m===!0;try{return this._cmp(u,f)>0||this._cmp(u,f)===0&&(h||m)&&!(h&&m)?Zs(this):new this.Collection(this,function(){return ma(u,f,!h,!m)})}catch{return cn(this,Ri)}},s.prototype.equals=function(u){return u==null?cn(this,Ri):new this.Collection(this,function(){return E_(u)})},s.prototype.above=function(u){return u==null?cn(this,Ri):new this.Collection(this,function(){return ma(u,void 0,!0)})},s.prototype.aboveOrEqual=function(u){return u==null?cn(this,Ri):new this.Collection(this,function(){return ma(u,void 0,!1)})},s.prototype.below=function(u){return u==null?cn(this,Ri):new this.Collection(this,function(){return ma(void 0,u,!1,!0)})},s.prototype.belowOrEqual=function(u){return u==null?cn(this,Ri):new this.Collection(this,function(){return ma(void 0,u)})},s.prototype.startsWith=function(u){return typeof u!="string"?cn(this,f_):this.between(u,u+es,!0,!0)},s.prototype.startsWithIgnoreCase=function(u){return u===""?this.startsWith(u):Ol(this,function(f,h){return f.indexOf(h[0])===0},[u],es)},s.prototype.equalsIgnoreCase=function(u){return Ol(this,function(f,h){return f===h[0]},[u],"")},s.prototype.anyOfIgnoreCase=function(){var u=ut.apply(ot,arguments);return u.length===0?Zs(this):Ol(this,function(f,h){return h.indexOf(f)!==-1},u,"")},s.prototype.startsWithAnyOfIgnoreCase=function(){var u=ut.apply(ot,arguments);return u.length===0?Zs(this):Ol(this,function(f,h){return h.some(function(m){return f.indexOf(m)===0})},u,es)},s.prototype.anyOf=function(){var u=this,f=ut.apply(ot,arguments),h=this._cmp;try{f.sort(h)}catch{return cn(this,Ri)}if(f.length===0)return Zs(this);var m=new this.Collection(this,function(){return ma(f[0],f[f.length-1])});m._ondirectionchange=function(T){h=T==="next"?u._ascending:u._descending,f.sort(h)};var b=0;return m._addAlgorithm(function(T,A,S){for(var O=T.key;h(O,f[b])>0;)if(++b,b===f.length)return A(S),!1;return h(O,f[b])===0?!0:(A(function(){T.continue(f[b])}),!1)}),m},s.prototype.notEqual=function(u){return this.inAnyRange([[Bh,u],[u,this.db._maxKey]],{includeLowers:!1,includeUppers:!1})},s.prototype.noneOf=function(){var u=ut.apply(ot,arguments);if(u.length===0)return new this.Collection(this);try{u.sort(this._ascending)}catch{return cn(this,Ri)}var f=u.reduce(function(h,m){return h?h.concat([[h[h.length-1][1],m]]):[[Bh,m]]},null);return f.push([u[u.length-1],this.db._maxKey]),this.inAnyRange(f,{includeLowers:!1,includeUppers:!1})},s.prototype.inAnyRange=function(u,f){var h=this,m=this._cmp,b=this._ascending,T=this._descending,A=this._min,S=this._max;if(u.length===0)return Zs(this);if(!u.every(function(G){return G[0]!==void 0&&G[1]!==void 0&&b(G[0],G[1])<=0}))return cn(this,"First argument to inAnyRange() must be an Array of two-value Arrays [lower,upper] where upper must not be lower than lower",me.InvalidArgument);var O=!f||f.includeLowers!==!1,$=f&&f.includeUppers===!0;function D(G,ue){for(var he=0,le=G.length;he0){Ae[0]=A(Ae[0],ue[0]),Ae[1]=S(Ae[1],ue[1]);break}}return he===le&&G.push(ue),G}var W=b;function ie(G,ue){return W(G[0],ue[0])}var M;try{M=u.reduce(D,[]),M.sort(ie)}catch{return cn(this,Ri)}var z=0,j=$?function(G){return b(G,M[z][1])>0}:function(G){return b(G,M[z][1])>=0},J=O?function(G){return T(G,M[z][0])>0}:function(G){return T(G,M[z][0])>=0};function Q(G){return!j(G)&&!J(G)}var Z=j,re=new this.Collection(this,function(){return ma(M[0][0],M[M.length-1][1],!O,!$)});return re._ondirectionchange=function(G){G==="next"?(Z=j,W=b):(Z=J,W=T),M.sort(ie)},re._addAlgorithm(function(G,ue,he){for(var le=G.key;Z(le);)if(++z,z===M.length)return ue(he),!1;return Q(le)?!0:(h._cmp(le,M[z][1])===0||h._cmp(le,M[z][0])===0||ue(function(){W===b?G.continue(M[z][0]):G.continue(M[z][1])}),!1)}),re},s.prototype.startsWithAnyOf=function(){var u=ut.apply(ot,arguments);return u.every(function(f){return typeof f=="string"})?u.length===0?Zs(this):this.inAnyRange(u.map(function(f){return[f,f+es]})):cn(this,"startsWithAnyOf() only works with strings")},s}();function dC(s){return xu(v_.prototype,function(f,h,m){if(this.db=s,this._ctx={table:f,index:h===":id"?null:h,or:m},this._cmp=this._ascending=We,this._descending=function(b,T){return We(T,b)},this._max=function(b,T){return We(b,T)>0?b:T},this._min=function(b,T){return We(b,T)<0?b:T},this._IDBKeyRange=s._deps.IDBKeyRange,!this._IDBKeyRange)throw new me.MissingAPI})}function di(s){return At(function(u){return Au(u),s(u.target.error),!1})}function Au(s){s.stopPropagation&&s.stopPropagation(),s.preventDefault&&s.preventDefault()}var wu="storagemutated",zh="x-storagemutated-1",ga=Tu(null,wu),hC=function(){function s(){}return s.prototype._lock=function(){return R(!be.global),++this._reculock,this._reculock===1&&!be.global&&(be.lockOwnerFor=this),this},s.prototype._unlock=function(){if(R(!be.global),--this._reculock===0)for(be.global||(be.lockOwnerFor=null);this._blockedFuncs.length>0&&!this._locked();){var u=this._blockedFuncs.shift();try{Ja(u[1],u[0])}catch{}}return this},s.prototype._locked=function(){return this._reculock&&be.lockOwnerFor!==this},s.prototype.create=function(u){var f=this;if(!this.mode)return this;var h=this.db.idbdb,m=this.db._state.dbOpenError;if(R(!this.idbtrans),!u&&!h)switch(m&&m.name){case"DatabaseClosedError":throw new me.DatabaseClosed(m);case"MissingAPIError":throw new me.MissingAPI(m.message,m);default:throw new me.OpenFailed(m)}if(!this.active)throw new me.TransactionInactive;return R(this._completion._state===null),u=this.idbtrans=u||(this.db.core?this.db.core.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability}):h.transaction(this.storeNames,this.mode,{durability:this.chromeTransactionDurability})),u.onerror=At(function(b){Au(b),f._reject(u.error)}),u.onabort=At(function(b){Au(b),f.active&&f._reject(new me.Abort(u.error)),f.active=!1,f.on("abort").fire(b)}),u.oncomplete=At(function(){f.active=!1,f._resolve(),"mutatedParts"in u&&ga.storagemutated.fire(u.mutatedParts)}),this},s.prototype._promise=function(u,f,h){var m=this;if(u==="readwrite"&&this.mode!=="readwrite")return Lt(new me.ReadOnly("Transaction is readonly"));if(!this.active)return Lt(new me.TransactionInactive);if(this._locked())return new de(function(T,A){m._blockedFuncs.push([function(){m._promise(u,f,h).then(T,A)},be])});if(h)return da(function(){var T=new de(function(A,S){m._lock();var O=f(A,S,m);O&&O.then&&O.then(A,S)});return T.finally(function(){return m._unlock()}),T._lib=!0,T});var b=new de(function(T,A){var S=f(T,A,m);S&&S.then&&S.then(T,A)});return b._lib=!0,b},s.prototype._root=function(){return this.parent?this.parent._root():this},s.prototype.waitFor=function(u){var f=this._root(),h=de.resolve(u);if(f._waitingFor)f._waitingFor=f._waitingFor.then(function(){return h});else{f._waitingFor=h,f._waitingQueue=[];var m=f.idbtrans.objectStore(f.storeNames[0]);(function T(){for(++f._spinCount;f._waitingQueue.length;)f._waitingQueue.shift()();f._waitingFor&&(m.get(-1/0).onsuccess=T)})()}var b=f._waitingFor;return new de(function(T,A){h.then(function(S){return f._waitingQueue.push(At(T.bind(null,S)))},function(S){return f._waitingQueue.push(At(A.bind(null,S)))}).finally(function(){f._waitingFor===b&&(f._waitingFor=null)})})},s.prototype.abort=function(){this.active&&(this.active=!1,this.idbtrans&&this.idbtrans.abort(),this._reject(new me.Abort))},s.prototype.table=function(u){var f=this._memoizedTables||(this._memoizedTables={});if(g(f,u))return f[u];var h=this.schema[u];if(!h)throw new me.NotFound("Table "+u+" not part of transaction");var m=new this.db.Table(u,h,this);return m.core=this.db.core.table(u),f[u]=m,m},s}();function pC(s){return xu(hC.prototype,function(f,h,m,b,T){var A=this;this.db=s,this.mode=f,this.storeNames=h,this.schema=m,this.chromeTransactionDurability=b,this.idbtrans=null,this.on=Tu(this,"complete","error","abort"),this.parent=T||null,this.active=!0,this._reculock=0,this._blockedFuncs=[],this._resolve=null,this._reject=null,this._waitingFor=null,this._waitingQueue=null,this._spinCount=0,this._completion=new de(function(S,O){A._resolve=S,A._reject=O}),this._completion.then(function(){A.active=!1,A.on.complete.fire()},function(S){var O=A.active;return A.active=!1,A.on.error.fire(S),A.parent?A.parent._reject(S):O&&A.idbtrans&&A.idbtrans.abort(),Lt(S)})})}function Yh(s,u,f,h,m,b,T){return{name:s,keyPath:u,unique:f,multi:h,auto:m,compound:b,src:(f&&!T?"&":"")+(h?"*":"")+(m?"++":"")+T_(u)}}function T_(s){return typeof s=="string"?s:s?"["+[].join.call(s,"+")+"]":""}function Kh(s,u,f){return{name:s,primKey:u,indexes:f,mappedClass:null,idxByName:V(f,function(h){return[h.name,h]})}}function mC(s){return s.length===1?s[0]:s}var Su=function(s){try{return s.only([[]]),Su=function(){return[[]]},[[]]}catch{return Su=function(){return es},es}};function jh(s){return s==null?function(){}:typeof s=="string"?gC(s):function(u){return X(u,s)}}function gC(s){var u=s.split(".");return u.length===1?function(f){return f[s]}:function(f){return X(f,s)}}function x_(s){return[].slice.call(s)}var _C=0;function Cu(s){return s==null?":id":typeof s=="string"?s:"[".concat(s.join("+"),"]")}function bC(s,u,f){function h(D,W){var ie=x_(D.objectStoreNames);return{schema:{name:D.name,tables:ie.map(function(M){return W.objectStore(M)}).map(function(M){var z=M.keyPath,j=M.autoIncrement,J=o(z),Q=z==null,Z={},re={name:M.name,primaryKey:{name:null,isPrimaryKey:!0,outbound:Q,compound:J,keyPath:z,autoIncrement:j,unique:!0,extractKey:jh(z)},indexes:x_(M.indexNames).map(function(G){return M.index(G)}).map(function(G){var ue=G.name,he=G.unique,le=G.multiEntry,Ae=G.keyPath,Ve=o(Ae),pe={name:ue,compound:Ve,keyPath:Ae,unique:he,multiEntry:le,extractKey:jh(Ae)};return Z[Cu(Ae)]=pe,pe}),getIndexByKeyPath:function(G){return Z[Cu(G)]}};return Z[":id"]=re.primaryKey,z!=null&&(Z[Cu(z)]=re.primaryKey),re})},hasGetAll:ie.length>0&&"getAll"in W.objectStore(ie[0])&&!(typeof navigator<"u"&&/Safari/.test(navigator.userAgent)&&!/(Chrome\/|Edge\/)/.test(navigator.userAgent)&&[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]<604)}}function m(D){if(D.type===3)return null;if(D.type===4)throw new Error("Cannot convert never type to IDBKeyRange");var W=D.lower,ie=D.upper,M=D.lowerOpen,z=D.upperOpen,j=W===void 0?ie===void 0?null:u.upperBound(ie,!!z):ie===void 0?u.lowerBound(W,!!M):u.bound(W,ie,!!M,!!z);return j}function b(D){var W=D.name;function ie(j){var J=j.trans,Q=j.type,Z=j.keys,re=j.values,G=j.range;return new Promise(function(ue,he){ue=At(ue);var le=J.objectStore(W),Ae=le.keyPath==null,Ve=Q==="put"||Q==="add";if(!Ve&&Q!=="delete"&&Q!=="deleteRange")throw new Error("Invalid operation type: "+Q);var pe=(Z||re||{length:1}).length;if(Z&&re&&Z.length!==re.length)throw new Error("Given keys array must have same length as given values array.");if(pe===0)return ue({numFailures:0,failures:{},results:[],lastResult:void 0});var Be,Ce=[],Xe=[],ye=0,It=function(pi){++ye,Au(pi)};if(Q==="deleteRange"){if(G.type===4)return ue({numFailures:ye,failures:Xe,results:[],lastResult:void 0});G.type===3?Ce.push(Be=le.clear()):Ce.push(Be=le.delete(m(G)))}else{var Tr=Ve?Ae?[re,Z]:[re,null]:[Z,null],hi=Tr[0],Yr=Tr[1];if(Ve)for(var In=0;In=u});if(A.length===0)return de.resolve();A.forEach(function(O){m.push(function(){var $=T,D=O._cfg.dbschema;Pl(s,$,h),Pl(s,D,h),T=s._dbSchema=D;var W=Gh($,D);W.add.forEach(function(Q){Qh(h,Q[0],Q[1].primKey,Q[1].indexes)}),W.change.forEach(function(Q){if(Q.recreate)throw new me.Upgrade("Not yet support for changing primary key");var Z=h.objectStore(Q.name);Q.add.forEach(function(re){return Rl(Z,re)}),Q.change.forEach(function(re){Z.deleteIndex(re.name),Rl(Z,re)}),Q.del.forEach(function(re){return Z.deleteIndex(re)})});var ie=O._cfg.contentUpgrade;if(ie&&O._cfg.version>u){Dl(s,h),f._memoizedTables={};var M=Re(D);W.del.forEach(function(Q){M[Q]=$[Q]}),Wh(s,[s.Transaction.prototype]),kl(s,[s.Transaction.prototype],a(M),M),f.schema=M;var z=_t(ie);z&&Gs();var j,J=de.follow(function(){if(j=ie(f),j&&z){var Q=ha.bind(null,null);j.then(Q,Q)}});return j&&typeof j.then=="function"?de.resolve(j):J.then(function(){return j})}}),m.push(function($){var D=O._cfg.dbschema;SC(D,$),Wh(s,[s.Transaction.prototype]),kl(s,[s.Transaction.prototype],s._storeNames,s._dbSchema),f.schema=s._dbSchema}),m.push(function($){s.idbdb.objectStoreNames.contains("$meta")&&(Math.ceil(s.idbdb.version/10)===O._cfg.version?(s.idbdb.deleteObjectStore("$meta"),delete s._dbSchema.$meta,s._storeNames=s._storeNames.filter(function(D){return D!=="$meta"})):$.objectStore("$meta").put(O._cfg.version,"version"))})});function S(){return m.length?de.resolve(m.shift()(f.idbtrans)).then(S):de.resolve()}return S().then(function(){y_(T,h)})}function Gh(s,u){var f={del:[],add:[],change:[]},h;for(h in s)u[h]||f.del.push(h);for(h in u){var m=s[h],b=u[h];if(!m)f.add.push([h,b]);else{var T={name:h,def:b,recreate:!1,del:[],add:[],change:[]};if(""+(m.primKey.keyPath||"")!=""+(b.primKey.keyPath||"")||m.primKey.auto!==b.primKey.auto)T.recreate=!0,f.change.push(T);else{var A=m.idxByName,S=b.idxByName,O=void 0;for(O in A)S[O]||T.del.push(O);for(O in S){var $=A[O],D=S[O];$?$.src!==D.src&&T.change.push(D):T.add.push(D)}(T.del.length>0||T.add.length>0||T.change.length>0)&&f.change.push(T)}}}return f}function Qh(s,u,f,h){var m=s.db.createObjectStore(u,f.keyPath?{keyPath:f.keyPath,autoIncrement:f.auto}:{autoIncrement:f.auto});return h.forEach(function(b){return Rl(m,b)}),m}function y_(s,u){a(s).forEach(function(f){u.db.objectStoreNames.contains(f)||(on&&console.debug("Dexie: Creating missing table",f),Qh(u,f,s[f].primKey,s[f].indexes))})}function SC(s,u){[].slice.call(u.db.objectStoreNames).forEach(function(f){return s[f]==null&&u.db.deleteObjectStore(f)})}function Rl(s,u){s.createIndex(u.name,u.keyPath,{unique:u.unique,multiEntry:u.multi})}function Ll(s,u,f){var h={},m=L(u.objectStoreNames,0);return m.forEach(function(b){for(var T=f.objectStore(b),A=T.keyPath,S=Yh(T_(A),A||"",!0,!1,!!T.autoIncrement,A&&typeof A!="string",!0),O=[],$=0;$1?u:s}:{d:0});else{var f=new vr;return s&&"d"in s&&l(f,s),f}};E(vr.prototype,(ep={add:function(s){return Nu(this,s),this},addKey:function(s){return Iu(this,s,s),this},addKeys:function(s){var u=this;return s.forEach(function(f){return Iu(u,f,f)}),this},hasKey:function(s){var u=Ml(this).next(s).value;return u&&We(u.from,s)<=0&&We(u.to,s)>=0}},ep[Fe]=function(){return Ml(this)},ep));function Iu(s,u,f){var h=We(u,f);if(!isNaN(h)){if(h>0)throw RangeError();if(tp(s))return l(s,{from:u,to:f,d:1});var m=s.l,b=s.r;if(We(f,s.from)<0)return m?Iu(m,u,f):s.l={from:u,to:f,d:1,l:null,r:null},S_(s);if(We(u,s.to)>0)return b?Iu(b,u,f):s.r={from:u,to:f,d:1,l:null,r:null},S_(s);We(u,s.from)<0&&(s.from=u,s.l=null,s.d=b?b.d+1:1),We(f,s.to)>0&&(s.to=f,s.r=null,s.d=s.l?s.l.d+1:1);var T=!s.r;m&&!s.l&&Nu(s,m),b&&T&&Nu(s,b)}}function Nu(s,u){function f(h,m){var b=m.from,T=m.to,A=m.l,S=m.r;Iu(h,b,T),A&&f(h,A),S&&f(h,S)}tp(u)||f(s,u)}function w_(s,u){var f=Ml(u),h=f.next();if(h.done)return!1;for(var m=h.value,b=Ml(s),T=b.next(m.from),A=T.value;!h.done&&!T.done;){if(We(A.from,m.to)<=0&&We(A.to,m.from)>=0)return!0;We(m.from,A.from)<0?m=(h=f.next(A.from)).value:A=(T=b.next(m.from)).value}return!1}function Ml(s){var u=tp(s)?null:{s:0,n:s};return{next:function(f){for(var h=arguments.length>0;u;)switch(u.s){case 0:if(u.s=1,h)for(;u.n.l&&We(f,u.n.from)<0;)u={up:u,n:u.n.l,s:1};else for(;u.n.l;)u={up:u,n:u.n.l,s:1};case 1:if(u.s=2,!h||We(f,u.n.to)<=0)return{value:u.n,done:!1};case 2:if(u.n.r){u.s=3,u={up:u,n:u.n.r,s:0};continue}case 3:u=u.up}return{done:!0}}}}function S_(s){var u,f,h=(((u=s.r)===null||u===void 0?void 0:u.d)||0)-(((f=s.l)===null||f===void 0?void 0:f.d)||0),m=h>1?"r":h<-1?"l":"";if(m){var b=m==="r"?"l":"r",T=r({},s),A=s[m];s.from=A.from,s.to=A.to,s[m]=A[m],T[m]=A[b],s[b]=T,T.d=C_(T)}s.d=C_(s)}function C_(s){var u=s.r,f=s.l;return(u?f?Math.max(u.d,f.d):u.d:f?f.d:0)+1}function Fl(s,u){return a(u).forEach(function(f){s[f]?Nu(s[f],u[f]):s[f]=et(u[f])}),s}function rp(s,u){return s.all||u.all||Object.keys(s).some(function(f){return u[f]&&w_(u[f],s[f])})}var rs={},np={},ip=!1;function Bl(s,u){Fl(np,s),ip||(ip=!0,setTimeout(function(){ip=!1;var f=np;np={},ap(f,!1)},0))}function ap(s,u){u===void 0&&(u=!1);var f=new Set;if(s.all)for(var h=0,m=Object.values(rs);hMath.pow(2,62)?0:z.oldVersion;O=J<1,s.idbdb=M.result,b&&yC(s,S),xC(s,J/10,S,W)}},W),M.onsuccess=At(function(){S=null;var z=s.idbdb=M.result,j=L(z.objectStoreNames);if(j.length>0)try{var J=z.transaction(mC(j),"readonly");if(u.autoSchema)CC(s,z,J);else if(Pl(s,s._dbSchema,J),!IC(s,J)&&!b)return console.warn("Dexie SchemaDiff: Schema was extended without increasing the number passed to db.version(). Dexie will add missing parts and increment native version number to workaround this."),z.close(),m=z.version+1,b=!0,D($());Dl(s,J)}catch{}Qs.push(s),z.onversionchange=At(function(Q){u.vcFired=!0,s.on("versionchange").fire(Q)}),z.onclose=At(function(Q){s.on("close").fire(Q)}),O&&kC(s._deps,ie),D()},W)}).catch(function(D){switch(D?.name){case"UnknownError":if(u.PR1398_maxLoop>0)return u.PR1398_maxLoop--,console.warn("Dexie: Workaround for Chrome UnknownError on open()"),$();break;case"VersionError":if(m>0)return m=0,$();break}return de.reject(D)})};return de.race([h,(typeof navigator>"u"?de.resolve():LC()).then($)]).then(function(){return T(),u.onReadyBeingFired=[],de.resolve(Jh(function(){return s.on.ready.fire(s.vip)})).then(function D(){if(u.onReadyBeingFired.length>0){var W=u.onReadyBeingFired.reduce(Ks,nt);return u.onReadyBeingFired=[],de.resolve(Jh(function(){return W(s.vip)})).then(D)}})}).finally(function(){u.openCanceller===h&&(u.onReadyBeingFired=null,u.isBeingOpened=!1)}).catch(function(D){u.dbOpenError=D;try{S&&S.abort()}catch{}return h===u.openCanceller&&s._close(),Lt(D)}).finally(function(){u.openComplete=!0,A()}).then(function(){if(O){var D={};s.tables.forEach(function(W){W.schema.indexes.forEach(function(ie){ie.name&&(D["idb://".concat(s.name,"/").concat(W.name,"/").concat(ie.name)]=new vr(-1/0,[[[]]]))}),D["idb://".concat(s.name,"/").concat(W.name,"/")]=D["idb://".concat(s.name,"/").concat(W.name,"/:dels")]=new vr(-1/0,[[[]]])}),ga(wu).fire(D),ap(D,!0)}return s})}function sp(s){var u=function(T){return s.next(T)},f=function(T){return s.throw(T)},h=b(u),m=b(f);function b(T){return function(A){var S=T(A),O=S.value;return S.done?O:!O||typeof O.then!="function"?o(O)?Promise.all(O).then(h,m):h(O):O.then(h,m)}}return b(u)()}function MC(s,u,f){var h=arguments.length;if(h<2)throw new me.InvalidArgument("Too few arguments");for(var m=new Array(h-1);--h;)m[h-1]=arguments[h];f=m.pop();var b=St(m);return[s,b,f]}function N_(s,u,f,h,m){return de.resolve().then(function(){var b=be.transless||be,T=s._createTransaction(u,f,s._dbSchema,h);T.explicit=!0;var A={trans:T,transless:b};if(h)T.idbtrans=h.idbtrans;else try{T.create(),T.idbtrans._explicit=!0,s._state.PR1398_maxLoop=3}catch(D){return D.name===$t.InvalidState&&s.isOpen()&&--s._state.PR1398_maxLoop>0?(console.warn("Dexie: Need to reopen db"),s.close({disableAutoOpen:!1}),s.open().then(function(){return N_(s,u,f,null,m)})):Lt(D)}var S=_t(m);S&&Gs();var O,$=de.follow(function(){if(O=m.call(T,T),O)if(S){var D=ha.bind(null,null);O.then(D,D)}else typeof O.next=="function"&&typeof O.throw=="function"&&(O=sp(O))},A);return(O&&typeof O.then=="function"?de.resolve(O).then(function(D){return T.active?D:Lt(new me.PrematureCommit("Transaction committed too early. See http://bit.ly/2kdckMn"))}):$.then(function(){return O})).then(function(D){return h&&T._resolve(),T._completion.then(function(){return D})}).catch(function(D){return T._reject(D),Lt(D)})})}function $l(s,u,f){for(var h=o(s)?s.slice():[s],m=0;m0,ue=r(r({},J),{name:G?"".concat(Q,"(virtual-from:").concat(J.name,")"):J.name,lowLevelIndex:J,isVirtual:G,keyTail:j,keyLength:re,extractKey:jh(z),unique:!G&&J.unique});if(Z.push(ue),ue.isPrimaryKey||b.push(ue),re>1){var he=re===2?z[0]:z.slice(0,re-1);T(he,j+1,J)}return Z.sort(function(le,Ae){return le.keyTail-Ae.keyTail}),ue}var A=T(h.primaryKey.keyPath,0,h.primaryKey);m[":id"]=[A];for(var S=0,O=h.indexes;S0?Promise.reject(Z.failures[0]):Q.length0:We(s,u.lower)>=0}function YC(s,u){return u.upper===void 0?!0:u.upperOpen?We(s,u.upper)<0:We(s,u.upper)<=0}function cp(s,u){return zC(s,u)&&YC(s,u)}function L_(s,u,f,h,m,b){if(!f||f.length===0)return s;var T=u.query.index,A=T.multiEntry,S=u.query.range,O=h.schema.primaryKey,$=O.extractKey,D=T.extractKey,W=(T.lowLevelIndex||T).extractKey,ie=f.reduce(function(M,z){var j=M,J=[];if(z.type==="add"||z.type==="put")for(var Q=new vr,Z=z.values.length-1;Z>=0;--Z){var re=z.values[Z],G=$(re);if(!Q.hasKey(G)){var ue=D(re);(A&&o(ue)?ue.some(function(pe){return cp(pe,S)}):cp(ue,S))&&(Q.addKey(G),J.push(re))}}switch(z.type){case"add":{var he=new vr().addKeys(u.values?M.map(function(pe){return $(pe)}):M);j=M.concat(u.values?J.filter(function(pe){var Be=$(pe);return he.hasKey(Be)?!1:(he.addKey(Be),!0)}):J.map(function(pe){return $(pe)}).filter(function(pe){return he.hasKey(pe)?!1:(he.addKey(pe),!0)}));break}case"put":{var le=new vr().addKeys(z.values.map(function(pe){return $(pe)}));j=M.filter(function(pe){return!le.hasKey(u.values?$(pe):pe)}).concat(u.values?J:J.map(function(pe){return $(pe)}));break}case"delete":var Ae=new vr().addKeys(z.keys);j=M.filter(function(pe){return!Ae.hasKey(u.values?$(pe):pe)});break;case"deleteRange":var Ve=z.range;j=M.filter(function(pe){return!cp($(pe),Ve)});break}return j},s);return ie===s?s:(ie.sort(function(M,z){return We(W(M),W(z))||We($(M),$(z))}),u.limit&&u.limit<1/0&&(ie.length>u.limit?ie.length=u.limit:s.length===u.limit&&ie.length=0}function GC(s,u,f,h){var m=rs["idb://".concat(s,"/").concat(u)];if(!m)return[];var b=m.queries[f];if(!b)return[null,!1,m,null];var T=h.query?h.query.index.name:null,A=b[T||""];if(!A)return[null,!1,m,null];switch(f){case"query":var S=A.find(function(D){return D.req.limit===h.limit&&D.req.values===h.values&&P_(D.req.query.range,h.query.range)});if(S)return[S,!0,m,A];var O=A.find(function(D){var W="limit"in D.req?D.req.limit:1/0;return W>=h.limit&&(h.values?D.req.values:!0)&&WC(D.req.query.range,h.query.range)});return[O,!1,m,A];case"count":var $=A.find(function(D){return P_(D.req.query.range,h.query.range)});return[$,!!$,m,A]}}function QC(s,u,f,h){s.subscribers.add(f),h.addEventListener("abort",function(){s.subscribers.delete(f),s.subscribers.size===0&&XC(s,u)})}function XC(s,u){setTimeout(function(){s.subscribers.size===0&&Ue(u,s)},3e3)}var ZC={stack:"dbcore",level:0,name:"Cache",create:function(s){var u=s.schema.name,f=r(r({},s),{transaction:function(h,m,b){var T=s.transaction(h,m,b);if(m==="readwrite"){var A=new AbortController,S=A.signal,O=function($){return function(){if(A.abort(),m==="readwrite"){for(var D=new Set,W=0,ie=h;W0){z.optimisticOps=z.optimisticOps.filter(function(Xe){return Xe.trans!==T});for(var le=0,Ae=Object.values(z.queries.query);le=50||up(b,A).some(function(D){return D==null}))?$.then(function(D){var W=r(r({},A),{values:A.values.map(function(M,z){var j;if(D.failures[z])return M;var J=!((j=b.keyPath)===null||j===void 0)&&j.includes(".")?F(M):r({},M);return ce(J,b.keyPath,D.results[z]),J})}),ie=R_(O,W,D);O.optimisticOps.push(ie),queueMicrotask(function(){return A.mutatedParts&&Bl(A.mutatedParts)})}):(O.optimisticOps.push(A),A.mutatedParts&&Bl(A.mutatedParts),$.then(function(D){if(D.numFailures>0){Ue(O.optimisticOps,A);var W=R_(O,A,D);W&&O.optimisticOps.push(W),A.mutatedParts&&Bl(A.mutatedParts)}}),$.catch(function(){Ue(O.optimisticOps,A),A.mutatedParts&&Bl(A.mutatedParts)})),$},query:function(A){var S;if(!D_(be,m)||!k_("query",A))return m.query(A);var O=((S=be.trans)===null||S===void 0?void 0:S.db._options.cache)==="immutable",$=be,D=$.requery,W=$.signal,ie=GC(u,h,"query",A),M=ie[0],z=ie[1],j=ie[2],J=ie[3];if(M&&z)M.obsSet=A.obsSet;else{var Q=m.query(A).then(function(Z){var re=Z.result;if(M&&(M.res=re),O){for(var G=0,ue=re.length;G0?console.warn("Another connection wants to upgrade database '".concat(h.name,"'. Closing db now to resume the upgrade.")):console.warn("Another connection wants to delete database '".concat(h.name,"'. Closing db now to resume the delete request.")),h.close({disableAutoOpen:!1})}),this.on("blocked",function(S){!S.newVersion||S.newVersion=0&&Qs.splice(f,1),this.idbdb){try{this.idbdb.close()}catch{}this.idbdb=null}u.isBeingOpened||(u.dbReadyPromise=new de(function(h){u.dbReadyResolve=h}),u.openCanceller=new de(function(h,m){u.cancelOpen=m}))},s.prototype.close=function(u){var f=u===void 0?{disableAutoOpen:!0}:u,h=f.disableAutoOpen,m=this._state;h?(m.isBeingOpened&&m.cancelOpen(new me.DatabaseClosed),this._close(),m.autoOpen=!1,m.dbOpenError=new me.DatabaseClosed):(this._close(),m.autoOpen=this._options.autoOpen||m.isBeingOpened,m.openComplete=!1,m.dbOpenError=null)},s.prototype.delete=function(u){var f=this;u===void 0&&(u={disableAutoOpen:!0});var h=arguments.length>0&&typeof arguments[0]!="object",m=this._state;return new de(function(b,T){var A=function(){f.close(u);var S=f._deps.indexedDB.deleteDatabase(f.name);S.onsuccess=At(function(){RC(f._deps,f.name),b()}),S.onerror=di(T),S.onblocked=f._fireOnBlocked};if(h)throw new me.InvalidArgument("Invalid closeOptions argument to db.delete()");m.isBeingOpened?m.dbReadyPromise.then(A):A()})},s.prototype.backendDB=function(){return this.idbdb},s.prototype.isOpen=function(){return this.idbdb!==null},s.prototype.hasBeenClosed=function(){var u=this._state.dbOpenError;return u&&u.name==="DatabaseClosed"},s.prototype.hasFailed=function(){return this._state.dbOpenError!==null},s.prototype.dynamicallyOpened=function(){return this._state.autoSchema},Object.defineProperty(s.prototype,"tables",{get:function(){var u=this;return a(this._allTables).map(function(f){return u._allTables[f]})},enumerable:!1,configurable:!0}),s.prototype.transaction=function(){var u=MC.apply(this,arguments);return this._transaction.apply(this,u)},s.prototype._transaction=function(u,f,h){var m=this,b=be.trans;(!b||b.db!==this||u.indexOf("!")!==-1)&&(b=null);var T=u.indexOf("?")!==-1;u=u.replace("!","").replace("?","");var A,S;try{if(S=f.map(function($){var D=$ instanceof m.Table?$.name:$;if(typeof D!="string")throw new TypeError("Invalid table argument to Dexie.transaction(). Only Table or String are allowed");return D}),u=="r"||u===$h)A=$h;else if(u=="rw"||u==Hh)A=Hh;else throw new me.InvalidArgument("Invalid transaction mode: "+u);if(b){if(b.mode===$h&&A===Hh)if(T)b=null;else throw new me.SubTransaction("Cannot enter a sub-transaction with READWRITE mode when parent transaction is READONLY");b&&S.forEach(function($){if(b&&b.storeNames.indexOf($)===-1)if(T)b=null;else throw new me.SubTransaction("Table "+$+" not included in parent transaction.")}),T&&b&&!b.active&&(b=null)}}catch($){return b?b._promise(null,function(D,W){W($)}):Lt($)}var O=N_.bind(null,this,A,S,b,h);return b?b._promise(A,O,"lock"):be.trans?Ja(be.transless,function(){return m._whenReady(O)}):this._whenReady(O)},s.prototype.table=function(u){if(!g(this._allTables,u))throw new me.InvalidTable("Table ".concat(u," does not exist"));return this._allTables[u]},s}(),JC=typeof Symbol<"u"&&"observable"in Symbol?Symbol.observable:"@@observable",eI=function(){function s(u){this._subscribe=u}return s.prototype.subscribe=function(u,f,h){return this._subscribe(!u||typeof u=="function"?{next:u,error:f,complete:h}:u)},s.prototype[JC]=function(){return this},s}(),Ul;try{Ul={indexedDB:i.indexedDB||i.mozIndexedDB||i.webkitIndexedDB||i.msIndexedDB,IDBKeyRange:i.IDBKeyRange||i.webkitIDBKeyRange}}catch{Ul={indexedDB:null,IDBKeyRange:null}}function M_(s){var u=!1,f,h=new eI(function(m){var b=_t(s);function T(J){var Q=js();try{b&&Gs();var Z=da(s,J);return b&&(Z=Z.finally(ha)),Z}finally{Q&&Ws()}}var A=!1,S,O={},$={},D={get closed(){return A},unsubscribe:function(){A||(A=!0,S&&S.abort(),W&&ga.storagemutated.unsubscribe(z))}};m.start&&m.start(D);var W=!1,ie=function(){return Mh(j)};function M(){return rp($,O)}var z=function(J){Fl(O,J),M()&&ie()},j=function(){if(!(A||!Ul.indexedDB)){O={};var J={};S&&S.abort(),S=new AbortController;var Q={subscr:J,signal:S.signal,requery:ie,querier:s,trans:null},Z=T(Q);Promise.resolve(Z).then(function(re){u=!0,f=re,!(A||Q.signal.aborted)&&(O={},$=J,!je($)&&!W&&(ga(wu,z),W=!0),Mh(function(){return!A&&m.next&&m.next(re)}))},function(re){u=!1,["DatabaseClosedError","AbortError"].includes(re?.name)||A||Mh(function(){A||m.error&&m.error(re)})})}};return setTimeout(ie,0),D});return h.hasValue=function(){return u},h.getValue=function(){return f},h}var ns=Li;E(ns,r(r({},ca),{delete:function(s){var u=new ns(s,{addons:[]});return u.delete()},exists:function(s){return new ns(s,{addons:[]}).open().then(function(u){return u.close(),!0}).catch("NoSuchDatabaseError",function(){return!1})},getDatabaseNames:function(s){try{return DC(ns.dependencies).then(s)}catch{return Lt(new me.MissingAPI)}},defineClass:function(){function s(u){l(this,u)}return s},ignoreTransaction:function(s){return be.trans?Ja(be.transless,s):s()},vip:Jh,async:function(s){return function(){try{var u=sp(s.apply(this,arguments));return!u||typeof u.then!="function"?de.resolve(u):u}catch(f){return Lt(f)}}},spawn:function(s,u,f){try{var h=sp(s.apply(f,u||[]));return!h||typeof h.then!="function"?de.resolve(h):h}catch(m){return Lt(m)}},currentTransaction:{get:function(){return be.trans||null}},waitFor:function(s,u){var f=de.resolve(typeof s=="function"?ns.ignoreTransaction(s):s).timeout(u||6e4);return be.trans?be.trans.waitFor(f):f},Promise:de,debug:{get:function(){return on},set:function(s){El(s)}},derive:C,extend:l,props:E,override:H,Events:Tu,on:ga,liveQuery:M_,extendObservabilitySet:Fl,getByKeyPath:X,setByKeyPath:ce,delByKeyPath:ve,shallowClone:Re,deepClone:F,getObjectDiff:op,cmp:We,asap:B,minKey:Bh,addons:[],connections:Qs,errnames:$t,dependencies:Ul,cache:rs,semVer:l_,version:l_.split(".").map(function(s){return parseInt(s)}).reduce(function(s,u,f){return s+u/Math.pow(10,f*2)})})),ns.maxKey=Su(ns.dependencies.IDBKeyRange),typeof dispatchEvent<"u"&&typeof addEventListener<"u"&&(ga(wu,function(s){if(!_a){var u;u=new CustomEvent(zh,{detail:s}),_a=!0,dispatchEvent(u),_a=!1}}),addEventListener(zh,function(s){var u=s.detail;_a||lp(u)}));function lp(s){var u=_a;try{_a=!0,ga.storagemutated.fire(s),ap(s,!0)}finally{_a=u}}var _a=!1,ba,fp=function(){};typeof BroadcastChannel<"u"&&(fp=function(){ba=new BroadcastChannel(zh),ba.onmessage=function(s){return s.data&&lp(s.data)}},fp(),typeof ba.unref=="function"&&ba.unref(),ga(wu,function(s){_a||ba.postMessage(s)})),typeof addEventListener<"u"&&(addEventListener("pagehide",function(s){if(!Li.disableBfCache&&s.persisted){on&&console.debug("Dexie: handling persisted pagehide"),ba?.close();for(var u=0,f=Qs;u{"use strict";function Ad(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}Tt.defaults=Ad();function TA(e){Tt.defaults=e}var xA=/[&<>"']/,cR=new RegExp(xA.source,"g"),yA=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,lR=new RegExp(yA.source,"g"),fR={"&":"&","<":"<",">":">",'"':""","'":"'"},gA=e=>fR[e];function xn(e,t){if(t){if(xA.test(e))return e.replace(cR,gA)}else if(yA.test(e))return e.replace(lR,gA);return e}var dR=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig;function hR(e){return e.replace(dR,(t,r)=>(r=r.toLowerCase(),r==="colon"?":":r.charAt(0)==="#"?r.charAt(1)==="x"?String.fromCharCode(parseInt(r.substring(2),16)):String.fromCharCode(+r.substring(1)):""))}var pR=/(^|[^\[])\^/g;function dt(e,t){let r=typeof e=="string"?e:e.source;t=t||"";let n={replace:(i,a)=>{let o=typeof a=="string"?a:a.source;return o=o.replace(pR,"$1"),r=r.replace(i,o),n},getRegex:()=>new RegExp(r,t)};return n}function _A(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch{return null}return e}var Bc={exec:()=>null};function bA(e,t){let r=e.replace(/\|/g,(a,o,l)=>{let d=!1,p=o;for(;--p>=0&&l[p]==="\\";)d=!d;return d?"|":" |"}),n=r.split(/ \|/),i=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length{let a=i.match(/^\s+/);if(a===null)return i;let[o]=a;return o.length>=n.length?i.slice(n.length):i}).join(` -`)}var Rs=class{options;rules;lexer;constructor(t){this.options=t||Tt.defaults}space(t){let r=this.rules.block.newline.exec(t);if(r&&r[0].length>0)return{type:"space",raw:r[0]}}code(t){let r=this.rules.block.code.exec(t);if(r){let n=r[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:r[0],codeBlockStyle:"indented",text:this.options.pedantic?n:vd(n,` -`)}}}fences(t){let r=this.rules.block.fences.exec(t);if(r){let n=r[0],i=gR(n,r[3]||"");return{type:"code",raw:n,lang:r[2]?r[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):r[2],text:i}}}heading(t){let r=this.rules.block.heading.exec(t);if(r){let n=r[2].trim();if(/#$/.test(n)){let i=vd(n,"#");(this.options.pedantic||!i||/ $/.test(i))&&(n=i.trim())}return{type:"heading",raw:r[0],depth:r[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(t){let r=this.rules.block.hr.exec(t);if(r)return{type:"hr",raw:r[0]}}blockquote(t){let r=this.rules.block.blockquote.exec(t);if(r){let n=r[0].replace(/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,` - $1`);n=vd(n.replace(/^ *>[ \t]?/gm,""),` -`);let i=this.lexer.state.top;this.lexer.state.top=!0;let a=this.lexer.blockTokens(n);return this.lexer.state.top=i,{type:"blockquote",raw:r[0],tokens:a,text:n}}}list(t){let r=this.rules.block.list.exec(t);if(r){let n=r[1].trim(),i=n.length>1,a={type:"list",raw:"",ordered:i,start:i?+n.slice(0,-1):"",loose:!1,items:[]};n=i?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=i?n:"[*+-]");let o=new RegExp(`^( {0,3}${n})((?:[ ][^\\n]*)?(?:\\n|$))`),l="",d="",p=!1;for(;t;){let g=!1;if(!(r=o.exec(t))||this.rules.block.hr.test(t))break;l=r[0],t=t.substring(l.length);let E=r[2].split(` -`,1)[0].replace(/^\t+/,N=>" ".repeat(3*N.length)),_=t.split(` -`,1)[0],y=0;this.options.pedantic?(y=2,d=E.trimStart()):(y=r[2].search(/[^ ]/),y=y>4?1:y,d=E.slice(y),y+=r[1].length);let C=!1;if(!E&&/^ *$/.test(_)&&(l+=_+` -`,t=t.substring(_.length+1),g=!0),!g){let N=new RegExp(`^ {0,${Math.min(3,y-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),L=new RegExp(`^ {0,${Math.min(3,y-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),H=new RegExp(`^ {0,${Math.min(3,y-1)}}(?:\`\`\`|~~~)`),R=new RegExp(`^ {0,${Math.min(3,y-1)}}#`);for(;t;){let B=t.split(` -`,1)[0];if(_=B,this.options.pedantic&&(_=_.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),H.test(_)||R.test(_)||N.test(_)||L.test(t))break;if(_.search(/[^ ]/)>=y||!_.trim())d+=` -`+_.slice(y);else{if(C||E.search(/[^ ]/)>=4||H.test(E)||R.test(E)||L.test(E))break;d+=` -`+_}!C&&!_.trim()&&(C=!0),l+=B+` -`,t=t.substring(B.length+1),E=_.slice(y)}}a.loose||(p?a.loose=!0:/\n *\n *$/.test(l)&&(p=!0));let k=null,P;this.options.gfm&&(k=/^\[[ xX]\] /.exec(d),k&&(P=k[0]!=="[ ] ",d=d.replace(/^\[[ xX]\] +/,""))),a.items.push({type:"list_item",raw:l,task:!!k,checked:P,loose:!1,text:d,tokens:[]}),a.raw+=l}a.items[a.items.length-1].raw=l.trimEnd(),a.items[a.items.length-1].text=d.trimEnd(),a.raw=a.raw.trimEnd();for(let g=0;gy.type==="space"),_=E.length>0&&E.some(y=>/\n.*\n/.test(y.raw));a.loose=_}if(a.loose)for(let g=0;g$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",a=r[3]?r[3].substring(1,r[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):r[3];return{type:"def",tag:n,raw:r[0],href:i,title:a}}}table(t){let r=this.rules.block.table.exec(t);if(!r||!/[:|]/.test(r[2]))return;let n=bA(r[1]),i=r[2].replace(/^\||\| *$/g,"").split("|"),a=r[3]&&r[3].trim()?r[3].replace(/\n[ \t]*$/,"").split(` -`):[],o={type:"table",raw:r[0],header:[],align:[],rows:[]};if(n.length===i.length){for(let l of i)/^ *-+: *$/.test(l)?o.align.push("right"):/^ *:-+: *$/.test(l)?o.align.push("center"):/^ *:-+ *$/.test(l)?o.align.push("left"):o.align.push(null);for(let l of n)o.header.push({text:l,tokens:this.lexer.inline(l)});for(let l of a)o.rows.push(bA(l,o.header.length).map(d=>({text:d,tokens:this.lexer.inline(d)})));return o}}lheading(t){let r=this.rules.block.lheading.exec(t);if(r)return{type:"heading",raw:r[0],depth:r[2].charAt(0)==="="?1:2,text:r[1],tokens:this.lexer.inline(r[1])}}paragraph(t){let r=this.rules.block.paragraph.exec(t);if(r){let n=r[1].charAt(r[1].length-1)===` -`?r[1].slice(0,-1):r[1];return{type:"paragraph",raw:r[0],text:n,tokens:this.lexer.inline(n)}}}text(t){let r=this.rules.block.text.exec(t);if(r)return{type:"text",raw:r[0],text:r[0],tokens:this.lexer.inline(r[0])}}escape(t){let r=this.rules.inline.escape.exec(t);if(r)return{type:"escape",raw:r[0],text:xn(r[1])}}tag(t){let r=this.rules.inline.tag.exec(t);if(r)return!this.lexer.state.inLink&&/^/i.test(r[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(r[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(r[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:r[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:r[0]}}link(t){let r=this.rules.inline.link.exec(t);if(r){let n=r[2].trim();if(!this.options.pedantic&&/^$/.test(n))return;let o=vd(n.slice(0,-1),"\\");if((n.length-o.length)%2===0)return}else{let o=mR(r[2],"()");if(o>-1){let d=(r[0].indexOf("!")===0?5:4)+r[1].length+o;r[2]=r[2].substring(0,o),r[0]=r[0].substring(0,d).trim(),r[3]=""}}let i=r[2],a="";if(this.options.pedantic){let o=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(i);o&&(i=o[1],a=o[3])}else a=r[3]?r[3].slice(1,-1):"";return i=i.trim(),/^$/.test(n)?i=i.slice(1):i=i.slice(1,-1)),EA(r,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:a&&a.replace(this.rules.inline.anyPunctuation,"$1")},r[0],this.lexer)}}reflink(t,r){let n;if((n=this.rules.inline.reflink.exec(t))||(n=this.rules.inline.nolink.exec(t))){let i=(n[2]||n[1]).replace(/\s+/g," "),a=r[i.toLowerCase()];if(!a){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return EA(n,a,n[0],this.lexer)}}emStrong(t,r,n=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!i||i[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(i[1]||i[2]||"")||!n||this.rules.inline.punctuation.exec(n)){let o=[...i[0]].length-1,l,d,p=o,g=0,E=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(E.lastIndex=0,r=r.slice(-1*t.length+o);(i=E.exec(r))!=null;){if(l=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!l)continue;if(d=[...l].length,i[3]||i[4]){p+=d;continue}else if((i[5]||i[6])&&o%3&&!((o+d)%3)){g+=d;continue}if(p-=d,p>0)continue;d=Math.min(d,d+p+g);let _=[...i[0]][0].length,y=t.slice(0,o+i.index+_+d);if(Math.min(o,d)%2){let k=y.slice(1,-1);return{type:"em",raw:y,text:k,tokens:this.lexer.inlineTokens(k)}}let C=y.slice(2,-2);return{type:"strong",raw:y,text:C,tokens:this.lexer.inlineTokens(C)}}}}codespan(t){let r=this.rules.inline.code.exec(t);if(r){let n=r[2].replace(/\n/g," "),i=/[^ ]/.test(n),a=/^ /.test(n)&&/ $/.test(n);return i&&a&&(n=n.substring(1,n.length-1)),n=xn(n,!0),{type:"codespan",raw:r[0],text:n}}}br(t){let r=this.rules.inline.br.exec(t);if(r)return{type:"br",raw:r[0]}}del(t){let r=this.rules.inline.del.exec(t);if(r)return{type:"del",raw:r[0],text:r[2],tokens:this.lexer.inlineTokens(r[2])}}autolink(t){let r=this.rules.inline.autolink.exec(t);if(r){let n,i;return r[2]==="@"?(n=xn(r[1]),i="mailto:"+n):(n=xn(r[1]),i=n),{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}url(t){let r;if(r=this.rules.inline.url.exec(t)){let n,i;if(r[2]==="@")n=xn(r[0]),i="mailto:"+n;else{let a;do a=r[0],r[0]=this.rules.inline._backpedal.exec(r[0])?.[0]??"";while(a!==r[0]);n=xn(r[0]),r[1]==="www."?i="http://"+r[0]:i=r[0]}return{type:"link",raw:r[0],text:n,href:i,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(t){let r=this.rules.inline.text.exec(t);if(r){let n;return this.lexer.state.inRawBlock?n=r[0]:n=xn(r[0]),{type:"text",raw:r[0],text:n}}}},_R=/^(?: *(?:\n|$))+/,bR=/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,ER=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,$c=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,vR=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,AA=/(?:[*+-]|\d{1,9}[.)])/,wA=dt(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,AA).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),k0=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,TR=/^[^\n]+/,R0=/(?!\s*\])(?:\\.|[^\[\]\\])+/,xR=dt(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",R0).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),yR=dt(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,AA).getRegex(),wd="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",L0=/|$))/,AR=dt("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",L0).replace("tag",wd).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),SA=dt(k0).replace("hr",$c).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",wd).getRegex(),wR=dt(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",SA).getRegex(),P0={blockquote:wR,code:bR,def:xR,fences:ER,heading:vR,hr:$c,html:AR,lheading:wA,list:yR,newline:_R,paragraph:SA,table:Bc,text:TR},vA=dt("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",$c).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",wd).getRegex(),SR={...P0,table:vA,paragraph:dt(k0).replace("hr",$c).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",vA).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",wd).getRegex()},CR={...P0,html:dt(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",L0).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Bc,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:dt(k0).replace("hr",$c).replace("heading",` *#{1,6} *[^ -]`).replace("lheading",wA).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},CA=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,IR=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,IA=/^( {2,}|\\)\n(?!\s*$)/,NR=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,kR=dt(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,Hc).getRegex(),RR=dt("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,Hc).getRegex(),LR=dt("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,Hc).getRegex(),PR=dt(/\\([punct])/,"gu").replace(/punct/g,Hc).getRegex(),MR=dt(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),FR=dt(L0).replace("(?:-->|$)","-->").getRegex(),BR=dt("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",FR).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),xd=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,$R=dt(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",xd).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),NA=dt(/^!?\[(label)\]\[(ref)\]/).replace("label",xd).replace("ref",R0).getRegex(),OA=dt(/^!?\[(ref)\](?:\[\])?/).replace("ref",R0).getRegex(),HR=dt("reflink|nolink(?!\\()","g").replace("reflink",NA).replace("nolink",OA).getRegex(),M0={_backpedal:Bc,anyPunctuation:PR,autolink:MR,blockSkip:DR,br:IA,code:IR,del:Bc,emStrongLDelim:kR,emStrongRDelimAst:RR,emStrongRDelimUnd:LR,escape:CA,link:$R,nolink:OA,punctuation:OR,reflink:NA,reflinkSearch:HR,tag:BR,text:NR,url:Bc},UR={...M0,link:dt(/^!?\[(label)\]\((.*?)\)/).replace("label",xd).getRegex(),reflink:dt(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",xd).getRegex()},D0={...M0,escape:dt(CA).replace("])","~|])").getRegex(),url:dt(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\d+" ".repeat(p.length));let n,i,a,o;for(;t;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some(l=>(n=l.call({lexer:this},t,r))?(t=t.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.space(t)){t=t.substring(n.raw.length),n.raw.length===1&&r.length>0?r[r.length-1].raw+=` -`:r.push(n);continue}if(n=this.tokenizer.code(t)){t=t.substring(n.raw.length),i=r[r.length-1],i&&(i.type==="paragraph"||i.type==="text")?(i.raw+=` -`+n.raw,i.text+=` -`+n.text,this.inlineQueue[this.inlineQueue.length-1].src=i.text):r.push(n);continue}if(n=this.tokenizer.fences(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(t)){t=t.substring(n.raw.length),i=r[r.length-1],i&&(i.type==="paragraph"||i.type==="text")?(i.raw+=` -`+n.raw,i.text+=` -`+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=i.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title});continue}if(n=this.tokenizer.table(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(t)){t=t.substring(n.raw.length),r.push(n);continue}if(a=t,this.options.extensions&&this.options.extensions.startBlock){let l=1/0,d=t.slice(1),p;this.options.extensions.startBlock.forEach(g=>{p=g.call({lexer:this},d),typeof p=="number"&&p>=0&&(l=Math.min(l,p))}),l<1/0&&l>=0&&(a=t.substring(0,l+1))}if(this.state.top&&(n=this.tokenizer.paragraph(a))){i=r[r.length-1],o&&i.type==="paragraph"?(i.raw+=` -`+n.raw,i.text+=` -`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):r.push(n),o=a.length!==t.length,t=t.substring(n.raw.length);continue}if(n=this.tokenizer.text(t)){t=t.substring(n.raw.length),i=r[r.length-1],i&&i.type==="text"?(i.raw+=` -`+n.raw,i.text+=` -`+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=i.text):r.push(n);continue}if(t){let l="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(l);break}else throw new Error(l)}}return this.state.top=!0,r}inline(t,r=[]){return this.inlineQueue.push({src:t,tokens:r}),r}inlineTokens(t,r=[]){let n,i,a,o=t,l,d,p;if(this.tokens.links){let g=Object.keys(this.tokens.links);if(g.length>0)for(;(l=this.tokenizer.rules.inline.reflinkSearch.exec(o))!=null;)g.includes(l[0].slice(l[0].lastIndexOf("[")+1,-1))&&(o=o.slice(0,l.index)+"["+"a".repeat(l[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(l=this.tokenizer.rules.inline.blockSkip.exec(o))!=null;)o=o.slice(0,l.index)+"["+"a".repeat(l[0].length-2)+"]"+o.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;(l=this.tokenizer.rules.inline.anyPunctuation.exec(o))!=null;)o=o.slice(0,l.index)+"++"+o.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;t;)if(d||(p=""),d=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some(g=>(n=g.call({lexer:this},t,r))?(t=t.substring(n.raw.length),r.push(n),!0):!1))){if(n=this.tokenizer.escape(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.tag(t)){t=t.substring(n.raw.length),i=r[r.length-1],i&&n.type==="text"&&i.type==="text"?(i.raw+=n.raw,i.text+=n.text):r.push(n);continue}if(n=this.tokenizer.link(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(n.raw.length),i=r[r.length-1],i&&n.type==="text"&&i.type==="text"?(i.raw+=n.raw,i.text+=n.text):r.push(n);continue}if(n=this.tokenizer.emStrong(t,o,p)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.codespan(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.br(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.del(t)){t=t.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.autolink(t)){t=t.substring(n.raw.length),r.push(n);continue}if(!this.state.inLink&&(n=this.tokenizer.url(t))){t=t.substring(n.raw.length),r.push(n);continue}if(a=t,this.options.extensions&&this.options.extensions.startInline){let g=1/0,E=t.slice(1),_;this.options.extensions.startInline.forEach(y=>{_=y.call({lexer:this},E),typeof _=="number"&&_>=0&&(g=Math.min(g,_))}),g<1/0&&g>=0&&(a=t.substring(0,g+1))}if(n=this.tokenizer.inlineText(a)){t=t.substring(n.raw.length),n.raw.slice(-1)!=="_"&&(p=n.raw.slice(-1)),d=!0,i=r[r.length-1],i&&i.type==="text"?(i.raw+=n.raw,i.text+=n.text):r.push(n);continue}if(t){let g="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(g);break}else throw new Error(g)}}return r}},Ls=class{options;constructor(t){this.options=t||Tt.defaults}code(t,r,n){let i=(r||"").match(/^\S*/)?.[0];return t=t.replace(/\n$/,"")+` -`,i?'
    '+(n?t:xn(t,!0))+`
    -`:"
    "+(n?t:xn(t,!0))+`
    -`}blockquote(t){return`
    -${t}
    -`}html(t,r){return t}heading(t,r,n){return`${t} -`}hr(){return`
    -`}list(t,r,n){let i=r?"ol":"ul",a=r&&n!==1?' start="'+n+'"':"";return"<"+i+a+`> -`+t+" -`}listitem(t,r,n){return`
  • ${t}
  • -`}checkbox(t){return"'}paragraph(t){return`

    ${t}

    -`}table(t,r){return r&&(r=`${r}`),` - -`+t+` -`+r+`
    -`}tablerow(t){return` -${t} -`}tablecell(t,r){let n=r.header?"th":"td";return(r.align?`<${n} align="${r.align}">`:`<${n}>`)+t+` -`}strong(t){return`${t}`}em(t){return`${t}`}codespan(t){return`${t}`}br(){return"
    "}del(t){return`${t}`}link(t,r,n){let i=_A(t);if(i===null)return n;t=i;let a='
    ",a}image(t,r,n){let i=_A(t);if(i===null)return n;t=i;let a=`${n}0&&_.tokens[0].type==="paragraph"?(_.tokens[0].text=P+" "+_.tokens[0].text,_.tokens[0].tokens&&_.tokens[0].tokens.length>0&&_.tokens[0].tokens[0].type==="text"&&(_.tokens[0].tokens[0].text=P+" "+_.tokens[0].tokens[0].text)):_.tokens.unshift({type:"text",text:P+" "}):k+=P+" "}k+=this.parse(_.tokens,p),g+=this.renderer.listitem(k,C,!!y)}n+=this.renderer.list(g,l,d);continue}case"html":{let o=a;n+=this.renderer.html(o.text,o.block);continue}case"paragraph":{let o=a;n+=this.renderer.paragraph(this.parseInline(o.tokens));continue}case"text":{let o=a,l=o.tokens?this.parseInline(o.tokens):o.text;for(;i+1{let l=a[o].flat(1/0);n=n.concat(this.walkTokens(l,r))}):a.tokens&&(n=n.concat(this.walkTokens(a.tokens,r)))}}return n}use(...t){let r=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(n=>{let i={...n};if(i.async=this.defaults.async||i.async||!1,n.extensions&&(n.extensions.forEach(a=>{if(!a.name)throw new Error("extension name required");if("renderer"in a){let o=r.renderers[a.name];o?r.renderers[a.name]=function(...l){let d=a.renderer.apply(this,l);return d===!1&&(d=o.apply(this,l)),d}:r.renderers[a.name]=a.renderer}if("tokenizer"in a){if(!a.level||a.level!=="block"&&a.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=r[a.level];o?o.unshift(a.tokenizer):r[a.level]=[a.tokenizer],a.start&&(a.level==="block"?r.startBlock?r.startBlock.push(a.start):r.startBlock=[a.start]:a.level==="inline"&&(r.startInline?r.startInline.push(a.start):r.startInline=[a.start]))}"childTokens"in a&&a.childTokens&&(r.childTokens[a.name]=a.childTokens)}),i.extensions=r),n.renderer){let a=this.defaults.renderer||new Ls(this.defaults);for(let o in n.renderer){if(!(o in a))throw new Error(`renderer '${o}' does not exist`);if(o==="options")continue;let l=o,d=n.renderer[l],p=a[l];a[l]=(...g)=>{let E=d.apply(a,g);return E===!1&&(E=p.apply(a,g)),E||""}}i.renderer=a}if(n.tokenizer){let a=this.defaults.tokenizer||new Rs(this.defaults);for(let o in n.tokenizer){if(!(o in a))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let l=o,d=n.tokenizer[l],p=a[l];a[l]=(...g)=>{let E=d.apply(a,g);return E===!1&&(E=p.apply(a,g)),E}}i.tokenizer=a}if(n.hooks){let a=this.defaults.hooks||new Ba;for(let o in n.hooks){if(!(o in a))throw new Error(`hook '${o}' does not exist`);if(o==="options")continue;let l=o,d=n.hooks[l],p=a[l];Ba.passThroughHooks.has(o)?a[l]=g=>{if(this.defaults.async)return Promise.resolve(d.call(a,g)).then(_=>p.call(a,_));let E=d.call(a,g);return p.call(a,E)}:a[l]=(...g)=>{let E=d.apply(a,g);return E===!1&&(E=p.apply(a,g)),E}}i.hooks=a}if(n.walkTokens){let a=this.defaults.walkTokens,o=n.walkTokens;i.walkTokens=function(l){let d=[];return d.push(o.call(this,l)),a&&(d=d.concat(a.call(this,l))),d}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,r){return yn.lex(t,r??this.defaults)}parser(t,r){return An.parse(t,r??this.defaults)}#e(t,r){return(n,i)=>{let a={...i},o={...this.defaults,...a};this.defaults.async===!0&&a.async===!1&&(o.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),o.async=!0);let l=this.#t(!!o.silent,!!o.async);if(typeof n>"u"||n===null)return l(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o),o.async)return Promise.resolve(o.hooks?o.hooks.preprocess(n):n).then(d=>t(d,o)).then(d=>o.hooks?o.hooks.processAllTokens(d):d).then(d=>o.walkTokens?Promise.all(this.walkTokens(d,o.walkTokens)).then(()=>d):d).then(d=>r(d,o)).then(d=>o.hooks?o.hooks.postprocess(d):d).catch(l);try{o.hooks&&(n=o.hooks.preprocess(n));let d=t(n,o);o.hooks&&(d=o.hooks.processAllTokens(d)),o.walkTokens&&this.walkTokens(d,o.walkTokens);let p=r(d,o);return o.hooks&&(p=o.hooks.postprocess(p)),p}catch(d){return l(d)}}}#t(t,r){return n=>{if(n.message+=` -Please report this to https://github.com/markedjs/marked.`,t){let i="

    An error occurred:

    "+xn(n.message+"",!0)+"
    ";return r?Promise.resolve(i):i}if(r)return Promise.reject(n);throw n}}},Ps=new yd;function st(e,t){return Ps.parse(e,t)}st.options=st.setOptions=function(e){return Ps.setOptions(e),st.defaults=Ps.defaults,TA(st.defaults),st};st.getDefaults=Ad;st.defaults=Tt.defaults;st.use=function(...e){return Ps.use(...e),st.defaults=Ps.defaults,TA(st.defaults),st};st.walkTokens=function(e,t){return Ps.walkTokens(e,t)};st.parseInline=Ps.parseInline;st.Parser=An;st.parser=An.parse;st.Renderer=Ls;st.TextRenderer=Yo;st.Lexer=yn;st.lexer=yn.lex;st.Tokenizer=Rs;st.Hooks=Ba;st.parse=st;var qR=st.options,zR=st.setOptions,YR=st.use,KR=st.walkTokens,jR=st.parseInline,WR=st,GR=An.parse,QR=yn.lex;Tt.Hooks=Ba;Tt.Lexer=yn;Tt.Marked=yd;Tt.Parser=An;Tt.Renderer=Ls;Tt.TextRenderer=Yo;Tt.Tokenizer=Rs;Tt.getDefaults=Ad;Tt.lexer=QR;Tt.marked=st;Tt.options=qR;Tt.parse=WR;Tt.parseInline=jR;Tt.parser=GR;Tt.setOptions=zR;Tt.use=YR;Tt.walkTokens=KR});function kA(e){return e.type===Ze.Tag||e.type===Ze.Script||e.type===Ze.Style}var Ze,RA,LA,PA,MA,FA,BA,$A,HA,UA,Ko=v(()=>{(function(e){e.Root="root",e.Text="text",e.Directive="directive",e.Comment="comment",e.Script="script",e.Style="style",e.Tag="tag",e.CDATA="cdata",e.Doctype="doctype"})(Ze||(Ze={}));RA=Ze.Root,LA=Ze.Text,PA=Ze.Directive,MA=Ze.Comment,FA=Ze.Script,BA=Ze.Style,$A=Ze.Tag,HA=Ze.CDATA,UA=Ze.Doctype});function _e(e){return kA(e)}function jo(e){return e.type===Ze.CDATA}function nn(e){return e.type===Ze.Text}function $s(e){return e.type===Ze.Comment}function Cd(e){return e.type===Ze.Directive}function Bn(e){return e.type===Ze.Root}function ht(e){return Object.prototype.hasOwnProperty.call(e,"children")}function Wo(e,t=!1){let r;if(nn(e))r=new Ni(e.data);else if($s(e))r=new Ms(e.data);else if(_e(e)){let n=t?F0(e.children):[],i=new Bs(e.name,{...e.attribs},n);n.forEach(a=>a.parent=i),e.namespace!=null&&(i.namespace=e.namespace),e["x-attribsNamespace"]&&(i["x-attribsNamespace"]={...e["x-attribsNamespace"]}),e["x-attribsPrefix"]&&(i["x-attribsPrefix"]={...e["x-attribsPrefix"]}),r=i}else if(jo(e)){let n=t?F0(e.children):[],i=new qc(n);n.forEach(a=>a.parent=i),r=i}else if(Bn(e)){let n=t?F0(e.children):[],i=new wn(n);n.forEach(a=>a.parent=i),e["x-mode"]&&(i["x-mode"]=e["x-mode"]),r=i}else if(Cd(e)){let n=new Fs(e.name,e.data);e["x-name"]!=null&&(n["x-name"]=e["x-name"],n["x-publicId"]=e["x-publicId"],n["x-systemId"]=e["x-systemId"]),r=n}else throw new Error(`Not implemented yet: ${e.type}`);return r.startIndex=e.startIndex,r.endIndex=e.endIndex,e.sourceCodeLocation!=null&&(r.sourceCodeLocation=e.sourceCodeLocation),r}function F0(e){let t=e.map(r=>Wo(r,!0));for(let r=1;r{Ko();Sd=class{constructor(){this.parent=null,this.prev=null,this.next=null,this.startIndex=null,this.endIndex=null}get parentNode(){return this.parent}set parentNode(t){this.parent=t}get previousSibling(){return this.prev}set previousSibling(t){this.prev=t}get nextSibling(){return this.next}set nextSibling(t){this.next=t}cloneNode(t=!1){return Wo(this,t)}},Uc=class extends Sd{constructor(t){super(),this.data=t}get nodeValue(){return this.data}set nodeValue(t){this.data=t}},Ni=class extends Uc{constructor(){super(...arguments),this.type=Ze.Text}get nodeType(){return 3}},Ms=class extends Uc{constructor(){super(...arguments),this.type=Ze.Comment}get nodeType(){return 8}},Fs=class extends Uc{constructor(t,r){super(r),this.name=t,this.type=Ze.Directive}get nodeType(){return 1}},Vc=class extends Sd{constructor(t){super(),this.children=t}get firstChild(){var t;return(t=this.children[0])!==null&&t!==void 0?t:null}get lastChild(){return this.children.length>0?this.children[this.children.length-1]:null}get childNodes(){return this.children}set childNodes(t){this.children=t}},qc=class extends Vc{constructor(){super(...arguments),this.type=Ze.CDATA}get nodeType(){return 4}},wn=class extends Vc{constructor(){super(...arguments),this.type=Ze.Root}get nodeType(){return 9}},Bs=class extends Vc{constructor(t,r,n=[],i=t==="script"?Ze.Script:t==="style"?Ze.Style:Ze.Tag){super(n),this.name=t,this.attribs=r,this.type=i}get nodeType(){return 1}get tagName(){return this.name}set tagName(t){this.name=t}get attributes(){return Object.keys(this.attribs).map(t=>{var r,n;return{name:t,value:this.attribs[t],namespace:(r=this["x-attribsNamespace"])===null||r===void 0?void 0:r[t],prefix:(n=this["x-attribsPrefix"])===null||n===void 0?void 0:n[t]}})}}});var qA,Go,_r=v(()=>{Ko();B0();B0();qA={withStartIndices:!1,withEndIndices:!1,xmlMode:!1},Go=class{constructor(t,r,n){this.dom=[],this.root=new wn(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null,typeof r=="function"&&(n=r,r=qA),typeof t=="object"&&(r=t,t=void 0),this.callback=t??null,this.options=r??qA,this.elementCB=n??null}onparserinit(t){this.parser=t}onreset(){this.dom=[],this.root=new wn(this.dom),this.done=!1,this.tagStack=[this.root],this.lastNode=null,this.parser=null}onend(){this.done||(this.done=!0,this.parser=null,this.handleCallback(null))}onerror(t){this.handleCallback(t)}onclosetag(){this.lastNode=null;let t=this.tagStack.pop();this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),this.elementCB&&this.elementCB(t)}onopentag(t,r){let n=this.options.xmlMode?Ze.Tag:void 0,i=new Bs(t,r,void 0,n);this.addNode(i),this.tagStack.push(i)}ontext(t){let{lastNode:r}=this;if(r&&r.type===Ze.Text)r.data+=t,this.options.withEndIndices&&(r.endIndex=this.parser.endIndex);else{let n=new Ni(t);this.addNode(n),this.lastNode=n}}oncomment(t){if(this.lastNode&&this.lastNode.type===Ze.Comment){this.lastNode.data+=t;return}let r=new Ms(t);this.addNode(r),this.lastNode=r}oncommentend(){this.lastNode=null}oncdatastart(){let t=new Ni(""),r=new qc([t]);this.addNode(r),t.parent=r,this.lastNode=t}oncdataend(){this.lastNode=null}onprocessinginstruction(t,r){let n=new Fs(t,r);this.addNode(n)}handleCallback(t){if(typeof this.callback=="function")this.callback(t,this.dom);else if(t)throw t}addNode(t){let r=this.tagStack[this.tagStack.length-1],n=r.children[r.children.length-1];this.options.withStartIndices&&(t.startIndex=this.parser.startIndex),this.options.withEndIndices&&(t.endIndex=this.parser.endIndex),r.children.push(t),n&&(t.prev=n,n.next=t),t.parent=r,this.lastNode=null}}});var Qo,zA=v(()=>{Qo=new Uint16Array('\u1D41<\xD5\u0131\u028A\u049D\u057B\u05D0\u0675\u06DE\u07A2\u07D6\u080F\u0A4A\u0A91\u0DA1\u0E6D\u0F09\u0F26\u10CA\u1228\u12E1\u1415\u149D\u14C3\u14DF\u1525\0\0\0\0\0\0\u156B\u16CD\u198D\u1C12\u1DDD\u1F7E\u2060\u21B0\u228D\u23C0\u23FB\u2442\u2824\u2912\u2D08\u2E48\u2FCE\u3016\u32BA\u3639\u37AC\u38FE\u3A28\u3A71\u3AE0\u3B2E\u0800EMabcfglmnoprstu\\bfms\x7F\x84\x8B\x90\x95\x98\xA6\xB3\xB9\xC8\xCFlig\u803B\xC6\u40C6P\u803B&\u4026cute\u803B\xC1\u40C1reve;\u4102\u0100iyx}rc\u803B\xC2\u40C2;\u4410r;\uC000\u{1D504}rave\u803B\xC0\u40C0pha;\u4391acr;\u4100d;\u6A53\u0100gp\x9D\xA1on;\u4104f;\uC000\u{1D538}plyFunction;\u6061ing\u803B\xC5\u40C5\u0100cs\xBE\xC3r;\uC000\u{1D49C}ign;\u6254ilde\u803B\xC3\u40C3ml\u803B\xC4\u40C4\u0400aceforsu\xE5\xFB\xFE\u0117\u011C\u0122\u0127\u012A\u0100cr\xEA\xF2kslash;\u6216\u0176\xF6\xF8;\u6AE7ed;\u6306y;\u4411\u0180crt\u0105\u010B\u0114ause;\u6235noullis;\u612Ca;\u4392r;\uC000\u{1D505}pf;\uC000\u{1D539}eve;\u42D8c\xF2\u0113mpeq;\u624E\u0700HOacdefhilorsu\u014D\u0151\u0156\u0180\u019E\u01A2\u01B5\u01B7\u01BA\u01DC\u0215\u0273\u0278\u027Ecy;\u4427PY\u803B\xA9\u40A9\u0180cpy\u015D\u0162\u017Aute;\u4106\u0100;i\u0167\u0168\u62D2talDifferentialD;\u6145leys;\u612D\u0200aeio\u0189\u018E\u0194\u0198ron;\u410Cdil\u803B\xC7\u40C7rc;\u4108nint;\u6230ot;\u410A\u0100dn\u01A7\u01ADilla;\u40B8terDot;\u40B7\xF2\u017Fi;\u43A7rcle\u0200DMPT\u01C7\u01CB\u01D1\u01D6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01E2\u01F8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020FoubleQuote;\u601Duote;\u6019\u0200lnpu\u021E\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6A74\u0180git\u022F\u0236\u023Aruent;\u6261nt;\u622FourIntegral;\u622E\u0100fr\u024C\u024E;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6A2Fcr;\uC000\u{1D49E}p\u0100;C\u0284\u0285\u62D3ap;\u624D\u0580DJSZacefios\u02A0\u02AC\u02B0\u02B4\u02B8\u02CB\u02D7\u02E1\u02E6\u0333\u048D\u0100;o\u0179\u02A5trahd;\u6911cy;\u4402cy;\u4405cy;\u440F\u0180grs\u02BF\u02C4\u02C7ger;\u6021r;\u61A1hv;\u6AE4\u0100ay\u02D0\u02D5ron;\u410E;\u4414l\u0100;t\u02DD\u02DE\u6207a;\u4394r;\uC000\u{1D507}\u0100af\u02EB\u0327\u0100cm\u02F0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031Ccute;\u40B4o\u0174\u030B\u030D;\u42D9bleAcute;\u42DDrave;\u4060ilde;\u42DCond;\u62C4ferentialD;\u6146\u0470\u033D\0\0\0\u0342\u0354\0\u0405f;\uC000\u{1D53B}\u0180;DE\u0348\u0349\u034D\u40A8ot;\u60DCqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03CF\u03E2\u03F8ontourIntegra\xEC\u0239o\u0274\u0379\0\0\u037B\xBB\u0349nArrow;\u61D3\u0100eo\u0387\u03A4ft\u0180ART\u0390\u0396\u03A1rrow;\u61D0ightArrow;\u61D4e\xE5\u02CAng\u0100LR\u03AB\u03C4eft\u0100AR\u03B3\u03B9rrow;\u67F8ightArrow;\u67FAightArrow;\u67F9ight\u0100AT\u03D8\u03DErrow;\u61D2ee;\u62A8p\u0241\u03E9\0\0\u03EFrrow;\u61D1ownArrow;\u61D5erticalBar;\u6225n\u0300ABLRTa\u0412\u042A\u0430\u045E\u047F\u037Crrow\u0180;BU\u041D\u041E\u0422\u6193ar;\u6913pArrow;\u61F5reve;\u4311eft\u02D2\u043A\0\u0446\0\u0450ightVector;\u6950eeVector;\u695Eector\u0100;B\u0459\u045A\u61BDar;\u6956ight\u01D4\u0467\0\u0471eeVector;\u695Fector\u0100;B\u047A\u047B\u61C1ar;\u6957ee\u0100;A\u0486\u0487\u62A4rrow;\u61A7\u0100ct\u0492\u0497r;\uC000\u{1D49F}rok;\u4110\u0800NTacdfglmopqstux\u04BD\u04C0\u04C4\u04CB\u04DE\u04E2\u04E7\u04EE\u04F5\u0521\u052F\u0536\u0552\u055D\u0560\u0565G;\u414AH\u803B\xD0\u40D0cute\u803B\xC9\u40C9\u0180aiy\u04D2\u04D7\u04DCron;\u411Arc\u803B\xCA\u40CA;\u442Dot;\u4116r;\uC000\u{1D508}rave\u803B\xC8\u40C8ement;\u6208\u0100ap\u04FA\u04FEcr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65FBerySmallSquare;\u65AB\u0100gp\u0526\u052Aon;\u4118f;\uC000\u{1D53C}silon;\u4395u\u0100ai\u053C\u0549l\u0100;T\u0542\u0543\u6A75ilde;\u6242librium;\u61CC\u0100ci\u0557\u055Ar;\u6130m;\u6A73a;\u4397ml\u803B\xCB\u40CB\u0100ip\u056A\u056Fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058D\u05B2\u05CCy;\u4424r;\uC000\u{1D509}lled\u0253\u0597\0\0\u05A3mallSquare;\u65FCerySmallSquare;\u65AA\u0370\u05BA\0\u05BF\0\0\u05C4f;\uC000\u{1D53D}All;\u6200riertrf;\u6131c\xF2\u05CB\u0600JTabcdfgorst\u05E8\u05EC\u05EF\u05FA\u0600\u0612\u0616\u061B\u061D\u0623\u066C\u0672cy;\u4403\u803B>\u403Emma\u0100;d\u05F7\u05F8\u4393;\u43DCreve;\u411E\u0180eiy\u0607\u060C\u0610dil;\u4122rc;\u411C;\u4413ot;\u4120r;\uC000\u{1D50A};\u62D9pf;\uC000\u{1D53E}eater\u0300EFGLST\u0635\u0644\u064E\u0656\u065B\u0666qual\u0100;L\u063E\u063F\u6265ess;\u62DBullEqual;\u6267reater;\u6AA2ess;\u6277lantEqual;\u6A7Eilde;\u6273cr;\uC000\u{1D4A2};\u626B\u0400Aacfiosu\u0685\u068B\u0696\u069B\u069E\u06AA\u06BE\u06CARDcy;\u442A\u0100ct\u0690\u0694ek;\u42C7;\u405Eirc;\u4124r;\u610ClbertSpace;\u610B\u01F0\u06AF\0\u06B2f;\u610DizontalLine;\u6500\u0100ct\u06C3\u06C5\xF2\u06A9rok;\u4126mp\u0144\u06D0\u06D8ownHum\xF0\u012Fqual;\u624F\u0700EJOacdfgmnostu\u06FA\u06FE\u0703\u0707\u070E\u071A\u071E\u0721\u0728\u0744\u0778\u078B\u078F\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803B\xCD\u40CD\u0100iy\u0713\u0718rc\u803B\xCE\u40CE;\u4418ot;\u4130r;\u6111rave\u803B\xCC\u40CC\u0180;ap\u0720\u072F\u073F\u0100cg\u0734\u0737r;\u412AinaryI;\u6148lie\xF3\u03DD\u01F4\u0749\0\u0762\u0100;e\u074D\u074E\u622C\u0100gr\u0753\u0758ral;\u622Bsection;\u62C2isible\u0100CT\u076C\u0772omma;\u6063imes;\u6062\u0180gpt\u077F\u0783\u0788on;\u412Ef;\uC000\u{1D540}a;\u4399cr;\u6110ilde;\u4128\u01EB\u079A\0\u079Ecy;\u4406l\u803B\xCF\u40CF\u0280cfosu\u07AC\u07B7\u07BC\u07C2\u07D0\u0100iy\u07B1\u07B5rc;\u4134;\u4419r;\uC000\u{1D50D}pf;\uC000\u{1D541}\u01E3\u07C7\0\u07CCr;\uC000\u{1D4A5}rcy;\u4408kcy;\u4404\u0380HJacfos\u07E4\u07E8\u07EC\u07F1\u07FD\u0802\u0808cy;\u4425cy;\u440Cppa;\u439A\u0100ey\u07F6\u07FBdil;\u4136;\u441Ar;\uC000\u{1D50E}pf;\uC000\u{1D542}cr;\uC000\u{1D4A6}\u0580JTaceflmost\u0825\u0829\u082C\u0850\u0863\u09B3\u09B8\u09C7\u09CD\u0A37\u0A47cy;\u4409\u803B<\u403C\u0280cmnpr\u0837\u083C\u0841\u0844\u084Dute;\u4139bda;\u439Bg;\u67EAlacetrf;\u6112r;\u619E\u0180aey\u0857\u085C\u0861ron;\u413Ddil;\u413B;\u441B\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087E\u08A9\u08B1\u08E0\u08E6\u08FC\u092F\u095B\u0390\u096A\u0100nr\u0883\u088FgleBracket;\u67E8row\u0180;BR\u0899\u089A\u089E\u6190ar;\u61E4ightArrow;\u61C6eiling;\u6308o\u01F5\u08B7\0\u08C3bleBracket;\u67E6n\u01D4\u08C8\0\u08D2eeVector;\u6961ector\u0100;B\u08DB\u08DC\u61C3ar;\u6959loor;\u630Aight\u0100AV\u08EF\u08F5rrow;\u6194ector;\u694E\u0100er\u0901\u0917e\u0180;AV\u0909\u090A\u0910\u62A3rrow;\u61A4ector;\u695Aiangle\u0180;BE\u0924\u0925\u0929\u62B2ar;\u69CFqual;\u62B4p\u0180DTV\u0937\u0942\u094CownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61BFar;\u6958ector\u0100;B\u0965\u0966\u61BCar;\u6952ight\xE1\u039Cs\u0300EFGLST\u097E\u098B\u0995\u099D\u09A2\u09ADqualGreater;\u62DAullEqual;\u6266reater;\u6276ess;\u6AA1lantEqual;\u6A7Dilde;\u6272r;\uC000\u{1D50F}\u0100;e\u09BD\u09BE\u62D8ftarrow;\u61DAidot;\u413F\u0180npw\u09D4\u0A16\u0A1Bg\u0200LRlr\u09DE\u09F7\u0A02\u0A10eft\u0100AR\u09E6\u09ECrrow;\u67F5ightArrow;\u67F7ightArrow;\u67F6eft\u0100ar\u03B3\u0A0Aight\xE1\u03BFight\xE1\u03CAf;\uC000\u{1D543}er\u0100LR\u0A22\u0A2CeftArrow;\u6199ightArrow;\u6198\u0180cht\u0A3E\u0A40\u0A42\xF2\u084C;\u61B0rok;\u4141;\u626A\u0400acefiosu\u0A5A\u0A5D\u0A60\u0A77\u0A7C\u0A85\u0A8B\u0A8Ep;\u6905y;\u441C\u0100dl\u0A65\u0A6FiumSpace;\u605Flintrf;\u6133r;\uC000\u{1D510}nusPlus;\u6213pf;\uC000\u{1D544}c\xF2\u0A76;\u439C\u0480Jacefostu\u0AA3\u0AA7\u0AAD\u0AC0\u0B14\u0B19\u0D91\u0D97\u0D9Ecy;\u440Acute;\u4143\u0180aey\u0AB4\u0AB9\u0ABEron;\u4147dil;\u4145;\u441D\u0180gsw\u0AC7\u0AF0\u0B0Eative\u0180MTV\u0AD3\u0ADF\u0AE8ediumSpace;\u600Bhi\u0100cn\u0AE6\u0AD8\xEB\u0AD9eryThi\xEE\u0AD9ted\u0100GL\u0AF8\u0B06reaterGreate\xF2\u0673essLes\xF3\u0A48Line;\u400Ar;\uC000\u{1D511}\u0200Bnpt\u0B22\u0B28\u0B37\u0B3Areak;\u6060BreakingSpace;\u40A0f;\u6115\u0680;CDEGHLNPRSTV\u0B55\u0B56\u0B6A\u0B7C\u0BA1\u0BEB\u0C04\u0C5E\u0C84\u0CA6\u0CD8\u0D61\u0D85\u6AEC\u0100ou\u0B5B\u0B64ngruent;\u6262pCap;\u626DoubleVerticalBar;\u6226\u0180lqx\u0B83\u0B8A\u0B9Bement;\u6209ual\u0100;T\u0B92\u0B93\u6260ilde;\uC000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0BB6\u0BB7\u0BBD\u0BC9\u0BD3\u0BD8\u0BE5\u626Fqual;\u6271ullEqual;\uC000\u2267\u0338reater;\uC000\u226B\u0338ess;\u6279lantEqual;\uC000\u2A7E\u0338ilde;\u6275ump\u0144\u0BF2\u0BFDownHump;\uC000\u224E\u0338qual;\uC000\u224F\u0338e\u0100fs\u0C0A\u0C27tTriangle\u0180;BE\u0C1A\u0C1B\u0C21\u62EAar;\uC000\u29CF\u0338qual;\u62ECs\u0300;EGLST\u0C35\u0C36\u0C3C\u0C44\u0C4B\u0C58\u626Equal;\u6270reater;\u6278ess;\uC000\u226A\u0338lantEqual;\uC000\u2A7D\u0338ilde;\u6274ested\u0100GL\u0C68\u0C79reaterGreater;\uC000\u2AA2\u0338essLess;\uC000\u2AA1\u0338recedes\u0180;ES\u0C92\u0C93\u0C9B\u6280qual;\uC000\u2AAF\u0338lantEqual;\u62E0\u0100ei\u0CAB\u0CB9verseElement;\u620CghtTriangle\u0180;BE\u0CCB\u0CCC\u0CD2\u62EBar;\uC000\u29D0\u0338qual;\u62ED\u0100qu\u0CDD\u0D0CuareSu\u0100bp\u0CE8\u0CF9set\u0100;E\u0CF0\u0CF3\uC000\u228F\u0338qual;\u62E2erset\u0100;E\u0D03\u0D06\uC000\u2290\u0338qual;\u62E3\u0180bcp\u0D13\u0D24\u0D4Eset\u0100;E\u0D1B\u0D1E\uC000\u2282\u20D2qual;\u6288ceeds\u0200;EST\u0D32\u0D33\u0D3B\u0D46\u6281qual;\uC000\u2AB0\u0338lantEqual;\u62E1ilde;\uC000\u227F\u0338erset\u0100;E\u0D58\u0D5B\uC000\u2283\u20D2qual;\u6289ilde\u0200;EFT\u0D6E\u0D6F\u0D75\u0D7F\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uC000\u{1D4A9}ilde\u803B\xD1\u40D1;\u439D\u0700Eacdfgmoprstuv\u0DBD\u0DC2\u0DC9\u0DD5\u0DDB\u0DE0\u0DE7\u0DFC\u0E02\u0E20\u0E22\u0E32\u0E3F\u0E44lig;\u4152cute\u803B\xD3\u40D3\u0100iy\u0DCE\u0DD3rc\u803B\xD4\u40D4;\u441Eblac;\u4150r;\uC000\u{1D512}rave\u803B\xD2\u40D2\u0180aei\u0DEE\u0DF2\u0DF6cr;\u414Cga;\u43A9cron;\u439Fpf;\uC000\u{1D546}enCurly\u0100DQ\u0E0E\u0E1AoubleQuote;\u601Cuote;\u6018;\u6A54\u0100cl\u0E27\u0E2Cr;\uC000\u{1D4AA}ash\u803B\xD8\u40D8i\u016C\u0E37\u0E3Cde\u803B\xD5\u40D5es;\u6A37ml\u803B\xD6\u40D6er\u0100BP\u0E4B\u0E60\u0100ar\u0E50\u0E53r;\u603Eac\u0100ek\u0E5A\u0E5C;\u63DEet;\u63B4arenthesis;\u63DC\u0480acfhilors\u0E7F\u0E87\u0E8A\u0E8F\u0E92\u0E94\u0E9D\u0EB0\u0EFCrtialD;\u6202y;\u441Fr;\uC000\u{1D513}i;\u43A6;\u43A0usMinus;\u40B1\u0100ip\u0EA2\u0EADncareplan\xE5\u069Df;\u6119\u0200;eio\u0EB9\u0EBA\u0EE0\u0EE4\u6ABBcedes\u0200;EST\u0EC8\u0EC9\u0ECF\u0EDA\u627Aqual;\u6AAFlantEqual;\u627Cilde;\u627Eme;\u6033\u0100dp\u0EE9\u0EEEuct;\u620Fortion\u0100;a\u0225\u0EF9l;\u621D\u0100ci\u0F01\u0F06r;\uC000\u{1D4AB};\u43A8\u0200Ufos\u0F11\u0F16\u0F1B\u0F1FOT\u803B"\u4022r;\uC000\u{1D514}pf;\u611Acr;\uC000\u{1D4AC}\u0600BEacefhiorsu\u0F3E\u0F43\u0F47\u0F60\u0F73\u0FA7\u0FAA\u0FAD\u1096\u10A9\u10B4\u10BEarr;\u6910G\u803B\xAE\u40AE\u0180cnr\u0F4E\u0F53\u0F56ute;\u4154g;\u67EBr\u0100;t\u0F5C\u0F5D\u61A0l;\u6916\u0180aey\u0F67\u0F6C\u0F71ron;\u4158dil;\u4156;\u4420\u0100;v\u0F78\u0F79\u611Cerse\u0100EU\u0F82\u0F99\u0100lq\u0F87\u0F8Eement;\u620Builibrium;\u61CBpEquilibrium;\u696Fr\xBB\u0F79o;\u43A1ght\u0400ACDFTUVa\u0FC1\u0FEB\u0FF3\u1022\u1028\u105B\u1087\u03D8\u0100nr\u0FC6\u0FD2gleBracket;\u67E9row\u0180;BL\u0FDC\u0FDD\u0FE1\u6192ar;\u61E5eftArrow;\u61C4eiling;\u6309o\u01F5\u0FF9\0\u1005bleBracket;\u67E7n\u01D4\u100A\0\u1014eeVector;\u695Dector\u0100;B\u101D\u101E\u61C2ar;\u6955loor;\u630B\u0100er\u102D\u1043e\u0180;AV\u1035\u1036\u103C\u62A2rrow;\u61A6ector;\u695Biangle\u0180;BE\u1050\u1051\u1055\u62B3ar;\u69D0qual;\u62B5p\u0180DTV\u1063\u106E\u1078ownVector;\u694FeeVector;\u695Cector\u0100;B\u1082\u1083\u61BEar;\u6954ector\u0100;B\u1091\u1092\u61C0ar;\u6953\u0100pu\u109B\u109Ef;\u611DndImplies;\u6970ightarrow;\u61DB\u0100ch\u10B9\u10BCr;\u611B;\u61B1leDelayed;\u69F4\u0680HOacfhimoqstu\u10E4\u10F1\u10F7\u10FD\u1119\u111E\u1151\u1156\u1161\u1167\u11B5\u11BB\u11BF\u0100Cc\u10E9\u10EEHcy;\u4429y;\u4428FTcy;\u442Ccute;\u415A\u0280;aeiy\u1108\u1109\u110E\u1113\u1117\u6ABCron;\u4160dil;\u415Erc;\u415C;\u4421r;\uC000\u{1D516}ort\u0200DLRU\u112A\u1134\u113E\u1149ownArrow\xBB\u041EeftArrow\xBB\u089AightArrow\xBB\u0FDDpArrow;\u6191gma;\u43A3allCircle;\u6218pf;\uC000\u{1D54A}\u0272\u116D\0\0\u1170t;\u621Aare\u0200;ISU\u117B\u117C\u1189\u11AF\u65A1ntersection;\u6293u\u0100bp\u118F\u119Eset\u0100;E\u1197\u1198\u628Fqual;\u6291erset\u0100;E\u11A8\u11A9\u6290qual;\u6292nion;\u6294cr;\uC000\u{1D4AE}ar;\u62C6\u0200bcmp\u11C8\u11DB\u1209\u120B\u0100;s\u11CD\u11CE\u62D0et\u0100;E\u11CD\u11D5qual;\u6286\u0100ch\u11E0\u1205eeds\u0200;EST\u11ED\u11EE\u11F4\u11FF\u627Bqual;\u6AB0lantEqual;\u627Dilde;\u627FTh\xE1\u0F8C;\u6211\u0180;es\u1212\u1213\u1223\u62D1rset\u0100;E\u121C\u121D\u6283qual;\u6287et\xBB\u1213\u0580HRSacfhiors\u123E\u1244\u1249\u1255\u125E\u1271\u1276\u129F\u12C2\u12C8\u12D1ORN\u803B\xDE\u40DEADE;\u6122\u0100Hc\u124E\u1252cy;\u440By;\u4426\u0100bu\u125A\u125C;\u4009;\u43A4\u0180aey\u1265\u126A\u126Fron;\u4164dil;\u4162;\u4422r;\uC000\u{1D517}\u0100ei\u127B\u1289\u01F2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128E\u1298kSpace;\uC000\u205F\u200ASpace;\u6009lde\u0200;EFT\u12AB\u12AC\u12B2\u12BC\u623Cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uC000\u{1D54B}ipleDot;\u60DB\u0100ct\u12D6\u12DBr;\uC000\u{1D4AF}rok;\u4166\u0AE1\u12F7\u130E\u131A\u1326\0\u132C\u1331\0\0\0\0\0\u1338\u133D\u1377\u1385\0\u13FF\u1404\u140A\u1410\u0100cr\u12FB\u1301ute\u803B\xDA\u40DAr\u0100;o\u1307\u1308\u619Fcir;\u6949r\u01E3\u1313\0\u1316y;\u440Eve;\u416C\u0100iy\u131E\u1323rc\u803B\xDB\u40DB;\u4423blac;\u4170r;\uC000\u{1D518}rave\u803B\xD9\u40D9acr;\u416A\u0100di\u1341\u1369er\u0100BP\u1348\u135D\u0100ar\u134D\u1350r;\u405Fac\u0100ek\u1357\u1359;\u63DFet;\u63B5arenthesis;\u63DDon\u0100;P\u1370\u1371\u62C3lus;\u628E\u0100gp\u137B\u137Fon;\u4172f;\uC000\u{1D54C}\u0400ADETadps\u1395\u13AE\u13B8\u13C4\u03E8\u13D2\u13D7\u13F3rrow\u0180;BD\u1150\u13A0\u13A4ar;\u6912ownArrow;\u61C5ownArrow;\u6195quilibrium;\u696Eee\u0100;A\u13CB\u13CC\u62A5rrow;\u61A5own\xE1\u03F3er\u0100LR\u13DE\u13E8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13F9\u13FA\u43D2on;\u43A5ing;\u416Ecr;\uC000\u{1D4B0}ilde;\u4168ml\u803B\xDC\u40DC\u0480Dbcdefosv\u1427\u142C\u1430\u1433\u143E\u1485\u148A\u1490\u1496ash;\u62ABar;\u6AEBy;\u4412ash\u0100;l\u143B\u143C\u62A9;\u6AE6\u0100er\u1443\u1445;\u62C1\u0180bty\u144C\u1450\u147Aar;\u6016\u0100;i\u144F\u1455cal\u0200BLST\u1461\u1465\u146A\u1474ar;\u6223ine;\u407Ceparator;\u6758ilde;\u6240ThinSpace;\u600Ar;\uC000\u{1D519}pf;\uC000\u{1D54D}cr;\uC000\u{1D4B1}dash;\u62AA\u0280cefos\u14A7\u14AC\u14B1\u14B6\u14BCirc;\u4174dge;\u62C0r;\uC000\u{1D51A}pf;\uC000\u{1D54E}cr;\uC000\u{1D4B2}\u0200fios\u14CB\u14D0\u14D2\u14D8r;\uC000\u{1D51B};\u439Epf;\uC000\u{1D54F}cr;\uC000\u{1D4B3}\u0480AIUacfosu\u14F1\u14F5\u14F9\u14FD\u1504\u150F\u1514\u151A\u1520cy;\u442Fcy;\u4407cy;\u442Ecute\u803B\xDD\u40DD\u0100iy\u1509\u150Drc;\u4176;\u442Br;\uC000\u{1D51C}pf;\uC000\u{1D550}cr;\uC000\u{1D4B4}ml;\u4178\u0400Hacdefos\u1535\u1539\u153F\u154B\u154F\u155D\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417D;\u4417ot;\u417B\u01F2\u1554\0\u155BoWidt\xE8\u0AD9a;\u4396r;\u6128pf;\u6124cr;\uC000\u{1D4B5}\u0BE1\u1583\u158A\u1590\0\u15B0\u15B6\u15BF\0\0\0\0\u15C6\u15DB\u15EB\u165F\u166D\0\u1695\u169B\u16B2\u16B9\0\u16BEcute\u803B\xE1\u40E1reve;\u4103\u0300;Ediuy\u159C\u159D\u15A1\u15A3\u15A8\u15AD\u623E;\uC000\u223E\u0333;\u623Frc\u803B\xE2\u40E2te\u80BB\xB4\u0306;\u4430lig\u803B\xE6\u40E6\u0100;r\xB2\u15BA;\uC000\u{1D51E}rave\u803B\xE0\u40E0\u0100ep\u15CA\u15D6\u0100fp\u15CF\u15D4sym;\u6135\xE8\u15D3ha;\u43B1\u0100ap\u15DFc\u0100cl\u15E4\u15E7r;\u4101g;\u6A3F\u0264\u15F0\0\0\u160A\u0280;adsv\u15FA\u15FB\u15FF\u1601\u1607\u6227nd;\u6A55;\u6A5Clope;\u6A58;\u6A5A\u0380;elmrsz\u1618\u1619\u161B\u161E\u163F\u164F\u1659\u6220;\u69A4e\xBB\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163A\u163C\u163E;\u69A8;\u69A9;\u69AA;\u69AB;\u69AC;\u69AD;\u69AE;\u69AFt\u0100;v\u1645\u1646\u621Fb\u0100;d\u164C\u164D\u62BE;\u699D\u0100pt\u1654\u1657h;\u6222\xBB\xB9arr;\u637C\u0100gp\u1663\u1667on;\u4105f;\uC000\u{1D552}\u0380;Eaeiop\u12C1\u167B\u167D\u1682\u1684\u1687\u168A;\u6A70cir;\u6A6F;\u624Ad;\u624Bs;\u4027rox\u0100;e\u12C1\u1692\xF1\u1683ing\u803B\xE5\u40E5\u0180cty\u16A1\u16A6\u16A8r;\uC000\u{1D4B6};\u402Amp\u0100;e\u12C1\u16AF\xF1\u0288ilde\u803B\xE3\u40E3ml\u803B\xE4\u40E4\u0100ci\u16C2\u16C8onin\xF4\u0272nt;\u6A11\u0800Nabcdefiklnoprsu\u16ED\u16F1\u1730\u173C\u1743\u1748\u1778\u177D\u17E0\u17E6\u1839\u1850\u170D\u193D\u1948\u1970ot;\u6AED\u0100cr\u16F6\u171Ek\u0200ceps\u1700\u1705\u170D\u1713ong;\u624Cpsilon;\u43F6rime;\u6035im\u0100;e\u171A\u171B\u623Dq;\u62CD\u0176\u1722\u1726ee;\u62BDed\u0100;g\u172C\u172D\u6305e\xBB\u172Drk\u0100;t\u135C\u1737brk;\u63B6\u0100oy\u1701\u1741;\u4431quo;\u601E\u0280cmprt\u1753\u175B\u1761\u1764\u1768aus\u0100;e\u010A\u0109ptyv;\u69B0s\xE9\u170Cno\xF5\u0113\u0180ahw\u176F\u1771\u1773;\u43B2;\u6136een;\u626Cr;\uC000\u{1D51F}g\u0380costuvw\u178D\u179D\u17B3\u17C1\u17D5\u17DB\u17DE\u0180aiu\u1794\u1796\u179A\xF0\u0760rc;\u65EFp\xBB\u1371\u0180dpt\u17A4\u17A8\u17ADot;\u6A00lus;\u6A01imes;\u6A02\u0271\u17B9\0\0\u17BEcup;\u6A06ar;\u6605riangle\u0100du\u17CD\u17D2own;\u65BDp;\u65B3plus;\u6A04e\xE5\u1444\xE5\u14ADarow;\u690D\u0180ako\u17ED\u1826\u1835\u0100cn\u17F2\u1823k\u0180lst\u17FA\u05AB\u1802ozenge;\u69EBriangle\u0200;dlr\u1812\u1813\u1818\u181D\u65B4own;\u65BEeft;\u65C2ight;\u65B8k;\u6423\u01B1\u182B\0\u1833\u01B2\u182F\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183E\u184D\u0100;q\u1843\u1846\uC000=\u20E5uiv;\uC000\u2261\u20E5t;\u6310\u0200ptwx\u1859\u185E\u1867\u186Cf;\uC000\u{1D553}\u0100;t\u13CB\u1863om\xBB\u13CCtie;\u62C8\u0600DHUVbdhmptuv\u1885\u1896\u18AA\u18BB\u18D7\u18DB\u18EC\u18FF\u1905\u190A\u1910\u1921\u0200LRlr\u188E\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18A1\u18A2\u18A4\u18A6\u18A8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18B3\u18B5\u18B7\u18B9;\u655D;\u655A;\u655C;\u6559\u0380;HLRhlr\u18CA\u18CB\u18CD\u18CF\u18D1\u18D3\u18D5\u6551;\u656C;\u6563;\u6560;\u656B;\u6562;\u655Fox;\u69C9\u0200LRlr\u18E4\u18E6\u18E8\u18EA;\u6555;\u6552;\u6510;\u650C\u0280;DUdu\u06BD\u18F7\u18F9\u18FB\u18FD;\u6565;\u6568;\u652C;\u6534inus;\u629Flus;\u629Eimes;\u62A0\u0200LRlr\u1919\u191B\u191D\u191F;\u655B;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193B\u6502;\u656A;\u6561;\u655E;\u653C;\u6524;\u651C\u0100ev\u0123\u1942bar\u803B\xA6\u40A6\u0200ceio\u1951\u1956\u195A\u1960r;\uC000\u{1D4B7}mi;\u604Fm\u0100;e\u171A\u171Cl\u0180;bh\u1968\u1969\u196B\u405C;\u69C5sub;\u67C8\u016C\u1974\u197El\u0100;e\u1979\u197A\u6022t\xBB\u197Ap\u0180;Ee\u012F\u1985\u1987;\u6AAE\u0100;q\u06DC\u06DB\u0CE1\u19A7\0\u19E8\u1A11\u1A15\u1A32\0\u1A37\u1A50\0\0\u1AB4\0\0\u1AC1\0\0\u1B21\u1B2E\u1B4D\u1B52\0\u1BFD\0\u1C0C\u0180cpr\u19AD\u19B2\u19DDute;\u4107\u0300;abcds\u19BF\u19C0\u19C4\u19CA\u19D5\u19D9\u6229nd;\u6A44rcup;\u6A49\u0100au\u19CF\u19D2p;\u6A4Bp;\u6A47ot;\u6A40;\uC000\u2229\uFE00\u0100eo\u19E2\u19E5t;\u6041\xEE\u0693\u0200aeiu\u19F0\u19FB\u1A01\u1A05\u01F0\u19F5\0\u19F8s;\u6A4Don;\u410Ddil\u803B\xE7\u40E7rc;\u4109ps\u0100;s\u1A0C\u1A0D\u6A4Cm;\u6A50ot;\u410B\u0180dmn\u1A1B\u1A20\u1A26il\u80BB\xB8\u01ADptyv;\u69B2t\u8100\xA2;e\u1A2D\u1A2E\u40A2r\xE4\u01B2r;\uC000\u{1D520}\u0180cei\u1A3D\u1A40\u1A4Dy;\u4447ck\u0100;m\u1A47\u1A48\u6713ark\xBB\u1A48;\u43C7r\u0380;Ecefms\u1A5F\u1A60\u1A62\u1A6B\u1AA4\u1AAA\u1AAE\u65CB;\u69C3\u0180;el\u1A69\u1A6A\u1A6D\u42C6q;\u6257e\u0261\u1A74\0\0\u1A88rrow\u0100lr\u1A7C\u1A81eft;\u61BAight;\u61BB\u0280RSacd\u1A92\u1A94\u1A96\u1A9A\u1A9F\xBB\u0F47;\u64C8st;\u629Birc;\u629Aash;\u629Dnint;\u6A10id;\u6AEFcir;\u69C2ubs\u0100;u\u1ABB\u1ABC\u6663it\xBB\u1ABC\u02EC\u1AC7\u1AD4\u1AFA\0\u1B0Aon\u0100;e\u1ACD\u1ACE\u403A\u0100;q\xC7\xC6\u026D\u1AD9\0\0\u1AE2a\u0100;t\u1ADE\u1ADF\u402C;\u4040\u0180;fl\u1AE8\u1AE9\u1AEB\u6201\xEE\u1160e\u0100mx\u1AF1\u1AF6ent\xBB\u1AE9e\xF3\u024D\u01E7\u1AFE\0\u1B07\u0100;d\u12BB\u1B02ot;\u6A6Dn\xF4\u0246\u0180fry\u1B10\u1B14\u1B17;\uC000\u{1D554}o\xE4\u0254\u8100\xA9;s\u0155\u1B1Dr;\u6117\u0100ao\u1B25\u1B29rr;\u61B5ss;\u6717\u0100cu\u1B32\u1B37r;\uC000\u{1D4B8}\u0100bp\u1B3C\u1B44\u0100;e\u1B41\u1B42\u6ACF;\u6AD1\u0100;e\u1B49\u1B4A\u6AD0;\u6AD2dot;\u62EF\u0380delprvw\u1B60\u1B6C\u1B77\u1B82\u1BAC\u1BD4\u1BF9arr\u0100lr\u1B68\u1B6A;\u6938;\u6935\u0270\u1B72\0\0\u1B75r;\u62DEc;\u62DFarr\u0100;p\u1B7F\u1B80\u61B6;\u693D\u0300;bcdos\u1B8F\u1B90\u1B96\u1BA1\u1BA5\u1BA8\u622Arcap;\u6A48\u0100au\u1B9B\u1B9Ep;\u6A46p;\u6A4Aot;\u628Dr;\u6A45;\uC000\u222A\uFE00\u0200alrv\u1BB5\u1BBF\u1BDE\u1BE3rr\u0100;m\u1BBC\u1BBD\u61B7;\u693Cy\u0180evw\u1BC7\u1BD4\u1BD8q\u0270\u1BCE\0\0\u1BD2re\xE3\u1B73u\xE3\u1B75ee;\u62CEedge;\u62CFen\u803B\xA4\u40A4earrow\u0100lr\u1BEE\u1BF3eft\xBB\u1B80ight\xBB\u1BBDe\xE4\u1BDD\u0100ci\u1C01\u1C07onin\xF4\u01F7nt;\u6231lcty;\u632D\u0980AHabcdefhijlorstuwz\u1C38\u1C3B\u1C3F\u1C5D\u1C69\u1C75\u1C8A\u1C9E\u1CAC\u1CB7\u1CFB\u1CFF\u1D0D\u1D7B\u1D91\u1DAB\u1DBB\u1DC6\u1DCDr\xF2\u0381ar;\u6965\u0200glrs\u1C48\u1C4D\u1C52\u1C54ger;\u6020eth;\u6138\xF2\u1133h\u0100;v\u1C5A\u1C5B\u6010\xBB\u090A\u016B\u1C61\u1C67arow;\u690Fa\xE3\u0315\u0100ay\u1C6E\u1C73ron;\u410F;\u4434\u0180;ao\u0332\u1C7C\u1C84\u0100gr\u02BF\u1C81r;\u61CAtseq;\u6A77\u0180glm\u1C91\u1C94\u1C98\u803B\xB0\u40B0ta;\u43B4ptyv;\u69B1\u0100ir\u1CA3\u1CA8sht;\u697F;\uC000\u{1D521}ar\u0100lr\u1CB3\u1CB5\xBB\u08DC\xBB\u101E\u0280aegsv\u1CC2\u0378\u1CD6\u1CDC\u1CE0m\u0180;os\u0326\u1CCA\u1CD4nd\u0100;s\u0326\u1CD1uit;\u6666amma;\u43DDin;\u62F2\u0180;io\u1CE7\u1CE8\u1CF8\u40F7de\u8100\xF7;o\u1CE7\u1CF0ntimes;\u62C7n\xF8\u1CF7cy;\u4452c\u026F\u1D06\0\0\u1D0Arn;\u631Eop;\u630D\u0280lptuw\u1D18\u1D1D\u1D22\u1D49\u1D55lar;\u4024f;\uC000\u{1D555}\u0280;emps\u030B\u1D2D\u1D37\u1D3D\u1D42q\u0100;d\u0352\u1D33ot;\u6251inus;\u6238lus;\u6214quare;\u62A1blebarwedg\xE5\xFAn\u0180adh\u112E\u1D5D\u1D67ownarrow\xF3\u1C83arpoon\u0100lr\u1D72\u1D76ef\xF4\u1CB4igh\xF4\u1CB6\u0162\u1D7F\u1D85karo\xF7\u0F42\u026F\u1D8A\0\0\u1D8Ern;\u631Fop;\u630C\u0180cot\u1D98\u1DA3\u1DA6\u0100ry\u1D9D\u1DA1;\uC000\u{1D4B9};\u4455l;\u69F6rok;\u4111\u0100dr\u1DB0\u1DB4ot;\u62F1i\u0100;f\u1DBA\u1816\u65BF\u0100ah\u1DC0\u1DC3r\xF2\u0429a\xF2\u0FA6angle;\u69A6\u0100ci\u1DD2\u1DD5y;\u445Fgrarr;\u67FF\u0900Dacdefglmnopqrstux\u1E01\u1E09\u1E19\u1E38\u0578\u1E3C\u1E49\u1E61\u1E7E\u1EA5\u1EAF\u1EBD\u1EE1\u1F2A\u1F37\u1F44\u1F4E\u1F5A\u0100Do\u1E06\u1D34o\xF4\u1C89\u0100cs\u1E0E\u1E14ute\u803B\xE9\u40E9ter;\u6A6E\u0200aioy\u1E22\u1E27\u1E31\u1E36ron;\u411Br\u0100;c\u1E2D\u1E2E\u6256\u803B\xEA\u40EAlon;\u6255;\u444Dot;\u4117\u0100Dr\u1E41\u1E45ot;\u6252;\uC000\u{1D522}\u0180;rs\u1E50\u1E51\u1E57\u6A9Aave\u803B\xE8\u40E8\u0100;d\u1E5C\u1E5D\u6A96ot;\u6A98\u0200;ils\u1E6A\u1E6B\u1E72\u1E74\u6A99nters;\u63E7;\u6113\u0100;d\u1E79\u1E7A\u6A95ot;\u6A97\u0180aps\u1E85\u1E89\u1E97cr;\u4113ty\u0180;sv\u1E92\u1E93\u1E95\u6205et\xBB\u1E93p\u01001;\u1E9D\u1EA4\u0133\u1EA1\u1EA3;\u6004;\u6005\u6003\u0100gs\u1EAA\u1EAC;\u414Bp;\u6002\u0100gp\u1EB4\u1EB8on;\u4119f;\uC000\u{1D556}\u0180als\u1EC4\u1ECE\u1ED2r\u0100;s\u1ECA\u1ECB\u62D5l;\u69E3us;\u6A71i\u0180;lv\u1EDA\u1EDB\u1EDF\u43B5on\xBB\u1EDB;\u43F5\u0200csuv\u1EEA\u1EF3\u1F0B\u1F23\u0100io\u1EEF\u1E31rc\xBB\u1E2E\u0269\u1EF9\0\0\u1EFB\xED\u0548ant\u0100gl\u1F02\u1F06tr\xBB\u1E5Dess\xBB\u1E7A\u0180aei\u1F12\u1F16\u1F1Als;\u403Dst;\u625Fv\u0100;D\u0235\u1F20D;\u6A78parsl;\u69E5\u0100Da\u1F2F\u1F33ot;\u6253rr;\u6971\u0180cdi\u1F3E\u1F41\u1EF8r;\u612Fo\xF4\u0352\u0100ah\u1F49\u1F4B;\u43B7\u803B\xF0\u40F0\u0100mr\u1F53\u1F57l\u803B\xEB\u40EBo;\u60AC\u0180cip\u1F61\u1F64\u1F67l;\u4021s\xF4\u056E\u0100eo\u1F6C\u1F74ctatio\xEE\u0559nential\xE5\u0579\u09E1\u1F92\0\u1F9E\0\u1FA1\u1FA7\0\0\u1FC6\u1FCC\0\u1FD3\0\u1FE6\u1FEA\u2000\0\u2008\u205Allingdotse\xF1\u1E44y;\u4444male;\u6640\u0180ilr\u1FAD\u1FB3\u1FC1lig;\u8000\uFB03\u0269\u1FB9\0\0\u1FBDg;\u8000\uFB00ig;\u8000\uFB04;\uC000\u{1D523}lig;\u8000\uFB01lig;\uC000fj\u0180alt\u1FD9\u1FDC\u1FE1t;\u666Dig;\u8000\uFB02ns;\u65B1of;\u4192\u01F0\u1FEE\0\u1FF3f;\uC000\u{1D557}\u0100ak\u05BF\u1FF7\u0100;v\u1FFC\u1FFD\u62D4;\u6AD9artint;\u6A0D\u0100ao\u200C\u2055\u0100cs\u2011\u2052\u03B1\u201A\u2030\u2038\u2045\u2048\0\u2050\u03B2\u2022\u2025\u2027\u202A\u202C\0\u202E\u803B\xBD\u40BD;\u6153\u803B\xBC\u40BC;\u6155;\u6159;\u615B\u01B3\u2034\0\u2036;\u6154;\u6156\u02B4\u203E\u2041\0\0\u2043\u803B\xBE\u40BE;\u6157;\u615C5;\u6158\u01B6\u204C\0\u204E;\u615A;\u615D8;\u615El;\u6044wn;\u6322cr;\uC000\u{1D4BB}\u0880Eabcdefgijlnorstv\u2082\u2089\u209F\u20A5\u20B0\u20B4\u20F0\u20F5\u20FA\u20FF\u2103\u2112\u2138\u0317\u213E\u2152\u219E\u0100;l\u064D\u2087;\u6A8C\u0180cmp\u2090\u2095\u209Dute;\u41F5ma\u0100;d\u209C\u1CDA\u43B3;\u6A86reve;\u411F\u0100iy\u20AA\u20AErc;\u411D;\u4433ot;\u4121\u0200;lqs\u063E\u0642\u20BD\u20C9\u0180;qs\u063E\u064C\u20C4lan\xF4\u0665\u0200;cdl\u0665\u20D2\u20D5\u20E5c;\u6AA9ot\u0100;o\u20DC\u20DD\u6A80\u0100;l\u20E2\u20E3\u6A82;\u6A84\u0100;e\u20EA\u20ED\uC000\u22DB\uFE00s;\u6A94r;\uC000\u{1D524}\u0100;g\u0673\u061Bmel;\u6137cy;\u4453\u0200;Eaj\u065A\u210C\u210E\u2110;\u6A92;\u6AA5;\u6AA4\u0200Eaes\u211B\u211D\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6A8Arox\xBB\u2124\u0100;q\u212E\u212F\u6A88\u0100;q\u212E\u211Bim;\u62E7pf;\uC000\u{1D558}\u0100ci\u2143\u2146r;\u610Am\u0180;el\u066B\u214E\u2150;\u6A8E;\u6A90\u8300>;cdlqr\u05EE\u2160\u216A\u216E\u2173\u2179\u0100ci\u2165\u2167;\u6AA7r;\u6A7Aot;\u62D7Par;\u6995uest;\u6A7C\u0280adels\u2184\u216A\u2190\u0656\u219B\u01F0\u2189\0\u218Epro\xF8\u209Er;\u6978q\u0100lq\u063F\u2196les\xF3\u2088i\xED\u066B\u0100en\u21A3\u21ADrtneqq;\uC000\u2269\uFE00\xC5\u21AA\u0500Aabcefkosy\u21C4\u21C7\u21F1\u21F5\u21FA\u2218\u221D\u222F\u2268\u227Dr\xF2\u03A0\u0200ilmr\u21D0\u21D4\u21D7\u21DBrs\xF0\u1484f\xBB\u2024il\xF4\u06A9\u0100dr\u21E0\u21E4cy;\u444A\u0180;cw\u08F4\u21EB\u21EFir;\u6948;\u61ADar;\u610Firc;\u4125\u0180alr\u2201\u220E\u2213rts\u0100;u\u2209\u220A\u6665it\xBB\u220Alip;\u6026con;\u62B9r;\uC000\u{1D525}s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223A\u223E\u2243\u225E\u2263rr;\u61FFtht;\u623Bk\u0100lr\u2249\u2253eftarrow;\u61A9ightarrow;\u61AAf;\uC000\u{1D559}bar;\u6015\u0180clt\u226F\u2274\u2278r;\uC000\u{1D4BD}as\xE8\u21F4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xBB\u1C5B\u0AE1\u22A3\0\u22AA\0\u22B8\u22C5\u22CE\0\u22D5\u22F3\0\0\u22F8\u2322\u2367\u2362\u237F\0\u2386\u23AA\u23B4cute\u803B\xED\u40ED\u0180;iy\u0771\u22B0\u22B5rc\u803B\xEE\u40EE;\u4438\u0100cx\u22BC\u22BFy;\u4435cl\u803B\xA1\u40A1\u0100fr\u039F\u22C9;\uC000\u{1D526}rave\u803B\xEC\u40EC\u0200;ino\u073E\u22DD\u22E9\u22EE\u0100in\u22E2\u22E6nt;\u6A0Ct;\u622Dfin;\u69DCta;\u6129lig;\u4133\u0180aop\u22FE\u231A\u231D\u0180cgt\u2305\u2308\u2317r;\u412B\u0180elp\u071F\u230F\u2313in\xE5\u078Ear\xF4\u0720h;\u4131f;\u62B7ed;\u41B5\u0280;cfot\u04F4\u232C\u2331\u233D\u2341are;\u6105in\u0100;t\u2338\u2339\u621Eie;\u69DDdo\xF4\u2319\u0280;celp\u0757\u234C\u2350\u235B\u2361al;\u62BA\u0100gr\u2355\u2359er\xF3\u1563\xE3\u234Darhk;\u6A17rod;\u6A3C\u0200cgpt\u236F\u2372\u2376\u237By;\u4451on;\u412Ff;\uC000\u{1D55A}a;\u43B9uest\u803B\xBF\u40BF\u0100ci\u238A\u238Fr;\uC000\u{1D4BE}n\u0280;Edsv\u04F4\u239B\u239D\u23A1\u04F3;\u62F9ot;\u62F5\u0100;v\u23A6\u23A7\u62F4;\u62F3\u0100;i\u0777\u23AElde;\u4129\u01EB\u23B8\0\u23BCcy;\u4456l\u803B\xEF\u40EF\u0300cfmosu\u23CC\u23D7\u23DC\u23E1\u23E7\u23F5\u0100iy\u23D1\u23D5rc;\u4135;\u4439r;\uC000\u{1D527}ath;\u4237pf;\uC000\u{1D55B}\u01E3\u23EC\0\u23F1r;\uC000\u{1D4BF}rcy;\u4458kcy;\u4454\u0400acfghjos\u240B\u2416\u2422\u2427\u242D\u2431\u2435\u243Bppa\u0100;v\u2413\u2414\u43BA;\u43F0\u0100ey\u241B\u2420dil;\u4137;\u443Ar;\uC000\u{1D528}reen;\u4138cy;\u4445cy;\u445Cpf;\uC000\u{1D55C}cr;\uC000\u{1D4C0}\u0B80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248D\u2491\u250E\u253D\u255A\u2580\u264E\u265E\u2665\u2679\u267D\u269A\u26B2\u26D8\u275D\u2768\u278B\u27C0\u2801\u2812\u0180art\u2477\u247A\u247Cr\xF2\u09C6\xF2\u0395ail;\u691Barr;\u690E\u0100;g\u0994\u248B;\u6A8Bar;\u6962\u0963\u24A5\0\u24AA\0\u24B1\0\0\0\0\0\u24B5\u24BA\0\u24C6\u24C8\u24CD\0\u24F9ute;\u413Amptyv;\u69B4ra\xEE\u084Cbda;\u43BBg\u0180;dl\u088E\u24C1\u24C3;\u6991\xE5\u088E;\u6A85uo\u803B\xAB\u40ABr\u0400;bfhlpst\u0899\u24DE\u24E6\u24E9\u24EB\u24EE\u24F1\u24F5\u0100;f\u089D\u24E3s;\u691Fs;\u691D\xEB\u2252p;\u61ABl;\u6939im;\u6973l;\u61A2\u0180;ae\u24FF\u2500\u2504\u6AABil;\u6919\u0100;s\u2509\u250A\u6AAD;\uC000\u2AAD\uFE00\u0180abr\u2515\u2519\u251Drr;\u690Crk;\u6772\u0100ak\u2522\u252Cc\u0100ek\u2528\u252A;\u407B;\u405B\u0100es\u2531\u2533;\u698Bl\u0100du\u2539\u253B;\u698F;\u698D\u0200aeuy\u2546\u254B\u2556\u2558ron;\u413E\u0100di\u2550\u2554il;\u413C\xEC\u08B0\xE2\u2529;\u443B\u0200cqrs\u2563\u2566\u256D\u257Da;\u6936uo\u0100;r\u0E19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694Bh;\u61B2\u0280;fgqs\u258B\u258C\u0989\u25F3\u25FF\u6264t\u0280ahlrt\u2598\u25A4\u25B7\u25C2\u25E8rrow\u0100;t\u0899\u25A1a\xE9\u24F6arpoon\u0100du\u25AF\u25B4own\xBB\u045Ap\xBB\u0966eftarrows;\u61C7ight\u0180ahs\u25CD\u25D6\u25DErrow\u0100;s\u08F4\u08A7arpoon\xF3\u0F98quigarro\xF7\u21F0hreetimes;\u62CB\u0180;qs\u258B\u0993\u25FAlan\xF4\u09AC\u0280;cdgs\u09AC\u260A\u260D\u261D\u2628c;\u6AA8ot\u0100;o\u2614\u2615\u6A7F\u0100;r\u261A\u261B\u6A81;\u6A83\u0100;e\u2622\u2625\uC000\u22DA\uFE00s;\u6A93\u0280adegs\u2633\u2639\u263D\u2649\u264Bppro\xF8\u24C6ot;\u62D6q\u0100gq\u2643\u2645\xF4\u0989gt\xF2\u248C\xF4\u099Bi\xED\u09B2\u0180ilr\u2655\u08E1\u265Asht;\u697C;\uC000\u{1D529}\u0100;E\u099C\u2663;\u6A91\u0161\u2669\u2676r\u0100du\u25B2\u266E\u0100;l\u0965\u2673;\u696Alk;\u6584cy;\u4459\u0280;acht\u0A48\u2688\u268B\u2691\u2696r\xF2\u25C1orne\xF2\u1D08ard;\u696Bri;\u65FA\u0100io\u269F\u26A4dot;\u4140ust\u0100;a\u26AC\u26AD\u63B0che\xBB\u26AD\u0200Eaes\u26BB\u26BD\u26C9\u26D4;\u6268p\u0100;p\u26C3\u26C4\u6A89rox\xBB\u26C4\u0100;q\u26CE\u26CF\u6A87\u0100;q\u26CE\u26BBim;\u62E6\u0400abnoptwz\u26E9\u26F4\u26F7\u271A\u272F\u2741\u2747\u2750\u0100nr\u26EE\u26F1g;\u67ECr;\u61FDr\xEB\u08C1g\u0180lmr\u26FF\u270D\u2714eft\u0100ar\u09E6\u2707ight\xE1\u09F2apsto;\u67FCight\xE1\u09FDparrow\u0100lr\u2725\u2729ef\xF4\u24EDight;\u61AC\u0180afl\u2736\u2739\u273Dr;\u6985;\uC000\u{1D55D}us;\u6A2Dimes;\u6A34\u0161\u274B\u274Fst;\u6217\xE1\u134E\u0180;ef\u2757\u2758\u1800\u65CAnge\xBB\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277C\u2785\u2787r\xF2\u08A8orne\xF2\u1D8Car\u0100;d\u0F98\u2783;\u696D;\u600Eri;\u62BF\u0300achiqt\u2798\u279D\u0A40\u27A2\u27AE\u27BBquo;\u6039r;\uC000\u{1D4C1}m\u0180;eg\u09B2\u27AA\u27AC;\u6A8D;\u6A8F\u0100bu\u252A\u27B3o\u0100;r\u0E1F\u27B9;\u601Arok;\u4142\u8400<;cdhilqr\u082B\u27D2\u2639\u27DC\u27E0\u27E5\u27EA\u27F0\u0100ci\u27D7\u27D9;\u6AA6r;\u6A79re\xE5\u25F2mes;\u62C9arr;\u6976uest;\u6A7B\u0100Pi\u27F5\u27F9ar;\u6996\u0180;ef\u2800\u092D\u181B\u65C3r\u0100du\u2807\u280Dshar;\u694Ahar;\u6966\u0100en\u2817\u2821rtneqq;\uC000\u2268\uFE00\xC5\u281E\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288E\u2893\u28A0\u28A5\u28A8\u28DA\u28E2\u28E4\u0A83\u28F3\u2902Dot;\u623A\u0200clpr\u284E\u2852\u2863\u287Dr\u803B\xAF\u40AF\u0100et\u2857\u2859;\u6642\u0100;e\u285E\u285F\u6720se\xBB\u285F\u0100;s\u103B\u2868to\u0200;dlu\u103B\u2873\u2877\u287Bow\xEE\u048Cef\xF4\u090F\xF0\u13D1ker;\u65AE\u0100oy\u2887\u288Cmma;\u6A29;\u443Cash;\u6014asuredangle\xBB\u1626r;\uC000\u{1D52A}o;\u6127\u0180cdn\u28AF\u28B4\u28C9ro\u803B\xB5\u40B5\u0200;acd\u1464\u28BD\u28C0\u28C4s\xF4\u16A7ir;\u6AF0ot\u80BB\xB7\u01B5us\u0180;bd\u28D2\u1903\u28D3\u6212\u0100;u\u1D3C\u28D8;\u6A2A\u0163\u28DE\u28E1p;\u6ADB\xF2\u2212\xF0\u0A81\u0100dp\u28E9\u28EEels;\u62A7f;\uC000\u{1D55E}\u0100ct\u28F8\u28FDr;\uC000\u{1D4C2}pos\xBB\u159D\u0180;lm\u2909\u290A\u290D\u43BCtimap;\u62B8\u0C00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297E\u2989\u2998\u29DA\u29E9\u2A15\u2A1A\u2A58\u2A5D\u2A83\u2A95\u2AA4\u2AA8\u2B04\u2B07\u2B44\u2B7F\u2BAE\u2C34\u2C67\u2C7C\u2CE9\u0100gt\u2947\u294B;\uC000\u22D9\u0338\u0100;v\u2950\u0BCF\uC000\u226B\u20D2\u0180elt\u295A\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61CDightarrow;\u61CE;\uC000\u22D8\u0338\u0100;v\u297B\u0C47\uC000\u226A\u20D2ightarrow;\u61CF\u0100Dd\u298E\u2993ash;\u62AFash;\u62AE\u0280bcnpt\u29A3\u29A7\u29AC\u29B1\u29CCla\xBB\u02DEute;\u4144g;\uC000\u2220\u20D2\u0280;Eiop\u0D84\u29BC\u29C0\u29C5\u29C8;\uC000\u2A70\u0338d;\uC000\u224B\u0338s;\u4149ro\xF8\u0D84ur\u0100;a\u29D3\u29D4\u666El\u0100;s\u29D3\u0B38\u01F3\u29DF\0\u29E3p\u80BB\xA0\u0B37mp\u0100;e\u0BF9\u0C00\u0280aeouy\u29F4\u29FE\u2A03\u2A10\u2A13\u01F0\u29F9\0\u29FB;\u6A43on;\u4148dil;\u4146ng\u0100;d\u0D7E\u2A0Aot;\uC000\u2A6D\u0338p;\u6A42;\u443Dash;\u6013\u0380;Aadqsx\u0B92\u2A29\u2A2D\u2A3B\u2A41\u2A45\u2A50rr;\u61D7r\u0100hr\u2A33\u2A36k;\u6924\u0100;o\u13F2\u13F0ot;\uC000\u2250\u0338ui\xF6\u0B63\u0100ei\u2A4A\u2A4Ear;\u6928\xED\u0B98ist\u0100;s\u0BA0\u0B9Fr;\uC000\u{1D52B}\u0200Eest\u0BC5\u2A66\u2A79\u2A7C\u0180;qs\u0BBC\u2A6D\u0BE1\u0180;qs\u0BBC\u0BC5\u2A74lan\xF4\u0BE2i\xED\u0BEA\u0100;r\u0BB6\u2A81\xBB\u0BB7\u0180Aap\u2A8A\u2A8D\u2A91r\xF2\u2971rr;\u61AEar;\u6AF2\u0180;sv\u0F8D\u2A9C\u0F8C\u0100;d\u2AA1\u2AA2\u62FC;\u62FAcy;\u445A\u0380AEadest\u2AB7\u2ABA\u2ABE\u2AC2\u2AC5\u2AF6\u2AF9r\xF2\u2966;\uC000\u2266\u0338rr;\u619Ar;\u6025\u0200;fqs\u0C3B\u2ACE\u2AE3\u2AEFt\u0100ar\u2AD4\u2AD9rro\xF7\u2AC1ightarro\xF7\u2A90\u0180;qs\u0C3B\u2ABA\u2AEAlan\xF4\u0C55\u0100;s\u0C55\u2AF4\xBB\u0C36i\xED\u0C5D\u0100;r\u0C35\u2AFEi\u0100;e\u0C1A\u0C25i\xE4\u0D90\u0100pt\u2B0C\u2B11f;\uC000\u{1D55F}\u8180\xAC;in\u2B19\u2B1A\u2B36\u40ACn\u0200;Edv\u0B89\u2B24\u2B28\u2B2E;\uC000\u22F9\u0338ot;\uC000\u22F5\u0338\u01E1\u0B89\u2B33\u2B35;\u62F7;\u62F6i\u0100;v\u0CB8\u2B3C\u01E1\u0CB8\u2B41\u2B43;\u62FE;\u62FD\u0180aor\u2B4B\u2B63\u2B69r\u0200;ast\u0B7B\u2B55\u2B5A\u2B5Flle\xEC\u0B7Bl;\uC000\u2AFD\u20E5;\uC000\u2202\u0338lint;\u6A14\u0180;ce\u0C92\u2B70\u2B73u\xE5\u0CA5\u0100;c\u0C98\u2B78\u0100;e\u0C92\u2B7D\xF1\u0C98\u0200Aait\u2B88\u2B8B\u2B9D\u2BA7r\xF2\u2988rr\u0180;cw\u2B94\u2B95\u2B99\u619B;\uC000\u2933\u0338;\uC000\u219D\u0338ghtarrow\xBB\u2B95ri\u0100;e\u0CCB\u0CD6\u0380chimpqu\u2BBD\u2BCD\u2BD9\u2B04\u0B78\u2BE4\u2BEF\u0200;cer\u0D32\u2BC6\u0D37\u2BC9u\xE5\u0D45;\uC000\u{1D4C3}ort\u026D\u2B05\0\0\u2BD6ar\xE1\u2B56m\u0100;e\u0D6E\u2BDF\u0100;q\u0D74\u0D73su\u0100bp\u2BEB\u2BED\xE5\u0CF8\xE5\u0D0B\u0180bcp\u2BF6\u2C11\u2C19\u0200;Ees\u2BFF\u2C00\u0D22\u2C04\u6284;\uC000\u2AC5\u0338et\u0100;e\u0D1B\u2C0Bq\u0100;q\u0D23\u2C00c\u0100;e\u0D32\u2C17\xF1\u0D38\u0200;Ees\u2C22\u2C23\u0D5F\u2C27\u6285;\uC000\u2AC6\u0338et\u0100;e\u0D58\u2C2Eq\u0100;q\u0D60\u2C23\u0200gilr\u2C3D\u2C3F\u2C45\u2C47\xEC\u0BD7lde\u803B\xF1\u40F1\xE7\u0C43iangle\u0100lr\u2C52\u2C5Ceft\u0100;e\u0C1A\u2C5A\xF1\u0C26ight\u0100;e\u0CCB\u2C65\xF1\u0CD7\u0100;m\u2C6C\u2C6D\u43BD\u0180;es\u2C74\u2C75\u2C79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2C8F\u2C94\u2C99\u2C9E\u2CA3\u2CB0\u2CB6\u2CD3\u2CE3ash;\u62ADarr;\u6904p;\uC000\u224D\u20D2ash;\u62AC\u0100et\u2CA8\u2CAC;\uC000\u2265\u20D2;\uC000>\u20D2nfin;\u69DE\u0180Aet\u2CBD\u2CC1\u2CC5rr;\u6902;\uC000\u2264\u20D2\u0100;r\u2CCA\u2CCD\uC000<\u20D2ie;\uC000\u22B4\u20D2\u0100At\u2CD8\u2CDCrr;\u6903rie;\uC000\u22B5\u20D2im;\uC000\u223C\u20D2\u0180Aan\u2CF0\u2CF4\u2D02rr;\u61D6r\u0100hr\u2CFA\u2CFDk;\u6923\u0100;o\u13E7\u13E5ear;\u6927\u1253\u1A95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2D2D\0\u2D38\u2D48\u2D60\u2D65\u2D72\u2D84\u1B07\0\0\u2D8D\u2DAB\0\u2DC8\u2DCE\0\u2DDC\u2E19\u2E2B\u2E3E\u2E43\u0100cs\u2D31\u1A97ute\u803B\xF3\u40F3\u0100iy\u2D3C\u2D45r\u0100;c\u1A9E\u2D42\u803B\xF4\u40F4;\u443E\u0280abios\u1AA0\u2D52\u2D57\u01C8\u2D5Alac;\u4151v;\u6A38old;\u69BClig;\u4153\u0100cr\u2D69\u2D6Dir;\u69BF;\uC000\u{1D52C}\u036F\u2D79\0\0\u2D7C\0\u2D82n;\u42DBave\u803B\xF2\u40F2;\u69C1\u0100bm\u2D88\u0DF4ar;\u69B5\u0200acit\u2D95\u2D98\u2DA5\u2DA8r\xF2\u1A80\u0100ir\u2D9D\u2DA0r;\u69BEoss;\u69BBn\xE5\u0E52;\u69C0\u0180aei\u2DB1\u2DB5\u2DB9cr;\u414Dga;\u43C9\u0180cdn\u2DC0\u2DC5\u01CDron;\u43BF;\u69B6pf;\uC000\u{1D560}\u0180ael\u2DD4\u2DD7\u01D2r;\u69B7rp;\u69B9\u0380;adiosv\u2DEA\u2DEB\u2DEE\u2E08\u2E0D\u2E10\u2E16\u6228r\xF2\u1A86\u0200;efm\u2DF7\u2DF8\u2E02\u2E05\u6A5Dr\u0100;o\u2DFE\u2DFF\u6134f\xBB\u2DFF\u803B\xAA\u40AA\u803B\xBA\u40BAgof;\u62B6r;\u6A56lope;\u6A57;\u6A5B\u0180clo\u2E1F\u2E21\u2E27\xF2\u2E01ash\u803B\xF8\u40F8l;\u6298i\u016C\u2E2F\u2E34de\u803B\xF5\u40F5es\u0100;a\u01DB\u2E3As;\u6A36ml\u803B\xF6\u40F6bar;\u633D\u0AE1\u2E5E\0\u2E7D\0\u2E80\u2E9D\0\u2EA2\u2EB9\0\0\u2ECB\u0E9C\0\u2F13\0\0\u2F2B\u2FBC\0\u2FC8r\u0200;ast\u0403\u2E67\u2E72\u0E85\u8100\xB6;l\u2E6D\u2E6E\u40B6le\xEC\u0403\u0269\u2E78\0\0\u2E7Bm;\u6AF3;\u6AFDy;\u443Fr\u0280cimpt\u2E8B\u2E8F\u2E93\u1865\u2E97nt;\u4025od;\u402Eil;\u6030enk;\u6031r;\uC000\u{1D52D}\u0180imo\u2EA8\u2EB0\u2EB4\u0100;v\u2EAD\u2EAE\u43C6;\u43D5ma\xF4\u0A76ne;\u660E\u0180;tv\u2EBF\u2EC0\u2EC8\u43C0chfork\xBB\u1FFD;\u43D6\u0100au\u2ECF\u2EDFn\u0100ck\u2ED5\u2EDDk\u0100;h\u21F4\u2EDB;\u610E\xF6\u21F4s\u0480;abcdemst\u2EF3\u2EF4\u1908\u2EF9\u2EFD\u2F04\u2F06\u2F0A\u2F0E\u402Bcir;\u6A23ir;\u6A22\u0100ou\u1D40\u2F02;\u6A25;\u6A72n\u80BB\xB1\u0E9Dim;\u6A26wo;\u6A27\u0180ipu\u2F19\u2F20\u2F25ntint;\u6A15f;\uC000\u{1D561}nd\u803B\xA3\u40A3\u0500;Eaceinosu\u0EC8\u2F3F\u2F41\u2F44\u2F47\u2F81\u2F89\u2F92\u2F7E\u2FB6;\u6AB3p;\u6AB7u\xE5\u0ED9\u0100;c\u0ECE\u2F4C\u0300;acens\u0EC8\u2F59\u2F5F\u2F66\u2F68\u2F7Eppro\xF8\u2F43urlye\xF1\u0ED9\xF1\u0ECE\u0180aes\u2F6F\u2F76\u2F7Approx;\u6AB9qq;\u6AB5im;\u62E8i\xED\u0EDFme\u0100;s\u2F88\u0EAE\u6032\u0180Eas\u2F78\u2F90\u2F7A\xF0\u2F75\u0180dfp\u0EEC\u2F99\u2FAF\u0180als\u2FA0\u2FA5\u2FAAlar;\u632Eine;\u6312urf;\u6313\u0100;t\u0EFB\u2FB4\xEF\u0EFBrel;\u62B0\u0100ci\u2FC0\u2FC5r;\uC000\u{1D4C5};\u43C8ncsp;\u6008\u0300fiopsu\u2FDA\u22E2\u2FDF\u2FE5\u2FEB\u2FF1r;\uC000\u{1D52E}pf;\uC000\u{1D562}rime;\u6057cr;\uC000\u{1D4C6}\u0180aeo\u2FF8\u3009\u3013t\u0100ei\u2FFE\u3005rnion\xF3\u06B0nt;\u6A16st\u0100;e\u3010\u3011\u403F\xF1\u1F19\xF4\u0F14\u0A80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30E0\u310E\u312B\u3147\u3162\u3172\u318E\u3206\u3215\u3224\u3229\u3258\u326E\u3272\u3290\u32B0\u32B7\u0180art\u3047\u304A\u304Cr\xF2\u10B3\xF2\u03DDail;\u691Car\xF2\u1C65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307F\u308F\u3094\u30CC\u0100eu\u306D\u3071;\uC000\u223D\u0331te;\u4155i\xE3\u116Emptyv;\u69B3g\u0200;del\u0FD1\u3089\u308B\u308D;\u6992;\u69A5\xE5\u0FD1uo\u803B\xBB\u40BBr\u0580;abcfhlpstw\u0FDC\u30AC\u30AF\u30B7\u30B9\u30BC\u30BE\u30C0\u30C3\u30C7\u30CAp;\u6975\u0100;f\u0FE0\u30B4s;\u6920;\u6933s;\u691E\xEB\u225D\xF0\u272El;\u6945im;\u6974l;\u61A3;\u619D\u0100ai\u30D1\u30D5il;\u691Ao\u0100;n\u30DB\u30DC\u6236al\xF3\u0F1E\u0180abr\u30E7\u30EA\u30EEr\xF2\u17E5rk;\u6773\u0100ak\u30F3\u30FDc\u0100ek\u30F9\u30FB;\u407D;\u405D\u0100es\u3102\u3104;\u698Cl\u0100du\u310A\u310C;\u698E;\u6990\u0200aeuy\u3117\u311C\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xEC\u0FF2\xE2\u30FA;\u4440\u0200clqs\u3134\u3137\u313D\u3144a;\u6937dhar;\u6969uo\u0100;r\u020E\u020Dh;\u61B3\u0180acg\u314E\u315F\u0F44l\u0200;ips\u0F78\u3158\u315B\u109Cn\xE5\u10BBar\xF4\u0FA9t;\u65AD\u0180ilr\u3169\u1023\u316Esht;\u697D;\uC000\u{1D52F}\u0100ao\u3177\u3186r\u0100du\u317D\u317F\xBB\u047B\u0100;l\u1091\u3184;\u696C\u0100;v\u318B\u318C\u43C1;\u43F1\u0180gns\u3195\u31F9\u31FCht\u0300ahlrst\u31A4\u31B0\u31C2\u31D8\u31E4\u31EErrow\u0100;t\u0FDC\u31ADa\xE9\u30C8arpoon\u0100du\u31BB\u31BFow\xEE\u317Ep\xBB\u1092eft\u0100ah\u31CA\u31D0rrow\xF3\u0FEAarpoon\xF3\u0551ightarrows;\u61C9quigarro\xF7\u30CBhreetimes;\u62CCg;\u42DAingdotse\xF1\u1F32\u0180ahm\u320D\u3210\u3213r\xF2\u0FEAa\xF2\u0551;\u600Foust\u0100;a\u321E\u321F\u63B1che\xBB\u321Fmid;\u6AEE\u0200abpt\u3232\u323D\u3240\u3252\u0100nr\u3237\u323Ag;\u67EDr;\u61FEr\xEB\u1003\u0180afl\u3247\u324A\u324Er;\u6986;\uC000\u{1D563}us;\u6A2Eimes;\u6A35\u0100ap\u325D\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6A12ar\xF2\u31E3\u0200achq\u327B\u3280\u10BC\u3285quo;\u603Ar;\uC000\u{1D4C7}\u0100bu\u30FB\u328Ao\u0100;r\u0214\u0213\u0180hir\u3297\u329B\u32A0re\xE5\u31F8mes;\u62CAi\u0200;efl\u32AA\u1059\u1821\u32AB\u65B9tri;\u69CEluhar;\u6968;\u611E\u0D61\u32D5\u32DB\u32DF\u332C\u3338\u3371\0\u337A\u33A4\0\0\u33EC\u33F0\0\u3428\u3448\u345A\u34AD\u34B1\u34CA\u34F1\0\u3616\0\0\u3633cute;\u415Bqu\xEF\u27BA\u0500;Eaceinpsy\u11ED\u32F3\u32F5\u32FF\u3302\u330B\u330F\u331F\u3326\u3329;\u6AB4\u01F0\u32FA\0\u32FC;\u6AB8on;\u4161u\xE5\u11FE\u0100;d\u11F3\u3307il;\u415Frc;\u415D\u0180Eas\u3316\u3318\u331B;\u6AB6p;\u6ABAim;\u62E9olint;\u6A13i\xED\u1204;\u4441ot\u0180;be\u3334\u1D47\u3335\u62C5;\u6A66\u0380Aacmstx\u3346\u334A\u3357\u335B\u335E\u3363\u336Drr;\u61D8r\u0100hr\u3350\u3352\xEB\u2228\u0100;o\u0A36\u0A34t\u803B\xA7\u40A7i;\u403Bwar;\u6929m\u0100in\u3369\xF0nu\xF3\xF1t;\u6736r\u0100;o\u3376\u2055\uC000\u{1D530}\u0200acoy\u3382\u3386\u3391\u33A0rp;\u666F\u0100hy\u338B\u338Fcy;\u4449;\u4448rt\u026D\u3399\0\0\u339Ci\xE4\u1464ara\xEC\u2E6F\u803B\xAD\u40AD\u0100gm\u33A8\u33B4ma\u0180;fv\u33B1\u33B2\u33B2\u43C3;\u43C2\u0400;deglnpr\u12AB\u33C5\u33C9\u33CE\u33D6\u33DE\u33E1\u33E6ot;\u6A6A\u0100;q\u12B1\u12B0\u0100;E\u33D3\u33D4\u6A9E;\u6AA0\u0100;E\u33DB\u33DC\u6A9D;\u6A9Fe;\u6246lus;\u6A24arr;\u6972ar\xF2\u113D\u0200aeit\u33F8\u3408\u340F\u3417\u0100ls\u33FD\u3404lsetm\xE9\u336Ahp;\u6A33parsl;\u69E4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341C\u341D\u6AAA\u0100;s\u3422\u3423\u6AAC;\uC000\u2AAC\uFE00\u0180flp\u342E\u3433\u3442tcy;\u444C\u0100;b\u3438\u3439\u402F\u0100;a\u343E\u343F\u69C4r;\u633Ff;\uC000\u{1D564}a\u0100dr\u344D\u0402es\u0100;u\u3454\u3455\u6660it\xBB\u3455\u0180csu\u3460\u3479\u349F\u0100au\u3465\u346Fp\u0100;s\u1188\u346B;\uC000\u2293\uFE00p\u0100;s\u11B4\u3475;\uC000\u2294\uFE00u\u0100bp\u347F\u348F\u0180;es\u1197\u119C\u3486et\u0100;e\u1197\u348D\xF1\u119D\u0180;es\u11A8\u11AD\u3496et\u0100;e\u11A8\u349D\xF1\u11AE\u0180;af\u117B\u34A6\u05B0r\u0165\u34AB\u05B1\xBB\u117Car\xF2\u1148\u0200cemt\u34B9\u34BE\u34C2\u34C5r;\uC000\u{1D4C8}tm\xEE\xF1i\xEC\u3415ar\xE6\u11BE\u0100ar\u34CE\u34D5r\u0100;f\u34D4\u17BF\u6606\u0100an\u34DA\u34EDight\u0100ep\u34E3\u34EApsilo\xEE\u1EE0h\xE9\u2EAFs\xBB\u2852\u0280bcmnp\u34FB\u355E\u1209\u358B\u358E\u0480;Edemnprs\u350E\u350F\u3511\u3515\u351E\u3523\u352C\u3531\u3536\u6282;\u6AC5ot;\u6ABD\u0100;d\u11DA\u351Aot;\u6AC3ult;\u6AC1\u0100Ee\u3528\u352A;\u6ACB;\u628Alus;\u6ABFarr;\u6979\u0180eiu\u353D\u3552\u3555t\u0180;en\u350E\u3545\u354Bq\u0100;q\u11DA\u350Feq\u0100;q\u352B\u3528m;\u6AC7\u0100bp\u355A\u355C;\u6AD5;\u6AD3c\u0300;acens\u11ED\u356C\u3572\u3579\u357B\u3326ppro\xF8\u32FAurlye\xF1\u11FE\xF1\u11F3\u0180aes\u3582\u3588\u331Bppro\xF8\u331Aq\xF1\u3317g;\u666A\u0680123;Edehlmnps\u35A9\u35AC\u35AF\u121C\u35B2\u35B4\u35C0\u35C9\u35D5\u35DA\u35DF\u35E8\u35ED\u803B\xB9\u40B9\u803B\xB2\u40B2\u803B\xB3\u40B3;\u6AC6\u0100os\u35B9\u35BCt;\u6ABEub;\u6AD8\u0100;d\u1222\u35C5ot;\u6AC4s\u0100ou\u35CF\u35D2l;\u67C9b;\u6AD7arr;\u697Bult;\u6AC2\u0100Ee\u35E4\u35E6;\u6ACC;\u628Blus;\u6AC0\u0180eiu\u35F4\u3609\u360Ct\u0180;en\u121C\u35FC\u3602q\u0100;q\u1222\u35B2eq\u0100;q\u35E7\u35E4m;\u6AC8\u0100bp\u3611\u3613;\u6AD4;\u6AD6\u0180Aan\u361C\u3620\u362Drr;\u61D9r\u0100hr\u3626\u3628\xEB\u222E\u0100;o\u0A2B\u0A29war;\u692Alig\u803B\xDF\u40DF\u0BE1\u3651\u365D\u3660\u12CE\u3673\u3679\0\u367E\u36C2\0\0\0\0\0\u36DB\u3703\0\u3709\u376C\0\0\0\u3787\u0272\u3656\0\0\u365Bget;\u6316;\u43C4r\xEB\u0E5F\u0180aey\u3666\u366B\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uC000\u{1D531}\u0200eiko\u3686\u369D\u36B5\u36BC\u01F2\u368B\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369B\u43B8ym;\u43D1\u0100cn\u36A2\u36B2k\u0100as\u36A8\u36AEppro\xF8\u12C1im\xBB\u12ACs\xF0\u129E\u0100as\u36BA\u36AE\xF0\u12C1rn\u803B\xFE\u40FE\u01EC\u031F\u36C6\u22E7es\u8180\xD7;bd\u36CF\u36D0\u36D8\u40D7\u0100;a\u190F\u36D5r;\u6A31;\u6A30\u0180eps\u36E1\u36E3\u3700\xE1\u2A4D\u0200;bcf\u0486\u36EC\u36F0\u36F4ot;\u6336ir;\u6AF1\u0100;o\u36F9\u36FC\uC000\u{1D565}rk;\u6ADA\xE1\u3362rime;\u6034\u0180aip\u370F\u3712\u3764d\xE5\u1248\u0380adempst\u3721\u374D\u3740\u3751\u3757\u375C\u375Fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65B5own\xBB\u1DBBeft\u0100;e\u2800\u373E\xF1\u092E;\u625Cight\u0100;e\u32AA\u374B\xF1\u105Aot;\u65ECinus;\u6A3Alus;\u6A39b;\u69CDime;\u6A3Bezium;\u63E2\u0180cht\u3772\u377D\u3781\u0100ry\u3777\u377B;\uC000\u{1D4C9};\u4446cy;\u445Brok;\u4167\u0100io\u378B\u378Ex\xF4\u1777head\u0100lr\u3797\u37A0eftarro\xF7\u084Fightarrow\xBB\u0F5D\u0900AHabcdfghlmoprstuw\u37D0\u37D3\u37D7\u37E4\u37F0\u37FC\u380E\u381C\u3823\u3834\u3851\u385D\u386B\u38A9\u38CC\u38D2\u38EA\u38F6r\xF2\u03EDar;\u6963\u0100cr\u37DC\u37E2ute\u803B\xFA\u40FA\xF2\u1150r\u01E3\u37EA\0\u37EDy;\u445Eve;\u416D\u0100iy\u37F5\u37FArc\u803B\xFB\u40FB;\u4443\u0180abh\u3803\u3806\u380Br\xF2\u13ADlac;\u4171a\xF2\u13C3\u0100ir\u3813\u3818sht;\u697E;\uC000\u{1D532}rave\u803B\xF9\u40F9\u0161\u3827\u3831r\u0100lr\u382C\u382E\xBB\u0957\xBB\u1083lk;\u6580\u0100ct\u3839\u384D\u026F\u383F\0\0\u384Arn\u0100;e\u3845\u3846\u631Cr\xBB\u3846op;\u630Fri;\u65F8\u0100al\u3856\u385Acr;\u416B\u80BB\xA8\u0349\u0100gp\u3862\u3866on;\u4173f;\uC000\u{1D566}\u0300adhlsu\u114B\u3878\u387D\u1372\u3891\u38A0own\xE1\u13B3arpoon\u0100lr\u3888\u388Cef\xF4\u382Digh\xF4\u382Fi\u0180;hl\u3899\u389A\u389C\u43C5\xBB\u13FAon\xBB\u389Aparrows;\u61C8\u0180cit\u38B0\u38C4\u38C8\u026F\u38B6\0\0\u38C1rn\u0100;e\u38BC\u38BD\u631Dr\xBB\u38BDop;\u630Eng;\u416Fri;\u65F9cr;\uC000\u{1D4CA}\u0180dir\u38D9\u38DD\u38E2ot;\u62F0lde;\u4169i\u0100;f\u3730\u38E8\xBB\u1813\u0100am\u38EF\u38F2r\xF2\u38A8l\u803B\xFC\u40FCangle;\u69A7\u0780ABDacdeflnoprsz\u391C\u391F\u3929\u392D\u39B5\u39B8\u39BD\u39DF\u39E4\u39E8\u39F3\u39F9\u39FD\u3A01\u3A20r\xF2\u03F7ar\u0100;v\u3926\u3927\u6AE8;\u6AE9as\xE8\u03E1\u0100nr\u3932\u3937grt;\u699C\u0380eknprst\u34E3\u3946\u394B\u3952\u395D\u3964\u3996app\xE1\u2415othin\xE7\u1E96\u0180hir\u34EB\u2EC8\u3959op\xF4\u2FB5\u0100;h\u13B7\u3962\xEF\u318D\u0100iu\u3969\u396Dgm\xE1\u33B3\u0100bp\u3972\u3984setneq\u0100;q\u397D\u3980\uC000\u228A\uFE00;\uC000\u2ACB\uFE00setneq\u0100;q\u398F\u3992\uC000\u228B\uFE00;\uC000\u2ACC\uFE00\u0100hr\u399B\u399Fet\xE1\u369Ciangle\u0100lr\u39AA\u39AFeft\xBB\u0925ight\xBB\u1051y;\u4432ash\xBB\u1036\u0180elr\u39C4\u39D2\u39D7\u0180;be\u2DEA\u39CB\u39CFar;\u62BBq;\u625Alip;\u62EE\u0100bt\u39DC\u1468a\xF2\u1469r;\uC000\u{1D533}tr\xE9\u39AEsu\u0100bp\u39EF\u39F1\xBB\u0D1C\xBB\u0D59pf;\uC000\u{1D567}ro\xF0\u0EFBtr\xE9\u39B4\u0100cu\u3A06\u3A0Br;\uC000\u{1D4CB}\u0100bp\u3A10\u3A18n\u0100Ee\u3980\u3A16\xBB\u397En\u0100Ee\u3992\u3A1E\xBB\u3990igzag;\u699A\u0380cefoprs\u3A36\u3A3B\u3A56\u3A5B\u3A54\u3A61\u3A6Airc;\u4175\u0100di\u3A40\u3A51\u0100bg\u3A45\u3A49ar;\u6A5Fe\u0100;q\u15FA\u3A4F;\u6259erp;\u6118r;\uC000\u{1D534}pf;\uC000\u{1D568}\u0100;e\u1479\u3A66at\xE8\u1479cr;\uC000\u{1D4CC}\u0AE3\u178E\u3A87\0\u3A8B\0\u3A90\u3A9B\0\0\u3A9D\u3AA8\u3AAB\u3AAF\0\0\u3AC3\u3ACE\0\u3AD8\u17DC\u17DFtr\xE9\u17D1r;\uC000\u{1D535}\u0100Aa\u3A94\u3A97r\xF2\u03C3r\xF2\u09F6;\u43BE\u0100Aa\u3AA1\u3AA4r\xF2\u03B8r\xF2\u09EBa\xF0\u2713is;\u62FB\u0180dpt\u17A4\u3AB5\u3ABE\u0100fl\u3ABA\u17A9;\uC000\u{1D569}im\xE5\u17B2\u0100Aa\u3AC7\u3ACAr\xF2\u03CEr\xF2\u0A01\u0100cq\u3AD2\u17B8r;\uC000\u{1D4CD}\u0100pt\u17D6\u3ADCr\xE9\u17D4\u0400acefiosu\u3AF0\u3AFD\u3B08\u3B0C\u3B11\u3B15\u3B1B\u3B21c\u0100uy\u3AF6\u3AFBte\u803B\xFD\u40FD;\u444F\u0100iy\u3B02\u3B06rc;\u4177;\u444Bn\u803B\xA5\u40A5r;\uC000\u{1D536}cy;\u4457pf;\uC000\u{1D56A}cr;\uC000\u{1D4CE}\u0100cm\u3B26\u3B29y;\u444El\u803B\xFF\u40FF\u0500acdefhiosw\u3B42\u3B48\u3B54\u3B58\u3B64\u3B69\u3B6D\u3B74\u3B7A\u3B80cute;\u417A\u0100ay\u3B4D\u3B52ron;\u417E;\u4437ot;\u417C\u0100et\u3B5D\u3B61tr\xE6\u155Fa;\u43B6r;\uC000\u{1D537}cy;\u4436grarr;\u61DDpf;\uC000\u{1D56B}cr;\uC000\u{1D4CF}\u0100jn\u3B85\u3B87;\u600Dj;\u600C'.split("").map(e=>e.charCodeAt(0)))});var Id,YA=v(()=>{Id=new Uint16Array("\u0200aglq \x1B\u026D\0\0p;\u4026os;\u4027t;\u403Et;\u403Cuot;\u4022".split("").map(e=>e.charCodeAt(0)))});function H0(e){var t;return e>=55296&&e<=57343||e>1114111?65533:(t=XR.get(e))!==null&&t!==void 0?t:e}var $0,XR,Xo,U0=v(()=>{XR=new Map([[0,65533],[128,8364],[130,8218],[131,402],[132,8222],[133,8230],[134,8224],[135,8225],[136,710],[137,8240],[138,352],[139,8249],[140,338],[142,381],[145,8216],[146,8217],[147,8220],[148,8221],[149,8226],[150,8211],[151,8212],[152,732],[153,8482],[154,353],[155,8250],[156,339],[158,382],[159,376]]),Xo=($0=String.fromCodePoint)!==null&&$0!==void 0?$0:function(e){let t="";return e>65535&&(e-=65536,t+=String.fromCharCode(e>>>10&1023|55296),e=56320|e&1023),t+=String.fromCharCode(e),t}});function V0(e){return e>=or.ZERO&&e<=or.NINE}function JR(e){return e>=or.UPPER_A&&e<=or.UPPER_F||e>=or.LOWER_A&&e<=or.LOWER_F}function eL(e){return e>=or.UPPER_A&&e<=or.UPPER_Z||e>=or.LOWER_A&&e<=or.LOWER_Z||V0(e)}function tL(e){return e===or.EQUALS||eL(e)}function KA(e){let t="",r=new Ha(e,n=>t+=Xo(n));return function(i,a){let o=0,l=0;for(;(l=i.indexOf("&",l))>=0;){t+=i.slice(o,l),r.startEntity(a);let p=r.write(i,l+1);if(p<0){o=l+r.end();break}o=l+p,l=p===0?o+1:o}let d=t+i.slice(o);return t="",d}}function rL(e,t,r,n){let i=(t&$a.BRANCH_LENGTH)>>7,a=t&$a.JUMP_TABLE;if(i===0)return a!==0&&n===a?r:-1;if(a){let d=n-a;return d<0||d>=i?-1:e[r+d]-1}let o=r,l=o+i-1;for(;o<=l;){let d=o+l>>>1,p=e[d];if(pn)l=d-1;else return e[d+i]}return-1}var or,ZR,$a,sr,Dr,Ha,Nre,Ore,Zo=v(()=>{zA();YA();U0();U0();(function(e){e[e.NUM=35]="NUM",e[e.SEMI=59]="SEMI",e[e.EQUALS=61]="EQUALS",e[e.ZERO=48]="ZERO",e[e.NINE=57]="NINE",e[e.LOWER_A=97]="LOWER_A",e[e.LOWER_F=102]="LOWER_F",e[e.LOWER_X=120]="LOWER_X",e[e.LOWER_Z=122]="LOWER_Z",e[e.UPPER_A=65]="UPPER_A",e[e.UPPER_F=70]="UPPER_F",e[e.UPPER_Z=90]="UPPER_Z"})(or||(or={}));ZR=32;(function(e){e[e.VALUE_LENGTH=49152]="VALUE_LENGTH",e[e.BRANCH_LENGTH=16256]="BRANCH_LENGTH",e[e.JUMP_TABLE=127]="JUMP_TABLE"})($a||($a={}));(function(e){e[e.EntityStart=0]="EntityStart",e[e.NumericStart=1]="NumericStart",e[e.NumericDecimal=2]="NumericDecimal",e[e.NumericHex=3]="NumericHex",e[e.NamedEntity=4]="NamedEntity"})(sr||(sr={}));(function(e){e[e.Legacy=0]="Legacy",e[e.Strict=1]="Strict",e[e.Attribute=2]="Attribute"})(Dr||(Dr={}));Ha=class{constructor(t,r,n){this.decodeTree=t,this.emitCodePoint=r,this.errors=n,this.state=sr.EntityStart,this.consumed=1,this.result=0,this.treeIndex=0,this.excess=1,this.decodeMode=Dr.Strict}startEntity(t){this.decodeMode=t,this.state=sr.EntityStart,this.result=0,this.treeIndex=0,this.excess=1,this.consumed=1}write(t,r){switch(this.state){case sr.EntityStart:return t.charCodeAt(r)===or.NUM?(this.state=sr.NumericStart,this.consumed+=1,this.stateNumericStart(t,r+1)):(this.state=sr.NamedEntity,this.stateNamedEntity(t,r));case sr.NumericStart:return this.stateNumericStart(t,r);case sr.NumericDecimal:return this.stateNumericDecimal(t,r);case sr.NumericHex:return this.stateNumericHex(t,r);case sr.NamedEntity:return this.stateNamedEntity(t,r)}}stateNumericStart(t,r){return r>=t.length?-1:(t.charCodeAt(r)|ZR)===or.LOWER_X?(this.state=sr.NumericHex,this.consumed+=1,this.stateNumericHex(t,r+1)):(this.state=sr.NumericDecimal,this.stateNumericDecimal(t,r))}addToNumericResult(t,r,n,i){if(r!==n){let a=n-r;this.result=this.result*Math.pow(i,a)+parseInt(t.substr(r,a),i),this.consumed+=a}}stateNumericHex(t,r){let n=r;for(;r>14;for(;r>14,a!==0){if(o===or.SEMI)return this.emitNamedEntityData(this.treeIndex,a,this.consumed+this.excess);this.decodeMode!==Dr.Strict&&(this.result=this.treeIndex,this.consumed+=this.excess,this.excess=0)}}return-1}emitNotTerminatedNamedEntity(){var t;let{result:r,decodeTree:n}=this,i=(n[r]&$a.VALUE_LENGTH)>>14;return this.emitNamedEntityData(r,i,this.consumed),(t=this.errors)===null||t===void 0||t.missingSemicolonAfterCharacterReference(),this.consumed}emitNamedEntityData(t,r,n){let{decodeTree:i}=this;return this.emitCodePoint(r===1?i[t]&~$a.VALUE_LENGTH:i[t+1],n),r===3&&this.emitCodePoint(i[t+2],n),n}end(){var t;switch(this.state){case sr.NamedEntity:return this.result!==0&&(this.decodeMode!==Dr.Attribute||this.result===this.treeIndex)?this.emitNotTerminatedNamedEntity():0;case sr.NumericDecimal:return this.emitNumericEntity(0,2);case sr.NumericHex:return this.emitNumericEntity(0,3);case sr.NumericStart:return(t=this.errors)===null||t===void 0||t.absenceOfDigitsInNumericCharacterReference(this.consumed),0;case sr.EntityStart:return 0}}};Nre=KA(Qo),Ore=KA(Id)});function Nd(e){for(let t=1;t{nL=new Map(Nd([[9," "],[0," "],[22,"!"],[0,"""],[0,"#"],[0,"$"],[0,"%"],[0,"&"],[0,"'"],[0,"("],[0,")"],[0,"*"],[0,"+"],[0,","],[1,"."],[0,"/"],[10,":"],[0,";"],[0,{v:"<",n:8402,o:"<⃒"}],[0,{v:"=",n:8421,o:"=⃥"}],[0,{v:">",n:8402,o:">⃒"}],[0,"?"],[0,"@"],[26,"["],[0,"\"],[0,"]"],[0,"^"],[0,"_"],[0,"`"],[5,{n:106,o:"fj"}],[20,"{"],[0,"|"],[0,"}"],[34," "],[0,"¡"],[0,"¢"],[0,"£"],[0,"¤"],[0,"¥"],[0,"¦"],[0,"§"],[0,"¨"],[0,"©"],[0,"ª"],[0,"«"],[0,"¬"],[0,"­"],[0,"®"],[0,"¯"],[0,"°"],[0,"±"],[0,"²"],[0,"³"],[0,"´"],[0,"µ"],[0,"¶"],[0,"·"],[0,"¸"],[0,"¹"],[0,"º"],[0,"»"],[0,"¼"],[0,"½"],[0,"¾"],[0,"¿"],[0,"À"],[0,"Á"],[0,"Â"],[0,"Ã"],[0,"Ä"],[0,"Å"],[0,"Æ"],[0,"Ç"],[0,"È"],[0,"É"],[0,"Ê"],[0,"Ë"],[0,"Ì"],[0,"Í"],[0,"Î"],[0,"Ï"],[0,"Ð"],[0,"Ñ"],[0,"Ò"],[0,"Ó"],[0,"Ô"],[0,"Õ"],[0,"Ö"],[0,"×"],[0,"Ø"],[0,"Ù"],[0,"Ú"],[0,"Û"],[0,"Ü"],[0,"Ý"],[0,"Þ"],[0,"ß"],[0,"à"],[0,"á"],[0,"â"],[0,"ã"],[0,"ä"],[0,"å"],[0,"æ"],[0,"ç"],[0,"è"],[0,"é"],[0,"ê"],[0,"ë"],[0,"ì"],[0,"í"],[0,"î"],[0,"ï"],[0,"ð"],[0,"ñ"],[0,"ò"],[0,"ó"],[0,"ô"],[0,"õ"],[0,"ö"],[0,"÷"],[0,"ø"],[0,"ù"],[0,"ú"],[0,"û"],[0,"ü"],[0,"ý"],[0,"þ"],[0,"ÿ"],[0,"Ā"],[0,"ā"],[0,"Ă"],[0,"ă"],[0,"Ą"],[0,"ą"],[0,"Ć"],[0,"ć"],[0,"Ĉ"],[0,"ĉ"],[0,"Ċ"],[0,"ċ"],[0,"Č"],[0,"č"],[0,"Ď"],[0,"ď"],[0,"Đ"],[0,"đ"],[0,"Ē"],[0,"ē"],[2,"Ė"],[0,"ė"],[0,"Ę"],[0,"ę"],[0,"Ě"],[0,"ě"],[0,"Ĝ"],[0,"ĝ"],[0,"Ğ"],[0,"ğ"],[0,"Ġ"],[0,"ġ"],[0,"Ģ"],[1,"Ĥ"],[0,"ĥ"],[0,"Ħ"],[0,"ħ"],[0,"Ĩ"],[0,"ĩ"],[0,"Ī"],[0,"ī"],[2,"Į"],[0,"į"],[0,"İ"],[0,"ı"],[0,"IJ"],[0,"ij"],[0,"Ĵ"],[0,"ĵ"],[0,"Ķ"],[0,"ķ"],[0,"ĸ"],[0,"Ĺ"],[0,"ĺ"],[0,"Ļ"],[0,"ļ"],[0,"Ľ"],[0,"ľ"],[0,"Ŀ"],[0,"ŀ"],[0,"Ł"],[0,"ł"],[0,"Ń"],[0,"ń"],[0,"Ņ"],[0,"ņ"],[0,"Ň"],[0,"ň"],[0,"ʼn"],[0,"Ŋ"],[0,"ŋ"],[0,"Ō"],[0,"ō"],[2,"Ő"],[0,"ő"],[0,"Œ"],[0,"œ"],[0,"Ŕ"],[0,"ŕ"],[0,"Ŗ"],[0,"ŗ"],[0,"Ř"],[0,"ř"],[0,"Ś"],[0,"ś"],[0,"Ŝ"],[0,"ŝ"],[0,"Ş"],[0,"ş"],[0,"Š"],[0,"š"],[0,"Ţ"],[0,"ţ"],[0,"Ť"],[0,"ť"],[0,"Ŧ"],[0,"ŧ"],[0,"Ũ"],[0,"ũ"],[0,"Ū"],[0,"ū"],[0,"Ŭ"],[0,"ŭ"],[0,"Ů"],[0,"ů"],[0,"Ű"],[0,"ű"],[0,"Ų"],[0,"ų"],[0,"Ŵ"],[0,"ŵ"],[0,"Ŷ"],[0,"ŷ"],[0,"Ÿ"],[0,"Ź"],[0,"ź"],[0,"Ż"],[0,"ż"],[0,"Ž"],[0,"ž"],[19,"ƒ"],[34,"Ƶ"],[63,"ǵ"],[65,"ȷ"],[142,"ˆ"],[0,"ˇ"],[16,"˘"],[0,"˙"],[0,"˚"],[0,"˛"],[0,"˜"],[0,"˝"],[51,"̑"],[127,"Α"],[0,"Β"],[0,"Γ"],[0,"Δ"],[0,"Ε"],[0,"Ζ"],[0,"Η"],[0,"Θ"],[0,"Ι"],[0,"Κ"],[0,"Λ"],[0,"Μ"],[0,"Ν"],[0,"Ξ"],[0,"Ο"],[0,"Π"],[0,"Ρ"],[1,"Σ"],[0,"Τ"],[0,"Υ"],[0,"Φ"],[0,"Χ"],[0,"Ψ"],[0,"Ω"],[7,"α"],[0,"β"],[0,"γ"],[0,"δ"],[0,"ε"],[0,"ζ"],[0,"η"],[0,"θ"],[0,"ι"],[0,"κ"],[0,"λ"],[0,"μ"],[0,"ν"],[0,"ξ"],[0,"ο"],[0,"π"],[0,"ρ"],[0,"ς"],[0,"σ"],[0,"τ"],[0,"υ"],[0,"φ"],[0,"χ"],[0,"ψ"],[0,"ω"],[7,"ϑ"],[0,"ϒ"],[2,"ϕ"],[0,"ϖ"],[5,"Ϝ"],[0,"ϝ"],[18,"ϰ"],[0,"ϱ"],[3,"ϵ"],[0,"϶"],[10,"Ё"],[0,"Ђ"],[0,"Ѓ"],[0,"Є"],[0,"Ѕ"],[0,"І"],[0,"Ї"],[0,"Ј"],[0,"Љ"],[0,"Њ"],[0,"Ћ"],[0,"Ќ"],[1,"Ў"],[0,"Џ"],[0,"А"],[0,"Б"],[0,"В"],[0,"Г"],[0,"Д"],[0,"Е"],[0,"Ж"],[0,"З"],[0,"И"],[0,"Й"],[0,"К"],[0,"Л"],[0,"М"],[0,"Н"],[0,"О"],[0,"П"],[0,"Р"],[0,"С"],[0,"Т"],[0,"У"],[0,"Ф"],[0,"Х"],[0,"Ц"],[0,"Ч"],[0,"Ш"],[0,"Щ"],[0,"Ъ"],[0,"Ы"],[0,"Ь"],[0,"Э"],[0,"Ю"],[0,"Я"],[0,"а"],[0,"б"],[0,"в"],[0,"г"],[0,"д"],[0,"е"],[0,"ж"],[0,"з"],[0,"и"],[0,"й"],[0,"к"],[0,"л"],[0,"м"],[0,"н"],[0,"о"],[0,"п"],[0,"р"],[0,"с"],[0,"т"],[0,"у"],[0,"ф"],[0,"х"],[0,"ц"],[0,"ч"],[0,"ш"],[0,"щ"],[0,"ъ"],[0,"ы"],[0,"ь"],[0,"э"],[0,"ю"],[0,"я"],[1,"ё"],[0,"ђ"],[0,"ѓ"],[0,"є"],[0,"ѕ"],[0,"і"],[0,"ї"],[0,"ј"],[0,"љ"],[0,"њ"],[0,"ћ"],[0,"ќ"],[1,"ў"],[0,"џ"],[7074," "],[0," "],[0," "],[0," "],[1," "],[0," "],[0," "],[0," "],[0,"​"],[0,"‌"],[0,"‍"],[0,"‎"],[0,"‏"],[0,"‐"],[2,"–"],[0,"—"],[0,"―"],[0,"‖"],[1,"‘"],[0,"’"],[0,"‚"],[1,"“"],[0,"”"],[0,"„"],[1,"†"],[0,"‡"],[0,"•"],[2,"‥"],[0,"…"],[9,"‰"],[0,"‱"],[0,"′"],[0,"″"],[0,"‴"],[0,"‵"],[3,"‹"],[0,"›"],[3,"‾"],[2,"⁁"],[1,"⁃"],[0,"⁄"],[10,"⁏"],[7,"⁗"],[7,{v:" ",n:8202,o:"  "}],[0,"⁠"],[0,"⁡"],[0,"⁢"],[0,"⁣"],[72,"€"],[46,"⃛"],[0,"⃜"],[37,"ℂ"],[2,"℅"],[4,"ℊ"],[0,"ℋ"],[0,"ℌ"],[0,"ℍ"],[0,"ℎ"],[0,"ℏ"],[0,"ℐ"],[0,"ℑ"],[0,"ℒ"],[0,"ℓ"],[1,"ℕ"],[0,"№"],[0,"℗"],[0,"℘"],[0,"ℙ"],[0,"ℚ"],[0,"ℛ"],[0,"ℜ"],[0,"ℝ"],[0,"℞"],[3,"™"],[1,"ℤ"],[2,"℧"],[0,"ℨ"],[0,"℩"],[2,"ℬ"],[0,"ℭ"],[1,"ℯ"],[0,"ℰ"],[0,"ℱ"],[1,"ℳ"],[0,"ℴ"],[0,"ℵ"],[0,"ℶ"],[0,"ℷ"],[0,"ℸ"],[12,"ⅅ"],[0,"ⅆ"],[0,"ⅇ"],[0,"ⅈ"],[10,"⅓"],[0,"⅔"],[0,"⅕"],[0,"⅖"],[0,"⅗"],[0,"⅘"],[0,"⅙"],[0,"⅚"],[0,"⅛"],[0,"⅜"],[0,"⅝"],[0,"⅞"],[49,"←"],[0,"↑"],[0,"→"],[0,"↓"],[0,"↔"],[0,"↕"],[0,"↖"],[0,"↗"],[0,"↘"],[0,"↙"],[0,"↚"],[0,"↛"],[1,{v:"↝",n:824,o:"↝̸"}],[0,"↞"],[0,"↟"],[0,"↠"],[0,"↡"],[0,"↢"],[0,"↣"],[0,"↤"],[0,"↥"],[0,"↦"],[0,"↧"],[1,"↩"],[0,"↪"],[0,"↫"],[0,"↬"],[0,"↭"],[0,"↮"],[1,"↰"],[0,"↱"],[0,"↲"],[0,"↳"],[1,"↵"],[0,"↶"],[0,"↷"],[2,"↺"],[0,"↻"],[0,"↼"],[0,"↽"],[0,"↾"],[0,"↿"],[0,"⇀"],[0,"⇁"],[0,"⇂"],[0,"⇃"],[0,"⇄"],[0,"⇅"],[0,"⇆"],[0,"⇇"],[0,"⇈"],[0,"⇉"],[0,"⇊"],[0,"⇋"],[0,"⇌"],[0,"⇍"],[0,"⇎"],[0,"⇏"],[0,"⇐"],[0,"⇑"],[0,"⇒"],[0,"⇓"],[0,"⇔"],[0,"⇕"],[0,"⇖"],[0,"⇗"],[0,"⇘"],[0,"⇙"],[0,"⇚"],[0,"⇛"],[1,"⇝"],[6,"⇤"],[0,"⇥"],[15,"⇵"],[7,"⇽"],[0,"⇾"],[0,"⇿"],[0,"∀"],[0,"∁"],[0,{v:"∂",n:824,o:"∂̸"}],[0,"∃"],[0,"∄"],[0,"∅"],[1,"∇"],[0,"∈"],[0,"∉"],[1,"∋"],[0,"∌"],[2,"∏"],[0,"∐"],[0,"∑"],[0,"−"],[0,"∓"],[0,"∔"],[1,"∖"],[0,"∗"],[0,"∘"],[1,"√"],[2,"∝"],[0,"∞"],[0,"∟"],[0,{v:"∠",n:8402,o:"∠⃒"}],[0,"∡"],[0,"∢"],[0,"∣"],[0,"∤"],[0,"∥"],[0,"∦"],[0,"∧"],[0,"∨"],[0,{v:"∩",n:65024,o:"∩︀"}],[0,{v:"∪",n:65024,o:"∪︀"}],[0,"∫"],[0,"∬"],[0,"∭"],[0,"∮"],[0,"∯"],[0,"∰"],[0,"∱"],[0,"∲"],[0,"∳"],[0,"∴"],[0,"∵"],[0,"∶"],[0,"∷"],[0,"∸"],[1,"∺"],[0,"∻"],[0,{v:"∼",n:8402,o:"∼⃒"}],[0,{v:"∽",n:817,o:"∽̱"}],[0,{v:"∾",n:819,o:"∾̳"}],[0,"∿"],[0,"≀"],[0,"≁"],[0,{v:"≂",n:824,o:"≂̸"}],[0,"≃"],[0,"≄"],[0,"≅"],[0,"≆"],[0,"≇"],[0,"≈"],[0,"≉"],[0,"≊"],[0,{v:"≋",n:824,o:"≋̸"}],[0,"≌"],[0,{v:"≍",n:8402,o:"≍⃒"}],[0,{v:"≎",n:824,o:"≎̸"}],[0,{v:"≏",n:824,o:"≏̸"}],[0,{v:"≐",n:824,o:"≐̸"}],[0,"≑"],[0,"≒"],[0,"≓"],[0,"≔"],[0,"≕"],[0,"≖"],[0,"≗"],[1,"≙"],[0,"≚"],[1,"≜"],[2,"≟"],[0,"≠"],[0,{v:"≡",n:8421,o:"≡⃥"}],[0,"≢"],[1,{v:"≤",n:8402,o:"≤⃒"}],[0,{v:"≥",n:8402,o:"≥⃒"}],[0,{v:"≦",n:824,o:"≦̸"}],[0,{v:"≧",n:824,o:"≧̸"}],[0,{v:"≨",n:65024,o:"≨︀"}],[0,{v:"≩",n:65024,o:"≩︀"}],[0,{v:"≪",n:new Map(Nd([[824,"≪̸"],[7577,"≪⃒"]]))}],[0,{v:"≫",n:new Map(Nd([[824,"≫̸"],[7577,"≫⃒"]]))}],[0,"≬"],[0,"≭"],[0,"≮"],[0,"≯"],[0,"≰"],[0,"≱"],[0,"≲"],[0,"≳"],[0,"≴"],[0,"≵"],[0,"≶"],[0,"≷"],[0,"≸"],[0,"≹"],[0,"≺"],[0,"≻"],[0,"≼"],[0,"≽"],[0,"≾"],[0,{v:"≿",n:824,o:"≿̸"}],[0,"⊀"],[0,"⊁"],[0,{v:"⊂",n:8402,o:"⊂⃒"}],[0,{v:"⊃",n:8402,o:"⊃⃒"}],[0,"⊄"],[0,"⊅"],[0,"⊆"],[0,"⊇"],[0,"⊈"],[0,"⊉"],[0,{v:"⊊",n:65024,o:"⊊︀"}],[0,{v:"⊋",n:65024,o:"⊋︀"}],[1,"⊍"],[0,"⊎"],[0,{v:"⊏",n:824,o:"⊏̸"}],[0,{v:"⊐",n:824,o:"⊐̸"}],[0,"⊑"],[0,"⊒"],[0,{v:"⊓",n:65024,o:"⊓︀"}],[0,{v:"⊔",n:65024,o:"⊔︀"}],[0,"⊕"],[0,"⊖"],[0,"⊗"],[0,"⊘"],[0,"⊙"],[0,"⊚"],[0,"⊛"],[1,"⊝"],[0,"⊞"],[0,"⊟"],[0,"⊠"],[0,"⊡"],[0,"⊢"],[0,"⊣"],[0,"⊤"],[0,"⊥"],[1,"⊧"],[0,"⊨"],[0,"⊩"],[0,"⊪"],[0,"⊫"],[0,"⊬"],[0,"⊭"],[0,"⊮"],[0,"⊯"],[0,"⊰"],[1,"⊲"],[0,"⊳"],[0,{v:"⊴",n:8402,o:"⊴⃒"}],[0,{v:"⊵",n:8402,o:"⊵⃒"}],[0,"⊶"],[0,"⊷"],[0,"⊸"],[0,"⊹"],[0,"⊺"],[0,"⊻"],[1,"⊽"],[0,"⊾"],[0,"⊿"],[0,"⋀"],[0,"⋁"],[0,"⋂"],[0,"⋃"],[0,"⋄"],[0,"⋅"],[0,"⋆"],[0,"⋇"],[0,"⋈"],[0,"⋉"],[0,"⋊"],[0,"⋋"],[0,"⋌"],[0,"⋍"],[0,"⋎"],[0,"⋏"],[0,"⋐"],[0,"⋑"],[0,"⋒"],[0,"⋓"],[0,"⋔"],[0,"⋕"],[0,"⋖"],[0,"⋗"],[0,{v:"⋘",n:824,o:"⋘̸"}],[0,{v:"⋙",n:824,o:"⋙̸"}],[0,{v:"⋚",n:65024,o:"⋚︀"}],[0,{v:"⋛",n:65024,o:"⋛︀"}],[2,"⋞"],[0,"⋟"],[0,"⋠"],[0,"⋡"],[0,"⋢"],[0,"⋣"],[2,"⋦"],[0,"⋧"],[0,"⋨"],[0,"⋩"],[0,"⋪"],[0,"⋫"],[0,"⋬"],[0,"⋭"],[0,"⋮"],[0,"⋯"],[0,"⋰"],[0,"⋱"],[0,"⋲"],[0,"⋳"],[0,"⋴"],[0,{v:"⋵",n:824,o:"⋵̸"}],[0,"⋶"],[0,"⋷"],[1,{v:"⋹",n:824,o:"⋹̸"}],[0,"⋺"],[0,"⋻"],[0,"⋼"],[0,"⋽"],[0,"⋾"],[6,"⌅"],[0,"⌆"],[1,"⌈"],[0,"⌉"],[0,"⌊"],[0,"⌋"],[0,"⌌"],[0,"⌍"],[0,"⌎"],[0,"⌏"],[0,"⌐"],[1,"⌒"],[0,"⌓"],[1,"⌕"],[0,"⌖"],[5,"⌜"],[0,"⌝"],[0,"⌞"],[0,"⌟"],[2,"⌢"],[0,"⌣"],[9,"⌭"],[0,"⌮"],[7,"⌶"],[6,"⌽"],[1,"⌿"],[60,"⍼"],[51,"⎰"],[0,"⎱"],[2,"⎴"],[0,"⎵"],[0,"⎶"],[37,"⏜"],[0,"⏝"],[0,"⏞"],[0,"⏟"],[2,"⏢"],[4,"⏧"],[59,"␣"],[164,"Ⓢ"],[55,"─"],[1,"│"],[9,"┌"],[3,"┐"],[3,"└"],[3,"┘"],[3,"├"],[7,"┤"],[7,"┬"],[7,"┴"],[7,"┼"],[19,"═"],[0,"║"],[0,"╒"],[0,"╓"],[0,"╔"],[0,"╕"],[0,"╖"],[0,"╗"],[0,"╘"],[0,"╙"],[0,"╚"],[0,"╛"],[0,"╜"],[0,"╝"],[0,"╞"],[0,"╟"],[0,"╠"],[0,"╡"],[0,"╢"],[0,"╣"],[0,"╤"],[0,"╥"],[0,"╦"],[0,"╧"],[0,"╨"],[0,"╩"],[0,"╪"],[0,"╫"],[0,"╬"],[19,"▀"],[3,"▄"],[3,"█"],[8,"░"],[0,"▒"],[0,"▓"],[13,"□"],[8,"▪"],[0,"▫"],[1,"▭"],[0,"▮"],[2,"▱"],[1,"△"],[0,"▴"],[0,"▵"],[2,"▸"],[0,"▹"],[3,"▽"],[0,"▾"],[0,"▿"],[2,"◂"],[0,"◃"],[6,"◊"],[0,"○"],[32,"◬"],[2,"◯"],[8,"◸"],[0,"◹"],[0,"◺"],[0,"◻"],[0,"◼"],[8,"★"],[0,"☆"],[7,"☎"],[49,"♀"],[1,"♂"],[29,"♠"],[2,"♣"],[1,"♥"],[0,"♦"],[3,"♪"],[2,"♭"],[0,"♮"],[0,"♯"],[163,"✓"],[3,"✗"],[8,"✠"],[21,"✶"],[33,"❘"],[25,"❲"],[0,"❳"],[84,"⟈"],[0,"⟉"],[28,"⟦"],[0,"⟧"],[0,"⟨"],[0,"⟩"],[0,"⟪"],[0,"⟫"],[0,"⟬"],[0,"⟭"],[7,"⟵"],[0,"⟶"],[0,"⟷"],[0,"⟸"],[0,"⟹"],[0,"⟺"],[1,"⟼"],[2,"⟿"],[258,"⤂"],[0,"⤃"],[0,"⤄"],[0,"⤅"],[6,"⤌"],[0,"⤍"],[0,"⤎"],[0,"⤏"],[0,"⤐"],[0,"⤑"],[0,"⤒"],[0,"⤓"],[2,"⤖"],[2,"⤙"],[0,"⤚"],[0,"⤛"],[0,"⤜"],[0,"⤝"],[0,"⤞"],[0,"⤟"],[0,"⤠"],[2,"⤣"],[0,"⤤"],[0,"⤥"],[0,"⤦"],[0,"⤧"],[0,"⤨"],[0,"⤩"],[0,"⤪"],[8,{v:"⤳",n:824,o:"⤳̸"}],[1,"⤵"],[0,"⤶"],[0,"⤷"],[0,"⤸"],[0,"⤹"],[2,"⤼"],[0,"⤽"],[7,"⥅"],[2,"⥈"],[0,"⥉"],[0,"⥊"],[0,"⥋"],[2,"⥎"],[0,"⥏"],[0,"⥐"],[0,"⥑"],[0,"⥒"],[0,"⥓"],[0,"⥔"],[0,"⥕"],[0,"⥖"],[0,"⥗"],[0,"⥘"],[0,"⥙"],[0,"⥚"],[0,"⥛"],[0,"⥜"],[0,"⥝"],[0,"⥞"],[0,"⥟"],[0,"⥠"],[0,"⥡"],[0,"⥢"],[0,"⥣"],[0,"⥤"],[0,"⥥"],[0,"⥦"],[0,"⥧"],[0,"⥨"],[0,"⥩"],[0,"⥪"],[0,"⥫"],[0,"⥬"],[0,"⥭"],[0,"⥮"],[0,"⥯"],[0,"⥰"],[0,"⥱"],[0,"⥲"],[0,"⥳"],[0,"⥴"],[0,"⥵"],[0,"⥶"],[1,"⥸"],[0,"⥹"],[1,"⥻"],[0,"⥼"],[0,"⥽"],[0,"⥾"],[0,"⥿"],[5,"⦅"],[0,"⦆"],[4,"⦋"],[0,"⦌"],[0,"⦍"],[0,"⦎"],[0,"⦏"],[0,"⦐"],[0,"⦑"],[0,"⦒"],[0,"⦓"],[0,"⦔"],[0,"⦕"],[0,"⦖"],[3,"⦚"],[1,"⦜"],[0,"⦝"],[6,"⦤"],[0,"⦥"],[0,"⦦"],[0,"⦧"],[0,"⦨"],[0,"⦩"],[0,"⦪"],[0,"⦫"],[0,"⦬"],[0,"⦭"],[0,"⦮"],[0,"⦯"],[0,"⦰"],[0,"⦱"],[0,"⦲"],[0,"⦳"],[0,"⦴"],[0,"⦵"],[0,"⦶"],[0,"⦷"],[1,"⦹"],[1,"⦻"],[0,"⦼"],[1,"⦾"],[0,"⦿"],[0,"⧀"],[0,"⧁"],[0,"⧂"],[0,"⧃"],[0,"⧄"],[0,"⧅"],[3,"⧉"],[3,"⧍"],[0,"⧎"],[0,{v:"⧏",n:824,o:"⧏̸"}],[0,{v:"⧐",n:824,o:"⧐̸"}],[11,"⧜"],[0,"⧝"],[0,"⧞"],[4,"⧣"],[0,"⧤"],[0,"⧥"],[5,"⧫"],[8,"⧴"],[1,"⧶"],[9,"⨀"],[0,"⨁"],[0,"⨂"],[1,"⨄"],[1,"⨆"],[5,"⨌"],[0,"⨍"],[2,"⨐"],[0,"⨑"],[0,"⨒"],[0,"⨓"],[0,"⨔"],[0,"⨕"],[0,"⨖"],[0,"⨗"],[10,"⨢"],[0,"⨣"],[0,"⨤"],[0,"⨥"],[0,"⨦"],[0,"⨧"],[1,"⨩"],[0,"⨪"],[2,"⨭"],[0,"⨮"],[0,"⨯"],[0,"⨰"],[0,"⨱"],[1,"⨳"],[0,"⨴"],[0,"⨵"],[0,"⨶"],[0,"⨷"],[0,"⨸"],[0,"⨹"],[0,"⨺"],[0,"⨻"],[0,"⨼"],[2,"⨿"],[0,"⩀"],[1,"⩂"],[0,"⩃"],[0,"⩄"],[0,"⩅"],[0,"⩆"],[0,"⩇"],[0,"⩈"],[0,"⩉"],[0,"⩊"],[0,"⩋"],[0,"⩌"],[0,"⩍"],[2,"⩐"],[2,"⩓"],[0,"⩔"],[0,"⩕"],[0,"⩖"],[0,"⩗"],[0,"⩘"],[1,"⩚"],[0,"⩛"],[0,"⩜"],[0,"⩝"],[1,"⩟"],[6,"⩦"],[3,"⩪"],[2,{v:"⩭",n:824,o:"⩭̸"}],[0,"⩮"],[0,"⩯"],[0,{v:"⩰",n:824,o:"⩰̸"}],[0,"⩱"],[0,"⩲"],[0,"⩳"],[0,"⩴"],[0,"⩵"],[1,"⩷"],[0,"⩸"],[0,"⩹"],[0,"⩺"],[0,"⩻"],[0,"⩼"],[0,{v:"⩽",n:824,o:"⩽̸"}],[0,{v:"⩾",n:824,o:"⩾̸"}],[0,"⩿"],[0,"⪀"],[0,"⪁"],[0,"⪂"],[0,"⪃"],[0,"⪄"],[0,"⪅"],[0,"⪆"],[0,"⪇"],[0,"⪈"],[0,"⪉"],[0,"⪊"],[0,"⪋"],[0,"⪌"],[0,"⪍"],[0,"⪎"],[0,"⪏"],[0,"⪐"],[0,"⪑"],[0,"⪒"],[0,"⪓"],[0,"⪔"],[0,"⪕"],[0,"⪖"],[0,"⪗"],[0,"⪘"],[0,"⪙"],[0,"⪚"],[2,"⪝"],[0,"⪞"],[0,"⪟"],[0,"⪠"],[0,{v:"⪡",n:824,o:"⪡̸"}],[0,{v:"⪢",n:824,o:"⪢̸"}],[1,"⪤"],[0,"⪥"],[0,"⪦"],[0,"⪧"],[0,"⪨"],[0,"⪩"],[0,"⪪"],[0,"⪫"],[0,{v:"⪬",n:65024,o:"⪬︀"}],[0,{v:"⪭",n:65024,o:"⪭︀"}],[0,"⪮"],[0,{v:"⪯",n:824,o:"⪯̸"}],[0,{v:"⪰",n:824,o:"⪰̸"}],[2,"⪳"],[0,"⪴"],[0,"⪵"],[0,"⪶"],[0,"⪷"],[0,"⪸"],[0,"⪹"],[0,"⪺"],[0,"⪻"],[0,"⪼"],[0,"⪽"],[0,"⪾"],[0,"⪿"],[0,"⫀"],[0,"⫁"],[0,"⫂"],[0,"⫃"],[0,"⫄"],[0,{v:"⫅",n:824,o:"⫅̸"}],[0,{v:"⫆",n:824,o:"⫆̸"}],[0,"⫇"],[0,"⫈"],[2,{v:"⫋",n:65024,o:"⫋︀"}],[0,{v:"⫌",n:65024,o:"⫌︀"}],[2,"⫏"],[0,"⫐"],[0,"⫑"],[0,"⫒"],[0,"⫓"],[0,"⫔"],[0,"⫕"],[0,"⫖"],[0,"⫗"],[0,"⫘"],[0,"⫙"],[0,"⫚"],[0,"⫛"],[8,"⫤"],[1,"⫦"],[0,"⫧"],[0,"⫨"],[0,"⫩"],[1,"⫫"],[0,"⫬"],[0,"⫭"],[0,"⫮"],[0,"⫯"],[0,"⫰"],[0,"⫱"],[0,"⫲"],[0,"⫳"],[9,{v:"⫽",n:8421,o:"⫽⃥"}],[44343,{n:new Map(Nd([[56476,"𝒜"],[1,"𝒞"],[0,"𝒟"],[2,"𝒢"],[2,"𝒥"],[0,"𝒦"],[2,"𝒩"],[0,"𝒪"],[0,"𝒫"],[0,"𝒬"],[1,"𝒮"],[0,"𝒯"],[0,"𝒰"],[0,"𝒱"],[0,"𝒲"],[0,"𝒳"],[0,"𝒴"],[0,"𝒵"],[0,"𝒶"],[0,"𝒷"],[0,"𝒸"],[0,"𝒹"],[1,"𝒻"],[1,"𝒽"],[0,"𝒾"],[0,"𝒿"],[0,"𝓀"],[0,"𝓁"],[0,"𝓂"],[0,"𝓃"],[1,"𝓅"],[0,"𝓆"],[0,"𝓇"],[0,"𝓈"],[0,"𝓉"],[0,"𝓊"],[0,"𝓋"],[0,"𝓌"],[0,"𝓍"],[0,"𝓎"],[0,"𝓏"],[52,"𝔄"],[0,"𝔅"],[1,"𝔇"],[0,"𝔈"],[0,"𝔉"],[0,"𝔊"],[2,"𝔍"],[0,"𝔎"],[0,"𝔏"],[0,"𝔐"],[0,"𝔑"],[0,"𝔒"],[0,"𝔓"],[0,"𝔔"],[1,"𝔖"],[0,"𝔗"],[0,"𝔘"],[0,"𝔙"],[0,"𝔚"],[0,"𝔛"],[0,"𝔜"],[1,"𝔞"],[0,"𝔟"],[0,"𝔠"],[0,"𝔡"],[0,"𝔢"],[0,"𝔣"],[0,"𝔤"],[0,"𝔥"],[0,"𝔦"],[0,"𝔧"],[0,"𝔨"],[0,"𝔩"],[0,"𝔪"],[0,"𝔫"],[0,"𝔬"],[0,"𝔭"],[0,"𝔮"],[0,"𝔯"],[0,"𝔰"],[0,"𝔱"],[0,"𝔲"],[0,"𝔳"],[0,"𝔴"],[0,"𝔵"],[0,"𝔶"],[0,"𝔷"],[0,"𝔸"],[0,"𝔹"],[1,"𝔻"],[0,"𝔼"],[0,"𝔽"],[0,"𝔾"],[1,"𝕀"],[0,"𝕁"],[0,"𝕂"],[0,"𝕃"],[0,"𝕄"],[1,"𝕆"],[3,"𝕊"],[0,"𝕋"],[0,"𝕌"],[0,"𝕍"],[0,"𝕎"],[0,"𝕏"],[0,"𝕐"],[1,"𝕒"],[0,"𝕓"],[0,"𝕔"],[0,"𝕕"],[0,"𝕖"],[0,"𝕗"],[0,"𝕘"],[0,"𝕙"],[0,"𝕚"],[0,"𝕛"],[0,"𝕜"],[0,"𝕝"],[0,"𝕞"],[0,"𝕟"],[0,"𝕠"],[0,"𝕡"],[0,"𝕢"],[0,"𝕣"],[0,"𝕤"],[0,"𝕥"],[0,"𝕦"],[0,"𝕧"],[0,"𝕨"],[0,"𝕩"],[0,"𝕪"],[0,"𝕫"]]))}],[8906,"ff"],[0,"fi"],[0,"fl"],[0,"ffi"],[0,"ffl"]]))});function zc(e){let t="",r=0,n;for(;(n=q0.exec(e))!==null;){let i=n.index,a=e.charCodeAt(i),o=WA.get(a);o!==void 0?(t+=e.substring(r,i)+o,r=i+1):(t+=`${e.substring(r,i)}&#x${GA(e,i).toString(16)};`,r=q0.lastIndex+=+((a&64512)===55296))}return t+e.substr(r)}function z0(e,t){return function(n){let i,a=0,o="";for(;i=e.exec(n);)a!==i.index&&(o+=n.substring(a,i.index)),o+=t.get(i[0].charCodeAt(0)),a=i.index+1;return o+n.substring(a)}}var q0,WA,GA,QA,Jo,eu,Yc=v(()=>{q0=/["&'<>$\x80-\uFFFF]/g,WA=new Map([[34,"""],[38,"&"],[39,"'"],[60,"<"],[62,">"]]),GA=String.prototype.codePointAt!=null?(e,t)=>e.codePointAt(t):(e,t)=>(e.charCodeAt(t)&64512)===55296?(e.charCodeAt(t)-55296)*1024+e.charCodeAt(t+1)-56320+65536:e.charCodeAt(t);QA=z0(/[&<>'"]/g,WA),Jo=z0(/["&\u00A0]/g,new Map([[34,"""],[38,"&"],[160," "]])),eu=z0(/[&<>\u00A0]/g,new Map([[38,"&"],[60,"<"],[62,">"],[160," "]]))});var Y0=v(()=>{jA();Yc()});var XA,ZA,t2=v(()=>{Zo();Y0();Yc();Yc();Y0();Zo();(function(e){e[e.XML=0]="XML",e[e.HTML=1]="HTML"})(XA||(XA={}));(function(e){e[e.UTF8=0]="UTF8",e[e.ASCII=1]="ASCII",e[e.Extensive=2]="Extensive",e[e.Attribute=3]="Attribute",e[e.Text=4]="Text"})(ZA||(ZA={}))});var r2,n2,i2=v(()=>{r2=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),n2=new Map(["definitionURL","attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e]))});function sL(e){return e.replace(/"/g,""")}function oL(e,t){var r;if(!e)return;let n=((r=t.encodeEntities)!==null&&r!==void 0?r:t.decodeEntities)===!1?sL:t.xmlMode||t.encodeEntities!=="utf8"?zc:Jo;return Object.keys(e).map(i=>{var a,o;let l=(a=e[i])!==null&&a!==void 0?a:"";return t.xmlMode==="foreign"&&(i=(o=n2.get(i))!==null&&o!==void 0?o:i),!t.emptyAttrs&&!t.xmlMode&&l===""?i:`${i}="${n(l)}"`}).join(" ")}function W0(e,t={}){let r="length"in e?e:[e],n="";for(let i=0;i0&&(n+=W0(e.children,t)),(t.xmlMode||!a2.has(e.name))&&(n+=``)),n}function dL(e){return`<${e.data}>`}function hL(e,t){var r;let n=e.data||"";return((r=t.encodeEntities)!==null&&r!==void 0?r:t.decodeEntities)!==!1&&!(!t.xmlMode&&e.parent&&aL.has(e.parent.name))&&(n=t.xmlMode||t.encodeEntities!=="utf8"?zc(n):eu(n)),n}function pL(e){return``}function mL(e){return``}var aL,a2,Od,cL,lL,G0=v(()=>{Ko();t2();i2();aL=new Set(["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"]);a2=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]);Od=W0;cL=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignObject","desc","title"]),lL=new Set(["svg","math"])});function s2(e,t){return Od(e,t)}function gL(e,t){return ht(e)?e.children.map(r=>s2(r,t)).join(""):""}function Dd(e){return Array.isArray(e)?e.map(Dd).join(""):_e(e)?e.name==="br"?` -`:Dd(e.children):jo(e)?Dd(e.children):nn(e)?e.data:""}function ra(e){return Array.isArray(e)?e.map(ra).join(""):ht(e)&&!$s(e)?ra(e.children):nn(e)?e.data:""}function Kc(e){return Array.isArray(e)?e.map(Kc).join(""):ht(e)&&(e.type===Ze.Tag||jo(e))?Kc(e.children):nn(e)?e.data:""}var Q0=v(()=>{_r();G0();Ko()});function tu(e){return ht(e)?e.children:[]}function o2(e){return e.parent||null}function X0(e){let t=o2(e);if(t!=null)return tu(t);let r=[e],{prev:n,next:i}=e;for(;n!=null;)r.unshift(n),{prev:n}=n;for(;i!=null;)r.push(i),{next:i}=i;return r}function _L(e,t){var r;return(r=e.attribs)===null||r===void 0?void 0:r[t]}function bL(e,t){return e.attribs!=null&&Object.prototype.hasOwnProperty.call(e.attribs,t)&&e.attribs[t]!=null}function EL(e){return e.name}function kd(e){let{next:t}=e;for(;t!==null&&!_e(t);)({next:t}=t);return t}function Rd(e){let{prev:t}=e;for(;t!==null&&!_e(t);)({prev:t}=t);return t}var u2=v(()=>{_r()});function na(e){if(e.prev&&(e.prev.next=e.next),e.next&&(e.next.prev=e.prev),e.parent){let t=e.parent.children,r=t.lastIndexOf(e);r>=0&&t.splice(r,1)}e.next=null,e.prev=null,e.parent=null}function vL(e,t){let r=t.prev=e.prev;r&&(r.next=t);let n=t.next=e.next;n&&(n.prev=t);let i=t.parent=e.parent;if(i){let a=i.children;a[a.lastIndexOf(e)]=t,e.parent=null}}function TL(e,t){if(na(t),t.next=null,t.parent=e,e.children.push(t)>1){let r=e.children[e.children.length-2];r.next=t,t.prev=r}else t.prev=null}function xL(e,t){na(t);let{parent:r}=e,n=e.next;if(t.next=n,t.prev=e,e.next=t,t.parent=r,n){if(n.prev=t,r){let i=r.children;i.splice(i.lastIndexOf(n),0,t)}}else r&&r.children.push(t)}function yL(e,t){if(na(t),t.parent=e,t.prev=null,e.children.unshift(t)!==1){let r=e.children[1];r.prev=t,t.next=r}else t.next=null}function AL(e,t){na(t);let{parent:r}=e;if(r){let n=r.children;n.splice(n.indexOf(e),0,t)}e.prev&&(e.prev.next=t),t.parent=r,t.prev=e.prev,t.next=e,e.prev=t}var c2=v(()=>{});function ru(e,t,r=!0,n=1/0){return Ld(e,Array.isArray(t)?t:[t],r,n)}function Ld(e,t,r,n){let i=[],a=[Array.isArray(t)?t:[t]],o=[0];for(;;){if(o[0]>=a[0].length){if(o.length===1)return i;a.shift(),o.shift();continue}let l=a[0][o[0]++];if(e(l)&&(i.push(l),--n<=0))return i;r&&ht(l)&&l.children.length>0&&(o.unshift(0),a.unshift(l.children))}}function wL(e,t){return t.find(e)}function Pd(e,t,r=!0){let n=Array.isArray(t)?t:[t];for(let i=0;i0){let o=Pd(e,a.children,!0);if(o)return o}}return null}function l2(e,t){return(Array.isArray(t)?t:[t]).some(r=>_e(r)&&e(r)||ht(r)&&l2(e,r.children))}function SL(e,t){let r=[],n=[Array.isArray(t)?t:[t]],i=[0];for(;;){if(i[0]>=n[0].length){if(n.length===1)return r;n.shift(),i.shift();continue}let a=n[0][i[0]++];_e(a)&&e(a)&&r.push(a),ht(a)&&a.children.length>0&&(i.unshift(0),n.unshift(a.children))}}var Z0=v(()=>{_r()});function J0(e,t){return typeof t=="function"?r=>_e(r)&&t(r.attribs[e]):r=>_e(r)&&r.attribs[e]===t}function CL(e,t){return r=>e(r)||t(r)}function f2(e){let t=Object.keys(e).map(r=>{let n=e[r];return Object.prototype.hasOwnProperty.call(Md,r)?Md[r](n):J0(r,n)});return t.length===0?null:t.reduce(CL)}function IL(e,t){let r=f2(e);return r?r(t):!0}function NL(e,t,r,n=1/0){let i=f2(e);return i?ru(i,t,r,n):[]}function OL(e,t,r=!0){return Array.isArray(t)||(t=[t]),Pd(J0("id",e),t,r)}function Hs(e,t,r=!0,n=1/0){return ru(Md.tag_name(e),t,r,n)}function DL(e,t,r=!0,n=1/0){return ru(J0("class",e),t,r,n)}function kL(e,t,r=!0,n=1/0){return ru(Md.tag_type(e),t,r,n)}var Md,eg=v(()=>{_r();Z0();Md={tag_name(e){return typeof e=="function"?t=>_e(t)&&e(t.name):e==="*"?_e:t=>_e(t)&&t.name===e},tag_type(e){return typeof e=="function"?t=>e(t.type):t=>t.type===e},tag_contains(e){return typeof e=="function"?t=>nn(t)&&e(t.data):t=>nn(t)&&t.data===e}}});function RL(e){let t=e.length;for(;--t>=0;){let r=e[t];if(t>0&&e.lastIndexOf(r,t-1)>=0){e.splice(t,1);continue}for(let n=r.parent;n;n=n.parent)if(e.includes(n)){e.splice(t,1);break}}return e}function d2(e,t){let r=[],n=[];if(e===t)return 0;let i=ht(e)?e:e.parent;for(;i;)r.unshift(i),i=i.parent;for(i=ht(t)?t:t.parent;i;)n.unshift(i),i=i.parent;let a=Math.min(r.length,n.length),o=0;for(;od.indexOf(g)?l===t?$n.FOLLOWING|$n.CONTAINED_BY:$n.FOLLOWING:l===e?$n.PRECEDING|$n.CONTAINS:$n.PRECEDING}function Ua(e){return e=e.filter((t,r,n)=>!n.includes(t,r+1)),e.sort((t,r)=>{let n=d2(t,r);return n&$n.PRECEDING?-1:n&$n.FOLLOWING?1:0}),e}var $n,h2=v(()=>{_r();(function(e){e[e.DISCONNECTED=1]="DISCONNECTED",e[e.PRECEDING=2]="PRECEDING",e[e.FOLLOWING=4]="FOLLOWING",e[e.CONTAINS=8]="CONTAINS",e[e.CONTAINED_BY=16]="CONTAINED_BY"})($n||($n={}))});function tg(e){let t=Fd(BL,e);return t?t.name==="feed"?LL(t):PL(t):null}function LL(e){var t;let r=e.children,n={type:"atom",items:Hs("entry",r).map(o=>{var l;let{children:d}=o,p={media:p2(d)};an(p,"id","id",d),an(p,"title","title",d);let g=(l=Fd("link",d))===null||l===void 0?void 0:l.attribs.href;g&&(p.link=g);let E=Va("summary",d)||Va("content",d);E&&(p.description=E);let _=Va("updated",d);return _&&(p.pubDate=new Date(_)),p})};an(n,"id","id",r),an(n,"title","title",r);let i=(t=Fd("link",r))===null||t===void 0?void 0:t.attribs.href;i&&(n.link=i),an(n,"description","subtitle",r);let a=Va("updated",r);return a&&(n.updated=new Date(a)),an(n,"author","email",r,!0),n}function PL(e){var t,r;let n=(r=(t=Fd("channel",e.children))===null||t===void 0?void 0:t.children)!==null&&r!==void 0?r:[],i={type:e.name.substr(0,3),id:"",items:Hs("item",e.children).map(o=>{let{children:l}=o,d={media:p2(l)};an(d,"id","guid",l),an(d,"title","title",l),an(d,"link","link",l),an(d,"description","description",l);let p=Va("pubDate",l)||Va("dc:date",l);return p&&(d.pubDate=new Date(p)),d})};an(i,"title","title",n),an(i,"link","link",n),an(i,"description","description",n);let a=Va("lastBuildDate",n);return a&&(i.updated=new Date(a)),an(i,"author","managingEditor",n,!0),i}function p2(e){return Hs("media:content",e).map(t=>{let{attribs:r}=t,n={medium:r.medium,isDefault:!!r.isDefault};for(let i of ML)r[i]&&(n[i]=r[i]);for(let i of FL)r[i]&&(n[i]=parseInt(r[i],10));return r.expression&&(n.expression=r.expression),n})}function Fd(e,t){return Hs(e,t,!0,1)[0]}function Va(e,t,r=!1){return ra(Hs(e,t,r,1)).trim()}function an(e,t,r,n,i=!1){let a=Va(r,n,i);a&&(e[t]=a)}function BL(e){return e==="rss"||e==="feed"||e==="rdf:RDF"}var ML,FL,m2=v(()=>{Q0();eg();ML=["url","type","lang"],FL=["fileSize","bitrate","framerate","samplingrate","channels","duration","height","width"]});var qa={};Nn(qa,{DocumentPosition:()=>$n,append:()=>xL,appendChild:()=>TL,compareDocumentPosition:()=>d2,existsOne:()=>l2,filter:()=>ru,find:()=>Ld,findAll:()=>SL,findOne:()=>Pd,findOneChild:()=>wL,getAttributeValue:()=>_L,getChildren:()=>tu,getElementById:()=>OL,getElements:()=>NL,getElementsByClassName:()=>DL,getElementsByTagName:()=>Hs,getElementsByTagType:()=>kL,getFeed:()=>tg,getInnerHTML:()=>gL,getName:()=>EL,getOuterHTML:()=>s2,getParent:()=>o2,getSiblings:()=>X0,getText:()=>Dd,hasAttrib:()=>bL,hasChildren:()=>ht,innerText:()=>Kc,isCDATA:()=>jo,isComment:()=>$s,isDocument:()=>Bn,isTag:()=>_e,isText:()=>nn,nextElementSibling:()=>kd,prepend:()=>AL,prependChild:()=>yL,prevElementSibling:()=>Rd,removeElement:()=>na,removeSubsets:()=>RL,replaceElement:()=>vL,testElement:()=>IL,textContent:()=>ra,uniqueSort:()=>Ua});var ui=v(()=>{Q0();u2();c2();Z0();eg();h2();m2();_r()});function jc(e,t){if(!e)return t??$L;let r={_useHtmlParser2:!!e.xmlMode,...t,...e};return e.xml?(r._useHtmlParser2=!0,r.xmlMode=!0,e.xml!==!0&&Object.assign(r,e.xml)):e.xmlMode&&(r._useHtmlParser2=!0),r}var $L,rg=v(()=>{$L={_useHtmlParser2:!1}});var ig={};Nn(ig,{contains:()=>Wc,extract:()=>YL,html:()=>UL,merge:()=>ng,parseHTML:()=>qL,root:()=>zL,text:()=>Us,xml:()=>VL});function _2(e,t,r){return e?e(t??e._root.children,null,void 0,r).toString():""}function HL(e,t){return!t&&typeof e=="object"&&e!=null&&!("length"in e)&&!("type"in e)}function UL(e,t){let r=HL(e)?(t=e,void 0):e,n={...this===null||this===void 0?void 0:this._options,...jc(t)};return _2(this,r,n)}function VL(e){let t={...this._options,xmlMode:!0};return _2(this,e,t)}function Us(e){let t=e??(this?this.root():[]),r="";for(let n=0;n{ui();rg()});function Hn(e){return e.cheerio!=null}function b2(e){return e.replace(/[._-](\w|$)/g,(t,r)=>r.toUpperCase())}function E2(e){return e.replace(/[A-Z]/g,"-$&").toLowerCase()}function gt(e,t){let r=e.length;for(let n=0;ne.length-3)return!1;let r=e.charCodeAt(t+1);return(r>=Vs.LowerA&&r<=Vs.LowerZ||r>=Vs.UpperA&&r<=Vs.UpperZ||r===Vs.Exclamation)&&e.includes(">",t+2)}var Vs,iu=v(()=>{(function(e){e[e.LowerA=97]="LowerA",e[e.LowerZ=122]="LowerZ",e[e.UpperA=65]="UpperA",e[e.UpperZ=90]="UpperZ",e[e.Exclamation=33]="Exclamation"})(Vs||(Vs={}))});var ug={};Nn(ug,{addClass:()=>A2,attr:()=>jL,data:()=>XL,hasClass:()=>eP,prop:()=>WL,removeAttr:()=>JL,removeClass:()=>w2,toggleClass:()=>S2,val:()=>ZL});function Bd(e,t,r){var n;if(!(!e||!_e(e))){if((n=e.attribs)!==null&&n!==void 0||(e.attribs={}),!t)return e.attribs;if(Qc.call(e.attribs,t))return!r&&og.test(t)?t:e.attribs[t];if(e.name==="option"&&t==="value")return Us(e.children);if(e.name==="input"&&(e.attribs.type==="radio"||e.attribs.type==="checkbox")&&t==="value")return"on"}}function au(e,t,r){r===null?y2(e,t):e.attribs[t]=`${r}`}function jL(e,t){if(typeof e=="object"||t!==void 0){if(typeof t=="function"){if(typeof e!="string")throw new Error("Bad combination of arguments.");return gt(this,(r,n)=>{_e(r)&&au(r,e,t.call(r,n,r.attribs[e]))})}return gt(this,r=>{if(_e(r))if(typeof e=="object")for(let n of Object.keys(e)){let i=e[n];au(r,n,i)}else au(r,e,t)})}return arguments.length>1?this:Bd(this[0],e,this.options.xmlMode)}function v2(e,t,r){return t in e?e[t]:!r&&og.test(t)?Bd(e,t,!1)!==void 0:Bd(e,t,r)}function ag(e,t,r,n){t in e?e[t]=r:au(e,t,!n&&og.test(t)?r?"":null:`${r}`)}function WL(e,t){var r;if(typeof e=="string"&&t===void 0){let n=this[0];if(!n||!_e(n))return;switch(e){case"style":{let i=this.css(),a=Object.keys(i);for(let o=0;o").parent().html();case"innerHTML":return this.html();default:return v2(n,e,this.options.xmlMode)}}if(typeof e=="object"||t!==void 0){if(typeof t=="function"){if(typeof e=="object")throw new TypeError("Bad combination of arguments.");return gt(this,(n,i)=>{_e(n)&&ag(n,e,t.call(n,i,v2(n,e,this.options.xmlMode)),this.options.xmlMode)})}return gt(this,n=>{if(_e(n))if(typeof e=="object")for(let i of Object.keys(e)){let a=e[i];ag(n,i,a,this.options.xmlMode)}else ag(n,e,t,this.options.xmlMode)})}}function T2(e,t,r){var n;(n=e.data)!==null&&n!==void 0||(e.data={}),typeof t=="object"?Object.assign(e.data,t):typeof t=="string"&&r!==void 0&&(e.data[t]=r)}function GL(e){for(let t of Object.keys(e.attribs)){if(!t.startsWith(sg))continue;let r=b2(t.slice(sg.length));Qc.call(e.data,r)||(e.data[r]=x2(e.attribs[t]))}return e.data}function QL(e,t){let r=sg+E2(t),n=e.data;if(Qc.call(n,t))return n[t];if(Qc.call(e.attribs,r))return n[t]=x2(e.attribs[r])}function x2(e){if(e==="null")return null;if(e==="true")return!0;if(e==="false")return!1;let t=Number(e);if(e===String(t))return t;if(KL.test(e))try{return JSON.parse(e)}catch{}return e}function XL(e,t){var r;let n=this[0];if(!n||!_e(n))return;let i=n;return(r=i.data)!==null&&r!==void 0||(i.data={}),e==null?GL(i):typeof e=="object"||t!==void 0?(gt(this,a=>{_e(a)&&(typeof e=="object"?T2(a,e):T2(a,e,t))}),this):QL(i,e)}function ZL(e){let t=arguments.length===0,r=this[0];if(!r||!_e(r))return t?void 0:this;switch(r.name){case"textarea":return this.text(e);case"select":{let n=this.find("option:selected");if(!t){if(this.attr("multiple")==null&&typeof e=="object")return this;this.find("option").removeAttr("selected");let i=typeof e=="object"?e:[e];for(let a of i)this.find(`option[value="${a}"]`).attr("selected","");return this}return this.attr("multiple")?n.toArray().map(i=>Us(i.children)):n.attr("value")}case"input":case"option":return t?this.attr("value"):this.attr("value",e)}}function y2(e,t){!e.attribs||!Qc.call(e.attribs,t)||delete e.attribs[t]}function $d(e){return e?e.trim().split(Xc):[]}function JL(e){let t=$d(e);for(let r of t)gt(this,n=>{_e(n)&&y2(n,r)});return this}function eP(e){return this.toArray().some(t=>{let r=_e(t)&&t.attribs.class,n=-1;if(r&&e.length>0)for(;(n=r.indexOf(e,n+1))>-1;){let i=n+e.length;if((n===0||Xc.test(r[n-1]))&&(i===r.length||Xc.test(r[i])))return!0}return!1})}function A2(e){if(typeof e=="function")return gt(this,(n,i)=>{if(_e(n)){let a=n.attribs.class||"";A2.call([n],e.call(n,i,a))}});if(!e||typeof e!="string")return this;let t=e.split(Xc),r=this.length;for(let n=0;n{_e(i)&&w2.call([i],e.call(i,a,i.attribs.class||""))});let t=$d(e),r=t.length,n=arguments.length===0;return gt(this,i=>{if(_e(i))if(n)i.attribs.class="";else{let a=$d(i.attribs.class),o=!1;for(let l=0;l=0&&(a.splice(d,1),o=!0,l--)}o&&(i.attribs.class=a.join(" "))}})}function S2(e,t){if(typeof e=="function")return gt(this,(o,l)=>{_e(o)&&S2.call([o],e.call(o,l,o.attribs.class||"",t),t)});if(!e||typeof e!="string")return this;let r=e.split(Xc),n=r.length,i=typeof t=="boolean"?t?1:-1:0,a=this.length;for(let o=0;o=0&&g<0?d.push(r[p]):i<=0&&g>=0&&d.splice(g,1)}l.attribs.class=d.join(" ")}return this}var Qc,Xc,sg,og,KL,C2=v(()=>{nu();iu();_r();ui();Qc=Object.prototype.hasOwnProperty,Xc=/\s+/,sg="data-",og=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,KL=/^{[^]*}$|^\[[^]*]$/});var Ee,Bt,cg=v(()=>{(function(e){e.Attribute="attribute",e.Pseudo="pseudo",e.PseudoElement="pseudo-element",e.Tag="tag",e.Universal="universal",e.Adjacent="adjacent",e.Child="child",e.Descendant="descendant",e.Parent="parent",e.Sibling="sibling",e.ColumnCombinator="column-combinator"})(Ee||(Ee={}));(function(e){e.Any="any",e.Element="element",e.End="end",e.Equals="equals",e.Exists="exists",e.Hyphen="hyphen",e.Not="not",e.Start="start"})(Bt||(Bt={}))});function qs(e){switch(e.type){case Ee.Adjacent:case Ee.Child:case Ee.Descendant:case Ee.Parent:case Ee.Sibling:case Ee.ColumnCombinator:return!0;default:return!1}}function aP(e,t,r){let n=parseInt(t,16)-65536;return n!==n||r?t:n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,n&1023|56320)}function Zc(e){return e.replace(tP,aP)}function lg(e){return e===39||e===34}function N2(e){return e===32||e===9||e===10||e===12||e===13}function ia(e){let t=[],r=O2(t,`${e}`,0);if(r0&&r0&&qs(n[n.length-1]))throw new Error("Did not expect successive traversals.")}function p(_){if(n.length>0&&n[n.length-1].type===Ee.Descendant){n[n.length-1].type=_;return}d(),n.push({type:_})}function g(_,y){n.push({type:Ee.Attribute,name:_,action:y,value:i(1),namespace:null,ignoreCase:"quirks"})}function E(){if(n.length&&n[n.length-1].type===Ee.Descendant&&n.pop(),n.length===0)throw new Error("Empty sub-selector");e.push(n)}if(a(0),t.length===r)return r;e:for(;r{cg();I2=/^[^\\#]?(?:\\(?:[\da-f]{1,6}\s?|.)|[\w\-\u00b0-\uFFFF])+/,tP=/\\([\da-f]{1,6}\s?|(\s)|.)/gi,rP=new Map([[126,Bt.Element],[94,Bt.Start],[36,Bt.End],[42,Bt.Any],[33,Bt.Not],[124,Bt.Hyphen]]),nP=new Set(["has","not","matches","is","where","host","host-context"]);iP=new Set(["contains","icontains"])});var su=v(()=>{cg();D2()});var za=Pi((Mne,k2)=>{k2.exports={trueFunc:function(){return!0},falseFunc:function(){return!1}}});function Jc(e){return!R2.has(e.type)}function fg(e){let t=e.map(L2);for(let r=1;r=0&&n>=1)):e.type===Ee.Pseudo&&(e.data?e.name==="has"||e.name==="contains"?n=0:Array.isArray(e.data)?(n=Math.min(...e.data.map(i=>Math.min(...i.map(L2)))),n<0&&(n=0)):n=2:n=3),n}var R2,sP,dg=v(()=>{su();R2=new Map([[Ee.Universal,50],[Ee.Tag,30],[Ee.Attribute,1],[Ee.Pseudo,0]]);sP=new Map([[Bt.Exists,10],[Bt.Equals,8],[Bt.Not,7],[Bt.Start,6],[Bt.End,6],[Bt.Any,5]])});function P2(e){return e.replace(oP,"\\$&")}function zs(e,t){return typeof e.ignoreCase=="boolean"?e.ignoreCase:e.ignoreCase==="quirks"?!!t.quirksMode:!t.xmlMode&&uP.has(e.name)}var el,oP,uP,M2,F2=v(()=>{el=ln(za(),1),oP=/[-[\]{}()*+?.,\\^$|#\s]/g;uP=new Set(["accept","accept-charset","align","alink","axis","bgcolor","charset","checked","clear","codetype","color","compact","declare","defer","dir","direction","disabled","enctype","face","frame","hreflang","http-equiv","lang","language","link","media","method","multiple","nohref","noresize","noshade","nowrap","readonly","rel","rev","rules","scope","scrolling","selected","shape","target","text","type","valign","valuetype","vlink"]);M2={equals(e,t,r){let{adapter:n}=r,{name:i}=t,{value:a}=t;return zs(t,r)?(a=a.toLowerCase(),o=>{let l=n.getAttributeValue(o,i);return l!=null&&l.length===a.length&&l.toLowerCase()===a&&e(o)}):o=>n.getAttributeValue(o,i)===a&&e(o)},hyphen(e,t,r){let{adapter:n}=r,{name:i}=t,{value:a}=t,o=a.length;return zs(t,r)?(a=a.toLowerCase(),function(d){let p=n.getAttributeValue(d,i);return p!=null&&(p.length===o||p.charAt(o)==="-")&&p.substr(0,o).toLowerCase()===a&&e(d)}):function(d){let p=n.getAttributeValue(d,i);return p!=null&&(p.length===o||p.charAt(o)==="-")&&p.substr(0,o)===a&&e(d)}},element(e,t,r){let{adapter:n}=r,{name:i,value:a}=t;if(/\s/.test(a))return el.default.falseFunc;let o=new RegExp(`(?:^|\\s)${P2(a)}(?:$|\\s)`,zs(t,r)?"i":"");return function(d){let p=n.getAttributeValue(d,i);return p!=null&&p.length>=a.length&&o.test(p)&&e(d)}},exists(e,{name:t},{adapter:r}){return n=>r.hasAttrib(n,t)&&e(n)},start(e,t,r){let{adapter:n}=r,{name:i}=t,{value:a}=t,o=a.length;return o===0?el.default.falseFunc:zs(t,r)?(a=a.toLowerCase(),l=>{let d=n.getAttributeValue(l,i);return d!=null&&d.length>=o&&d.substr(0,o).toLowerCase()===a&&e(l)}):l=>{var d;return!!(!((d=n.getAttributeValue(l,i))===null||d===void 0)&&d.startsWith(a))&&e(l)}},end(e,t,r){let{adapter:n}=r,{name:i}=t,{value:a}=t,o=-a.length;return o===0?el.default.falseFunc:zs(t,r)?(a=a.toLowerCase(),l=>{var d;return((d=n.getAttributeValue(l,i))===null||d===void 0?void 0:d.substr(o).toLowerCase())===a&&e(l)}):l=>{var d;return!!(!((d=n.getAttributeValue(l,i))===null||d===void 0)&&d.endsWith(a))&&e(l)}},any(e,t,r){let{adapter:n}=r,{name:i,value:a}=t;if(a==="")return el.default.falseFunc;if(zs(t,r)){let o=new RegExp(P2(a),"i");return function(d){let p=n.getAttributeValue(d,i);return p!=null&&p.length>=a.length&&o.test(p)&&e(d)}}return o=>{var l;return!!(!((l=n.getAttributeValue(o,i))===null||l===void 0)&&l.includes(a))&&e(o)}},not(e,t,r){let{adapter:n}=r,{name:i}=t,{value:a}=t;return a===""?o=>!!n.getAttributeValue(o,i)&&e(o):zs(t,r)?(a=a.toLowerCase(),o=>{let l=n.getAttributeValue(o,i);return(l==null||l.length!==a.length||l.toLowerCase()!==a)&&e(o)}):o=>n.getAttributeValue(o,i)!==a&&e(o)}}});function $2(e){if(e=e.trim().toLowerCase(),e==="even")return[2,0];if(e==="odd")return[2,1];let t=0,r=0,n=a(),i=o();if(t=B2&&e.charCodeAt(t)<=lP;)p=p*10+(e.charCodeAt(t)-B2),t++;return t===d?null:p}function l(){for(;t{cP=new Set([9,10,12,13,32]),B2="0".charCodeAt(0),lP="9".charCodeAt(0)});function U2(e){let t=e[0],r=e[1]-1;if(r<0&&t<=0)return hg.default.falseFunc;if(t===-1)return a=>a<=r;if(t===0)return a=>a===r;if(t===1)return r<0?hg.default.trueFunc:a=>a>=r;let n=Math.abs(t),i=(r%n+n)%n;return t>1?a=>a>=r&&a%n===i:a=>a<=r&&a%n===i}var hg,V2=v(()=>{hg=ln(za(),1)});function ou(e){return U2($2(e))}var q2=v(()=>{H2();V2()});function Hd(e,t){return r=>{let n=t.getParent(r);return n!=null&&t.isTag(n)&&e(r)}}function pg(e){return function(r,n,{adapter:i}){let a=i[e];return typeof a!="function"?sn.default.falseFunc:function(l){return a(l)&&r(l)}}}var sn,uu,z2=v(()=>{q2();sn=ln(za(),1);uu={contains(e,t,{adapter:r}){return function(i){return e(i)&&r.getText(i).includes(t)}},icontains(e,t,{adapter:r}){let n=t.toLowerCase();return function(a){return e(a)&&r.getText(a).toLowerCase().includes(n)}},"nth-child"(e,t,{adapter:r,equals:n}){let i=ou(t);return i===sn.default.falseFunc?sn.default.falseFunc:i===sn.default.trueFunc?Hd(e,r):function(o){let l=r.getSiblings(o),d=0;for(let p=0;p=0&&!n(o,l[p]);p--)r.isTag(l[p])&&d++;return i(d)&&e(o)}},"nth-of-type"(e,t,{adapter:r,equals:n}){let i=ou(t);return i===sn.default.falseFunc?sn.default.falseFunc:i===sn.default.trueFunc?Hd(e,r):function(o){let l=r.getSiblings(o),d=0;for(let p=0;p=0;p--){let g=l[p];if(n(o,g))break;r.isTag(g)&&r.getName(g)===r.getName(o)&&d++}return i(d)&&e(o)}},root(e,t,{adapter:r}){return n=>{let i=r.getParent(n);return(i==null||!r.isTag(i))&&e(n)}},scope(e,t,r,n){let{equals:i}=r;return!n||n.length===0?uu.root(e,t,r):n.length===1?a=>i(n[0],a)&&e(a):a=>n.includes(a)&&e(a)},hover:pg("isHovered"),visited:pg("isVisited"),active:pg("isActive")}});function mg(e,t,r,n){if(r===null){if(e.length>n)throw new Error(`Pseudo-class :${t} requires an argument`)}else if(e.length===n)throw new Error(`Pseudo-class :${t} doesn't have any arguments`)}var tl,Y2=v(()=>{tl={empty(e,{adapter:t}){return!t.getChildren(e).some(r=>t.isTag(r)||t.getText(r)!=="")},"first-child"(e,{adapter:t,equals:r}){if(t.prevElementSibling)return t.prevElementSibling(e)==null;let n=t.getSiblings(e).find(i=>t.isTag(i));return n!=null&&r(e,n)},"last-child"(e,{adapter:t,equals:r}){let n=t.getSiblings(e);for(let i=n.length-1;i>=0;i--){if(r(e,n[i]))return!0;if(t.isTag(n[i]))break}return!1},"first-of-type"(e,{adapter:t,equals:r}){let n=t.getSiblings(e),i=t.getName(e);for(let a=0;a=0;a--){let o=n[a];if(r(e,o))return!0;if(t.isTag(o)&&t.getName(o)===i)break}return!1},"only-of-type"(e,{adapter:t,equals:r}){let n=t.getName(e);return t.getSiblings(e).every(i=>r(e,i)||!t.isTag(i)||t.getName(i)!==n)},"only-child"(e,{adapter:t,equals:r}){return t.getSiblings(e).every(n=>r(e,n)||!t.isTag(n))}}});var Ud,K2=v(()=>{Ud={"any-link":":is(a, area, link)[href]",link:":any-link:not(:visited)",disabled:`:is( - :is(button, input, select, textarea, optgroup, option)[disabled], - optgroup[disabled] > option, - fieldset[disabled]:not(fieldset[disabled] legend:first-of-type *) - )`,enabled:":not(:disabled)",checked:":is(:is(input[type=radio], input[type=checkbox])[checked], option:selected)",required:":is(input, select, textarea)[required]",optional:":is(input, select, textarea):not([required])",selected:"option:is([selected], select:not([multiple]):not(:has(> option[selected])) > :first-of-type)",checkbox:"[type=checkbox]",file:"[type=file]",password:"[type=password]",radio:"[type=radio]",reset:"[type=reset]",image:"[type=image]",submit:"[type=submit]",parent:":not(:empty)",header:":is(h1, h2, h3, h4, h5, h6)",button:":is(button, input[type=button])",input:":is(input, textarea, select, button)",text:"input:is(:not([type!='']), [type=text])"}});function Eg(e,t){return e===Un.default.falseFunc?Un.default.falseFunc:r=>t.isTag(r)&&e(r)}function vg(e,t){let r=t.getSiblings(e);if(r.length<=1)return[];let n=r.indexOf(e);return n<0||n===r.length-1?[]:r.slice(n+1).filter(t.isTag)}function _g(e){return{xmlMode:!!e.xmlMode,lowerCaseAttributeNames:!!e.lowerCaseAttributeNames,lowerCaseTags:!!e.lowerCaseTags,quirksMode:!!e.quirksMode,cacheResults:!!e.cacheResults,pseudos:e.pseudos,adapter:e.adapter,equals:e.equals}}var Un,bg,gg,Vd,qd=v(()=>{Un=ln(za(),1);dg();bg={};gg=(e,t,r,n,i)=>{let a=i(t,_g(r),n);return a===Un.default.trueFunc?e:a===Un.default.falseFunc?Un.default.falseFunc:o=>a(o)&&e(o)},Vd={is:gg,matches:gg,where:gg,not(e,t,r,n,i){let a=i(t,_g(r),n);return a===Un.default.falseFunc?e:a===Un.default.trueFunc?Un.default.falseFunc:o=>!a(o)&&e(o)},has(e,t,r,n,i){let{adapter:a}=r,o=_g(r);o.relativeSelector=!0;let l=t.some(g=>g.some(Jc))?[bg]:void 0,d=i(t,o,l);if(d===Un.default.falseFunc)return Un.default.falseFunc;let p=Eg(d,a);if(l&&d!==Un.default.trueFunc){let{shouldTestNextSiblings:g=!1}=d;return E=>{if(!e(E))return!1;l[0]=E;let _=a.getChildren(E),y=g?[..._,...vg(E,a)]:_;return a.existsOne(p,y)}}return g=>e(g)&&a.existsOne(p,a.getChildren(g))}}});function j2(e,t,r,n,i){var a;let{name:o,data:l}=t;if(Array.isArray(l)){if(!(o in Vd))throw new Error(`Unknown pseudo-class :${o}(${l})`);return Vd[o](e,l,r,n,i)}let d=(a=r.pseudos)===null||a===void 0?void 0:a[o],p=typeof d=="string"?d:Ud[o];if(typeof p=="string"){if(l!=null)throw new Error(`Pseudo ${o} doesn't have any arguments`);let g=ia(p);return Vd.is(e,g,r,n,i)}if(typeof d=="function")return mg(d,o,l,1),g=>d(g,l)&&e(g);if(o in uu)return uu[o](e,l,r,n);if(o in tl){let g=tl[o];return mg(g,o,l,2),E=>g(E,r,l)&&e(E)}throw new Error(`Unknown pseudo-class :${o}`)}var Tg=v(()=>{su();z2();Y2();K2();qd()});function xg(e,t){let r=t.getParent(e);return r&&t.isTag(r)?r:null}function W2(e,t,r,n,i){let{adapter:a,equals:o}=r;switch(t.type){case Ee.PseudoElement:throw new Error("Pseudo-elements are not supported by css-select");case Ee.ColumnCombinator:throw new Error("Column combinators are not yet supported by css-select");case Ee.Attribute:{if(t.namespace!=null)throw new Error("Namespaced attributes are not yet supported by css-select");return(!r.xmlMode||r.lowerCaseAttributeNames)&&(t.name=t.name.toLowerCase()),M2[t.action](e,t,r)}case Ee.Pseudo:return j2(e,t,r,n,i);case Ee.Tag:{if(t.namespace!=null)throw new Error("Namespaced tag names are not yet supported by css-select");let{name:l}=t;return(!r.xmlMode||r.lowerCaseTags)&&(l=l.toLowerCase()),function(p){return a.getName(p)===l&&e(p)}}case Ee.Descendant:{if(r.cacheResults===!1||typeof WeakSet>"u")return function(p){let g=p;for(;g=xg(g,a);)if(e(g))return!0;return!1};let l=new WeakSet;return function(p){let g=p;for(;g=xg(g,a);)if(!l.has(g)){if(a.isTag(g)&&e(g))return!0;l.add(g)}return!1}}case"_flexibleDescendant":return function(d){let p=d;do if(e(p))return!0;while(p=xg(p,a));return!1};case Ee.Parent:return function(d){return a.getChildren(d).some(p=>a.isTag(p)&&e(p))};case Ee.Child:return function(d){let p=a.getParent(d);return p!=null&&a.isTag(p)&&e(p)};case Ee.Sibling:return function(d){let p=a.getSiblings(d);for(let g=0;g{F2();Tg();su()});function Q2(e,t,r){let n=zd(e,t,r);return Eg(n,t.adapter)}function zd(e,t,r){let n=typeof e=="string"?ia(e):e;return Yd(n,t,r)}function X2(e){return e.type===Ee.Pseudo&&(e.name==="scope"||Array.isArray(e.data)&&e.data.some(t=>t.some(X2)))}function pP(e,{adapter:t},r){let n=!!r?.every(i=>{let a=t.isTag(i)&&t.getParent(i);return i===bg||a&&t.isTag(a)});for(let i of e){if(!(i.length>0&&Jc(i[0])&&i[0].type!==Ee.Descendant))if(n&&!i.some(X2))i.unshift(fP);else continue;i.unshift(hP)}}function Yd(e,t,r){var n;e.forEach(fg),r=(n=t.context)!==null&&n!==void 0?n:r;let i=Array.isArray(r),a=r&&(Array.isArray(r)?r:[r]);if(t.relativeSelector!==!1)pP(e,t,a);else if(e.some(d=>d.length>0&&Jc(d[0])))throw new Error("Relative selectors are not allowed when the `relativeSelector` option is disabled");let o=!1,l=e.map(d=>{if(d.length>=2){let[p,g]=d;p.type!==Ee.Pseudo||p.name!=="scope"||(i&&g.type===Ee.Descendant?d[1]=dP:(g.type===Ee.Adjacent||g.type===Ee.Sibling)&&(o=!0))}return mP(d,t,a)}).reduce(gP,aa.default.falseFunc);return l.shouldTestNextSiblings=o,l}function mP(e,t,r){var n;return e.reduce((i,a)=>i===aa.default.falseFunc?aa.default.falseFunc:W2(i,a,t,r,Yd),(n=t.rootFunc)!==null&&n!==void 0?n:aa.default.trueFunc)}function gP(e,t){return t===aa.default.falseFunc||e===aa.default.trueFunc?e:e===aa.default.falseFunc||t===aa.default.trueFunc?t:function(n){return e(n)||t(n)}}var aa,fP,dP,hP,Z2=v(()=>{su();aa=ln(za(),1);dg();G2();qd();fP={type:Ee.Descendant},dP={type:"_flexibleDescendant"},hP={type:Ee.Pseudo,name:"scope",data:null}});function ew(e){var t,r,n,i;let a=e??_P;return(t=a.adapter)!==null&&t!==void 0||(a.adapter=qa),(r=a.equals)!==null&&r!==void 0||(a.equals=(i=(n=a.adapter)===null||n===void 0?void 0:n.equals)!==null&&i!==void 0?i:J2),a}function Ag(e){return function(r,n,i){let a=ew(n);return e(r,a,i)}}function tw(e){return function(r,n,i){let a=ew(i);typeof r!="function"&&(r=zd(r,a,n));let o=jd(n,a.adapter,r.shouldTestNextSiblings);return e(r,o,a)}}function jd(e,t,r=!1){return r&&(e=bP(e,t)),Array.isArray(e)?t.removeSubsets(e):t.getChildren(e)}function bP(e,t){let r=Array.isArray(e)?e.slice(0):[e],n=r.length;for(let i=0;i{ui();yg=ln(za(),1);Z2();qd();Tg();J2=(e,t)=>e===t,_P={adapter:qa,equals:J2};mie=Ag(Q2),gie=Ag(zd),Kd=Ag(Yd);_ie=tw((e,t,r)=>e===yg.default.falseFunc||!t||t.length===0?[]:r.adapter.findAll(e,t)),bie=tw((e,t,r)=>e===yg.default.falseFunc||!t||t.length===0?null:r.adapter.findOne(e,t))});function cu(e){return e.type!=="pseudo"?!1:EP.has(e.name)?!0:e.name==="not"&&Array.isArray(e.data)?e.data.some(t=>t.some(cu)):!1}function rw(e,t,r){let n=t!=null?parseInt(t,10):NaN;switch(e){case"first":return 1;case"nth":case"eq":return isFinite(n)?n>=0?n+1:1/0:0;case"lt":return isFinite(n)?n>=0?Math.min(n,r):1/0:0;case"gt":return isFinite(n)?1/0:0;case"odd":return 2*r;case"even":return 2*r-1;case"last":case"not":return 1/0}}var EP,Sg=v(()=>{EP=new Set(["first","last","eq","gt","nth","lt","even","odd"])});function nw(e){for(;e.parent;)e=e.parent;return e}function Wd(e){let t=[],r=[];for(let n of e)n.some(cu)?t.push(n):r.push(n);return[r,t]}var iw=v(()=>{Sg()});function Ng(e,t,r={}){return Og([e],t,r)}function Og(e,t,r={}){if(typeof t=="function")return e.some(t);let[n,i]=Wd(ia(t));return n.length>0&&e.some(Kd(n,r))||i.some(a=>sw(a,e,r).length>0)}function xP(e,t,r,n){let i=typeof r=="string"?parseInt(r,10):NaN;switch(e){case"first":case"lt":return t;case"last":return t.length>0?[t[t.length-1]]:t;case"nth":case"eq":return isFinite(i)&&Math.abs(i)o%2===0);case"odd":return t.filter((a,o)=>o%2===1);case"not":{let a=new Set(aw(r,t,n));return t.filter(o=>!a.has(o))}}}function Dg(e,t,r={}){return aw(ia(e),t,r)}function aw(e,t,r){if(t.length===0)return[];let[n,i]=Wd(e),a;if(n.length){let o=Ig(t,n,r);if(i.length===0)return o;o.length&&(a=new Set(o))}for(let o=0;o_e(g)&&!a.has(g)):t).length===0)break;let p=sw(l,t,r);if(p.length)if(a)p.forEach(g=>a.add(g));else{if(o===i.length-1)return p;a=new Set(p)}}return typeof a<"u"?a.size===t.length?t:t.filter(o=>a.has(o)):[]}function sw(e,t,r){var n;if(e.some(qs)){let i=(n=r.root)!==null&&n!==void 0?n:nw(t[0]),a={...r,context:t,relativeSelector:!1};return e.push(TP),Qd(i,e,a,!0,t.length)}return Qd(t,e,r,!1,t.length)}function ow(e,t,r={},n=1/0){if(typeof e=="function")return uw(t,e);let[i,a]=Wd(ia(e)),o=a.map(l=>Qd(t,l,r,!0,n));return i.length&&o.push(Cg(t,i,r,n)),o.length===0?[]:o.length===1?o[0]:Ua(o.reduce((l,d)=>[...l,...d]))}function Qd(e,t,r,n,i){let a=t.findIndex(cu),o=t.slice(0,a),l=t[a],d=t.length-1===a?i:1/0,p=rw(l.name,l.data,d);if(p===0)return[];let E=(o.length===0&&!Array.isArray(e)?tu(e).filter(_e):o.length===0?(Array.isArray(e)?e:[e]).filter(_e):n||o.some(qs)?Cg(e,[o],r,p):Ig(e,[o],r)).slice(0,p),_=xP(l.name,E,l.data,r);if(_.length===0||t.length===a+1)return _;let y=t.slice(a+1),C=y.some(qs);if(C){if(qs(y[0])){let{type:k}=y[0];(k===Ee.Sibling||k===Ee.Adjacent)&&(_=jd(_,qa,!0)),y.unshift(vP)}r={...r,relativeSelector:!1,rootFunc:k=>_.includes(k)}}else r.rootFunc&&r.rootFunc!==Gd.trueFunc&&(r={...r,rootFunc:Gd.trueFunc});return y.some(cu)?Qd(_,y,r,!1,i):C?Cg(_,[y],r,i):Ig(_,[y],r)}function Cg(e,t,r,n){let i=Kd(t,r,e);return uw(e,i,n)}function uw(e,t,r=1/0){let n=jd(e,qa,t.shouldTestNextSiblings);return Ld(i=>_e(i)&&t(i),n,!0,r)}function Ig(e,t,r){let n=(Array.isArray(e)?e:[e]).filter(_e);if(n.length===0)return n;let i=Kd(t,r);return i===Gd.trueFunc?n:n.filter(i)}var Gd,vP,TP,cw=v(()=>{su();wg();ui();Gd=ln(za(),1);iw();Sg();wg();vP={type:Ee.Universal,namespace:null},TP={type:Ee.Pseudo,name:"scope",data:null}});var Mg={};Nn(Mg,{_findBySelector:()=>SP,add:()=>e4,addBack:()=>t4,children:()=>BP,closest:()=>OP,contents:()=>$P,each:()=>HP,end:()=>JP,eq:()=>WP,filter:()=>VP,filterArray:()=>Pg,find:()=>wP,first:()=>KP,get:()=>GP,has:()=>YP,index:()=>XP,is:()=>qP,last:()=>jP,map:()=>UP,next:()=>DP,nextAll:()=>kP,nextUntil:()=>RP,not:()=>zP,parent:()=>CP,parents:()=>IP,parentsUntil:()=>NP,prev:()=>LP,prevAll:()=>PP,prevUntil:()=>MP,siblings:()=>FP,slice:()=>ZP,toArray:()=>QP});function wP(e){if(!e)return this._make([]);if(typeof e!="string"){let t=Hn(e)?e.toArray():[e],r=this.toArray();return this._make(t.filter(n=>r.some(i=>Wc(i,n))))}return this._findBySelector(e,Number.POSITIVE_INFINITY)}function SP(e,t){var r;let n=this.toArray(),i=AP.test(e)?n:this.children().toArray(),a={context:n,root:(r=this._root)===null||r===void 0?void 0:r[0],xmlMode:this.options.xmlMode,lowerCaseTags:this.options.lowerCaseTags,lowerCaseAttributeNames:this.options.lowerCaseAttributeNames,pseudos:this.options.pseudos,quirksMode:this.options.quirksMode};return this._make(ow(e,i,a,t))}function kg(e){return function(t,...r){return function(n){var i;let a=e(t,this);return n&&(a=Pg(a,n,this.options.xmlMode,(i=this._root)===null||i===void 0?void 0:i[0])),this._make(this.length>1&&a.length>1?r.reduce((o,l)=>l(o),a):a)}}}function Lg(e,...t){let r=null,n=kg((i,a)=>{let o=[];return gt(a,l=>{for(let d;(d=i(l))&&!r?.(d,o.length);l=d)o.push(d)}),o})(e,...t);return function(i,a){r=typeof i=="string"?l=>Ng(l,i,this.options):i?nl(i):null;let o=n.call(this,a);return r=null,o}}function lu(e){return e.length>1?Array.from(new Set(e)):e}function OP(e){var t;let r=[];if(!e)return this._make(r);let n={xmlMode:this.options.xmlMode,root:(t=this._root)===null||t===void 0?void 0:t[0]},i=typeof e=="string"?a=>Ng(a,e,n):nl(e);return gt(this,a=>{for(a&&!Bn(a)&&!_e(a)&&(a=a.parent);a&&_e(a);){if(i(a,0)){r.includes(a)||r.push(a);break}a=a.parent}}),this._make(r)}function $P(){let e=this.toArray().reduce((t,r)=>ht(r)?t.concat(r.children):t,[]);return this._make(e)}function HP(e){let t=0,r=this.length;for(;te.call(t,r,t):Hn(e)?t=>Array.prototype.includes.call(e,t):function(t){return e===t}}function VP(e){var t;return this._make(Pg(this.toArray(),e,this.options.xmlMode,(t=this._root)===null||t===void 0?void 0:t[0]))}function Pg(e,t,r,n){return typeof t=="string"?Dg(t,e,{xmlMode:r,root:n}):e.filter(nl(t))}function qP(e){let t=this.toArray();return typeof e=="string"?Og(t.filter(_e),e,this.options):e?t.some(nl(e)):!1}function zP(e){let t=this.toArray();if(typeof e=="string"){let r=new Set(Dg(e,t,this.options));t=t.filter(n=>!r.has(n))}else{let r=nl(e);t=t.filter((n,i)=>!r(n,i))}return this._make(t)}function YP(e){return this.filter(typeof e=="string"?`:has(${e})`:(t,r)=>this._make(r).find(e).length>0)}function KP(){return this.length>1?this._make(this[0]):this}function jP(){return this.length>0?this._make(this[this.length-1]):this}function WP(e){var t;return e=+e,e===0&&this.length<=1?this:(e<0&&(e=this.length+e),this._make((t=this[e])!==null&&t!==void 0?t:[]))}function GP(e){return e==null?this.toArray():this[e<0?this.length+e:e]}function QP(){return Array.prototype.slice.call(this)}function XP(e){let t,r;return e==null?(t=this.parent().children(),r=this[0]):typeof e=="string"?(t=this._make(e),r=this[0]):(t=this,r=Hn(e)?e[0]:e),Array.prototype.indexOf.call(t,r)}function ZP(e,t){return this._make(Array.prototype.slice.call(this,e,t))}function JP(){var e;return(e=this.prevObject)!==null&&e!==void 0?e:this._make([])}function e4(e,t){let r=this._make(e,t),n=Ua([...this.get(),...r.get()]);return this._make(n)}function t4(e){return this.prevObject?this.add(e?this.prevObject.filter(e):this.prevObject):this}var AP,rl,Rg,CP,IP,NP,DP,kP,RP,LP,PP,MP,FP,BP,lw=v(()=>{_r();cw();iu();nu();ui();AP=/^\s*[+~]/;rl=kg((e,t)=>{let r=[];for(let n=0;n0&&(r=r.concat(i))}return r}),Rg=kg((e,t)=>{let r=[];for(let n=0;ne&&!Bn(e)?e:null,lu),IP=rl(e=>{let t=[];for(;e.parent&&!Bn(e.parent);)t.push(e.parent),e=e.parent;return t},Ua,e=>e.reverse()),NP=Lg(({parent:e})=>e&&!Bn(e)?e:null,Ua,e=>e.reverse());DP=Rg(e=>kd(e)),kP=rl(e=>{let t=[];for(;e.next;)e=e.next,_e(e)&&t.push(e);return t},lu),RP=Lg(e=>kd(e),lu),LP=Rg(e=>Rd(e)),PP=rl(e=>{let t=[];for(;e.prev;)e=e.prev,_e(e)&&t.push(e);return t},lu),MP=Lg(e=>Rd(e),lu),FP=rl(e=>X0(e).filter(t=>_e(t)&&t!==e),Ua),BP=rl(e=>tu(e).filter(_e),lu)});function fw(e){return function(r,n,i,a){if(typeof Buffer<"u"&&Buffer.isBuffer(r)&&(r=r.toString()),typeof r=="string")return e(r,n,i,a);let o=r;if(!Array.isArray(o)&&Bn(o))return o;let l=new wn([]);return Ya(o,l),l}}function Ya(e,t){let r=Array.isArray(e)?e:[e];t?t.children=r:t=null;for(let n=0;n{ui();_r()});var Bg={};Nn(Bg,{_makeDomArray:()=>r4,after:()=>f4,append:()=>a4,appendTo:()=>n4,before:()=>h4,clone:()=>T4,empty:()=>_4,html:()=>b4,insertAfter:()=>d4,insertBefore:()=>p4,prepend:()=>s4,prependTo:()=>i4,remove:()=>m4,replaceWith:()=>g4,text:()=>v4,toString:()=>E4,unwrap:()=>c4,wrap:()=>o4,wrapAll:()=>l4,wrapInner:()=>u4});function r4(e,t){if(e==null)return[];if(typeof e=="string")return this._parse(e,this.options,!1,null).children.slice(0);if("length"in e){if(e.length===1)return this._makeDomArray(e[0],t);let r=[];for(let n=0;n{if(!ht(n))return;let a=typeof t[0]=="function"?t[0].call(n,i,this._render(n.children)):t,o=this._makeDomArray(a,i=e.length?null:e[t+r];for(let g=0;g-1&&(_.children.splice(C,1),i===_&&t>C&&l[0]--)}E.parent=i,E.prev&&(E.prev.next=(a=E.next)!==null&&a!==void 0?a:null),E.next&&(E.next.prev=(o=E.prev)!==null&&o!==void 0?o:null),E.prev=g===0?d:n[g-1],E.next=g===n.length-1?p:n[g+1]}return d&&(d.next=n[0]),p&&(p.prev=n[n.length-1]),e.splice(...l)}function n4(e){return(Hn(e)?e:this._make(e)).append(this),this}function i4(e){return(Hn(e)?e:this._make(e)).prepend(this),this}function hw(e){return function(t){let r=this.length-1,n=this.parents().last();for(let i=0;i{this._make(r).replaceWith(r.children)}),this}function l4(e){let t=this[0];if(t){let r=this._make(typeof e=="function"?e.call(t,0,t):e).insertBefore(t),n;for(let a=0;a{if(!ht(r)||!r.parent)return;let i=r.parent.children,a=i.indexOf(r);if(a<0)return;let o=typeof e[0]=="function"?e[0].call(r,n,this._render(r.children)):e,l=this._makeDomArray(o,n{if(!ht(r)||!r.parent)return;let i=r.parent.children,a=i.indexOf(r);if(a<0)return;let o=typeof e[0]=="function"?e[0].call(r,n,this._render(r.children)):e,l=this._makeDomArray(o,n{let i=this.clone().toArray(),{parent:a}=n;if(!a)return;let o=a.children,l=o.indexOf(n);l<0||(Ka(o,l,0,i,a),r.push(...i))}),this._make(r)}function m4(e){let t=e?this.filter(e):this;return gt(t,r=>{na(r),r.prev=r.next=r.parent=null}),this}function g4(e){return gt(this,(t,r)=>{let{parent:n}=t;if(!n)return;let i=n.children,a=typeof e=="function"?e.call(t,r,t):e,o=this._makeDomArray(a);Ya(o,null);let l=i.indexOf(t);Ka(i,l,1,o,n),o.includes(t)||(t.parent=t.prev=t.next=null)})}function _4(){return gt(this,e=>{if(ht(e)){for(let t of e.children)t.next=t.prev=t.parent=null;e.children.length=0}})}function b4(e){if(e===void 0){let t=this[0];return!t||!ht(t)?null:this._render(t.children)}return gt(this,t=>{if(!ht(t))return;for(let n of t.children)n.next=n.prev=n.parent=null;let r=Hn(e)?e.toArray():this._parse(`${e}`,this.options,!1,t).children;Ya(r,t)})}function E4(){return this._render(this)}function v4(e){return e===void 0?Us(this):typeof e=="function"?gt(this,(t,r)=>this._make(t).text(e.call(t,r,Us([t])))):gt(this,t=>{if(!ht(t))return;for(let n of t.children)n.next=n.prev=n.parent=null;let r=new Ni(`${e}`);Ya(r,t)})}function T4(){let e=Array.prototype.map.call(this.get(),r=>Wo(r,!0)),t=new wn(e);for(let r of e)r.parent=t;return this._make(e)}var a4,s4,o4,u4,pw=v(()=>{_r();Fg();nu();iu();ui();a4=dw((e,t,r)=>{Ka(t,t.length,0,e,r)}),s4=dw((e,t,r)=>{Ka(t,0,0,e,r)});o4=hw((e,t,r)=>{let{parent:n}=e;if(!n)return;let i=n.children,a=i.indexOf(e);Ya([e],t),Ka(i,a,0,r,n)}),u4=hw((e,t,r)=>{ht(e)&&(Ya(e.children,t),Ya(r,e))})});var $g={};Nn($g,{css:()=>x4});function x4(e,t){if(e!=null&&t!=null||typeof e=="object"&&!Array.isArray(e))return gt(this,(r,n)=>{_e(r)&&mw(r,e,t,n)});if(this.length!==0)return gw(this[0],e)}function mw(e,t,r,n){if(typeof t=="string"){let i=gw(e),a=typeof r=="function"?r.call(e,n,i[t]):r;a===""?delete i[t]:a!=null&&(i[t]=a),e.attribs.style=y4(i)}else if(typeof t=="object"){let i=Object.keys(t);for(let a=0;a`${t}${t?" ":""}${r}: ${e[r]};`,"")}function A4(e){if(e=(e||"").trim(),!e)return{};let t={},r;for(let n of e.split(";")){let i=n.indexOf(":");if(i<1||i===n.length-1){let a=n.trimEnd();a.length>0&&r!==void 0&&(t[r]+=`;${a}`)}else r=n.slice(0,i).trim(),t[r]=n.slice(i+1).trim()}return t}var _w=v(()=>{iu();_r()});var Hg={};Nn(Hg,{serialize:()=>S4,serializeArray:()=>C4});function S4(){return this.serializeArray().map(r=>`${encodeURIComponent(r.name)}=${encodeURIComponent(r.value)}`).join("&").replace(w4,"+")}function C4(){return this.map((e,t)=>{let r=this._make(t);return _e(t)&&t.name==="form"?r.find(bw).toArray():r.filter(bw).toArray()}).filter('[name!=""]:enabled:not(:submit, :button, :image, :reset, :file):matches([checked], :not(:checkbox, :radio))').map((e,t)=>{var r;let n=this._make(t),i=n.attr("name"),a=(r=n.val())!==null&&r!==void 0?r:"";return Array.isArray(a)?a.map(o=>({name:i,value:o.replace(Ew,`\r -`)})):{name:i,value:a.replace(Ew,`\r -`)}}).toArray()}var bw,w4,Ew,vw=v(()=>{_r();bw="input,select,textarea,keygen",w4=/%20/g,Ew=/\r?\n/g});var Ug={};Nn(Ug,{extract:()=>N4});function I4(e){var t;return typeof e=="string"?{selector:e,value:"textContent"}:{selector:e.selector,value:(t=e.value)!==null&&t!==void 0?t:"textContent"}}function N4(e){let t={};for(let r in e){let n=e[r],i=Array.isArray(n),{selector:a,value:o}=I4(i?n[0]:n),l=typeof o=="function"?o:typeof o=="string"?d=>this._make(d).prop(o):d=>this._make(d).extract(o);if(i)t[r]=this._findBySelector(a,Number.POSITIVE_INFINITY).map((d,p)=>l(p,r,t)).get();else{let d=this._findBySelector(a,1);t[r]=d.length>0?l(d[0],r,t):void 0}}return t}var Tw=v(()=>{});var ja,xw=v(()=>{C2();lw();pw();_w();vw();Tw();ja=class{constructor(t,r,n){if(this.length=0,this.options=n,this._root=r,t){for(let i=0;i{rg();nu();xw();iu()});function Xd(e){return e>=55296&&e<=57343}function ww(e){return e>=56320&&e<=57343}function Sw(e,t){return(e-55296)*1024+9216+t}function Zd(e){return e!==32&&e!==10&&e!==13&&e!==9&&e!==12&&e>=1&&e<=31||e>=127&&e<=159}function Jd(e){return e>=64976&&e<=65007||D4.has(e)}var D4,xt,x,Vr,eh=v(()=>{D4=new Set([65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]),xt="\uFFFD";(function(e){e[e.EOF=-1]="EOF",e[e.NULL=0]="NULL",e[e.TABULATION=9]="TABULATION",e[e.CARRIAGE_RETURN=13]="CARRIAGE_RETURN",e[e.LINE_FEED=10]="LINE_FEED",e[e.FORM_FEED=12]="FORM_FEED",e[e.SPACE=32]="SPACE",e[e.EXCLAMATION_MARK=33]="EXCLAMATION_MARK",e[e.QUOTATION_MARK=34]="QUOTATION_MARK",e[e.AMPERSAND=38]="AMPERSAND",e[e.APOSTROPHE=39]="APOSTROPHE",e[e.HYPHEN_MINUS=45]="HYPHEN_MINUS",e[e.SOLIDUS=47]="SOLIDUS",e[e.DIGIT_0=48]="DIGIT_0",e[e.DIGIT_9=57]="DIGIT_9",e[e.SEMICOLON=59]="SEMICOLON",e[e.LESS_THAN_SIGN=60]="LESS_THAN_SIGN",e[e.EQUALS_SIGN=61]="EQUALS_SIGN",e[e.GREATER_THAN_SIGN=62]="GREATER_THAN_SIGN",e[e.QUESTION_MARK=63]="QUESTION_MARK",e[e.LATIN_CAPITAL_A=65]="LATIN_CAPITAL_A",e[e.LATIN_CAPITAL_Z=90]="LATIN_CAPITAL_Z",e[e.RIGHT_SQUARE_BRACKET=93]="RIGHT_SQUARE_BRACKET",e[e.GRAVE_ACCENT=96]="GRAVE_ACCENT",e[e.LATIN_SMALL_A=97]="LATIN_SMALL_A",e[e.LATIN_SMALL_Z=122]="LATIN_SMALL_Z"})(x||(x={}));Vr={DASH_DASH:"--",CDATA_START:"[CDATA[",DOCTYPE:"doctype",SCRIPT:"script",PUBLIC:"public",SYSTEM:"system"}});var Y,il=v(()=>{(function(e){e.controlCharacterInInputStream="control-character-in-input-stream",e.noncharacterInInputStream="noncharacter-in-input-stream",e.surrogateInInputStream="surrogate-in-input-stream",e.nonVoidHtmlElementStartTagWithTrailingSolidus="non-void-html-element-start-tag-with-trailing-solidus",e.endTagWithAttributes="end-tag-with-attributes",e.endTagWithTrailingSolidus="end-tag-with-trailing-solidus",e.unexpectedSolidusInTag="unexpected-solidus-in-tag",e.unexpectedNullCharacter="unexpected-null-character",e.unexpectedQuestionMarkInsteadOfTagName="unexpected-question-mark-instead-of-tag-name",e.invalidFirstCharacterOfTagName="invalid-first-character-of-tag-name",e.unexpectedEqualsSignBeforeAttributeName="unexpected-equals-sign-before-attribute-name",e.missingEndTagName="missing-end-tag-name",e.unexpectedCharacterInAttributeName="unexpected-character-in-attribute-name",e.unknownNamedCharacterReference="unknown-named-character-reference",e.missingSemicolonAfterCharacterReference="missing-semicolon-after-character-reference",e.unexpectedCharacterAfterDoctypeSystemIdentifier="unexpected-character-after-doctype-system-identifier",e.unexpectedCharacterInUnquotedAttributeValue="unexpected-character-in-unquoted-attribute-value",e.eofBeforeTagName="eof-before-tag-name",e.eofInTag="eof-in-tag",e.missingAttributeValue="missing-attribute-value",e.missingWhitespaceBetweenAttributes="missing-whitespace-between-attributes",e.missingWhitespaceAfterDoctypePublicKeyword="missing-whitespace-after-doctype-public-keyword",e.missingWhitespaceBetweenDoctypePublicAndSystemIdentifiers="missing-whitespace-between-doctype-public-and-system-identifiers",e.missingWhitespaceAfterDoctypeSystemKeyword="missing-whitespace-after-doctype-system-keyword",e.missingQuoteBeforeDoctypePublicIdentifier="missing-quote-before-doctype-public-identifier",e.missingQuoteBeforeDoctypeSystemIdentifier="missing-quote-before-doctype-system-identifier",e.missingDoctypePublicIdentifier="missing-doctype-public-identifier",e.missingDoctypeSystemIdentifier="missing-doctype-system-identifier",e.abruptDoctypePublicIdentifier="abrupt-doctype-public-identifier",e.abruptDoctypeSystemIdentifier="abrupt-doctype-system-identifier",e.cdataInHtmlContent="cdata-in-html-content",e.incorrectlyOpenedComment="incorrectly-opened-comment",e.eofInScriptHtmlCommentLikeText="eof-in-script-html-comment-like-text",e.eofInDoctype="eof-in-doctype",e.nestedComment="nested-comment",e.abruptClosingOfEmptyComment="abrupt-closing-of-empty-comment",e.eofInComment="eof-in-comment",e.incorrectlyClosedComment="incorrectly-closed-comment",e.eofInCdata="eof-in-cdata",e.absenceOfDigitsInNumericCharacterReference="absence-of-digits-in-numeric-character-reference",e.nullCharacterReference="null-character-reference",e.surrogateCharacterReference="surrogate-character-reference",e.characterReferenceOutsideUnicodeRange="character-reference-outside-unicode-range",e.controlCharacterReference="control-character-reference",e.noncharacterCharacterReference="noncharacter-character-reference",e.missingWhitespaceBeforeDoctypeName="missing-whitespace-before-doctype-name",e.missingDoctypeName="missing-doctype-name",e.invalidCharacterSequenceAfterDoctypeName="invalid-character-sequence-after-doctype-name",e.duplicateAttribute="duplicate-attribute",e.nonConformingDoctype="non-conforming-doctype",e.missingDoctype="missing-doctype",e.misplacedDoctype="misplaced-doctype",e.endTagWithoutMatchingOpenElement="end-tag-without-matching-open-element",e.closingOfElementWithOpenChildElements="closing-of-element-with-open-child-elements",e.disallowedContentInNoscriptInHead="disallowed-content-in-noscript-in-head",e.openElementsLeftAfterEof="open-elements-left-after-eof",e.abandonedHeadElementChild="abandoned-head-element-child",e.misplacedStartTagForHeadElement="misplaced-start-tag-for-head-element",e.nestedNoscriptInHead="nested-noscript-in-head",e.eofInElementThatCanContainOnlyText="eof-in-element-that-can-contain-only-text"})(Y||(Y={}))});var R4,th,Cw=v(()=>{eh();il();R4=65536,th=class{constructor(t){this.handler=t,this.html="",this.pos=-1,this.lastGapPos=-2,this.gapStack=[],this.skipNextNewLine=!1,this.lastChunkWritten=!1,this.endOfChunkHit=!1,this.bufferWaterline=R4,this.isEol=!1,this.lineStartPos=0,this.droppedBufferSize=0,this.line=1,this.lastErrOffset=-1}get col(){return this.pos-this.lineStartPos+ +(this.lastGapPos!==this.pos)}get offset(){return this.droppedBufferSize+this.pos}getError(t,r){let{line:n,col:i,offset:a}=this,o=i+r,l=a+r;return{code:t,startLine:n,endLine:n,startCol:o,endCol:o,startOffset:l,endOffset:l}}_err(t){this.handler.onParseError&&this.lastErrOffset!==this.offset&&(this.lastErrOffset=this.offset,this.handler.onParseError(this.getError(t,0)))}_addGap(){this.gapStack.push(this.lastGapPos),this.lastGapPos=this.pos}_processSurrogate(t){if(this.pos!==this.html.length-1){let r=this.html.charCodeAt(this.pos+1);if(ww(r))return this.pos++,this._addGap(),Sw(t,r)}else if(!this.lastChunkWritten)return this.endOfChunkHit=!0,x.EOF;return this._err(Y.surrogateInInputStream),t}willDropParsedChunk(){return this.pos>this.bufferWaterline}dropParsedChunk(){this.willDropParsedChunk()&&(this.html=this.html.substring(this.pos),this.lineStartPos-=this.pos,this.droppedBufferSize+=this.pos,this.pos=0,this.lastGapPos=-2,this.gapStack.length=0)}write(t,r){this.html.length>0?this.html+=t:this.html=t,this.endOfChunkHit=!1,this.lastChunkWritten=r}insertHtmlAtCurrentPos(t){this.html=this.html.substring(0,this.pos+1)+t+this.html.substring(this.pos+1),this.endOfChunkHit=!1}startsWith(t,r){if(this.pos+t.length>this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,!1;if(r)return this.html.startsWith(t,this.pos);for(let n=0;n=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,x.EOF;let n=this.html.charCodeAt(r);return n===x.CARRIAGE_RETURN?x.LINE_FEED:n}advance(){if(this.pos++,this.isEol&&(this.isEol=!1,this.line++,this.lineStartPos=this.pos),this.pos>=this.html.length)return this.endOfChunkHit=!this.lastChunkWritten,x.EOF;let t=this.html.charCodeAt(this.pos);return t===x.CARRIAGE_RETURN?(this.isEol=!0,this.skipNextNewLine=!0,x.LINE_FEED):t===x.LINE_FEED&&(this.isEol=!0,this.skipNextNewLine)?(this.line--,this.skipNextNewLine=!1,this._addGap(),this.advance()):(this.skipNextNewLine=!1,Xd(t)&&(t=this._processSurrogate(t)),this.handler.onParseError===null||t>31&&t<127||t===x.LINE_FEED||t===x.CARRIAGE_RETURN||t>159&&t<64976||this._checkForProblematicCharacters(t),t)}_checkForProblematicCharacters(t){Zd(t)?this._err(Y.controlCharacterInInputStream):Jd(t)&&this._err(Y.noncharacterInInputStream)}retreat(t){for(this.pos-=t;this.pos=0;r--)if(e.attrs[r].name===t)return e.attrs[r].value;return null}var Qe,nh=v(()=>{(function(e){e[e.CHARACTER=0]="CHARACTER",e[e.NULL_CHARACTER=1]="NULL_CHARACTER",e[e.WHITESPACE_CHARACTER=2]="WHITESPACE_CHARACTER",e[e.START_TAG=3]="START_TAG",e[e.END_TAG=4]="END_TAG",e[e.COMMENT=5]="COMMENT",e[e.DOCTYPE=6]="DOCTYPE",e[e.EOF=7]="EOF",e[e.HIBERNATION=8]="HIBERNATION"})(Qe||(Qe={}))});var ih={};Nn(ih,{ATTRS:()=>Oi,DOCUMENT_MODE:()=>kr,NS:()=>ee,NUMBERED_HEADERS:()=>fu,SPECIAL_ELEMENTS:()=>Vg,TAG_ID:()=>c,TAG_NAMES:()=>U,getTagID:()=>Wa,hasUnescapedText:()=>qg});function Wa(e){var t;return(t=P4.get(e))!==null&&t!==void 0?t:c.UNKNOWN}function qg(e,t){return M4.has(e)||t&&e===U.NOSCRIPT}var ee,Oi,kr,U,c,P4,ae,Vg,fu,M4,sa=v(()=>{(function(e){e.HTML="http://www.w3.org/1999/xhtml",e.MATHML="http://www.w3.org/1998/Math/MathML",e.SVG="http://www.w3.org/2000/svg",e.XLINK="http://www.w3.org/1999/xlink",e.XML="http://www.w3.org/XML/1998/namespace",e.XMLNS="http://www.w3.org/2000/xmlns/"})(ee||(ee={}));(function(e){e.TYPE="type",e.ACTION="action",e.ENCODING="encoding",e.PROMPT="prompt",e.NAME="name",e.COLOR="color",e.FACE="face",e.SIZE="size"})(Oi||(Oi={}));(function(e){e.NO_QUIRKS="no-quirks",e.QUIRKS="quirks",e.LIMITED_QUIRKS="limited-quirks"})(kr||(kr={}));(function(e){e.A="a",e.ADDRESS="address",e.ANNOTATION_XML="annotation-xml",e.APPLET="applet",e.AREA="area",e.ARTICLE="article",e.ASIDE="aside",e.B="b",e.BASE="base",e.BASEFONT="basefont",e.BGSOUND="bgsound",e.BIG="big",e.BLOCKQUOTE="blockquote",e.BODY="body",e.BR="br",e.BUTTON="button",e.CAPTION="caption",e.CENTER="center",e.CODE="code",e.COL="col",e.COLGROUP="colgroup",e.DD="dd",e.DESC="desc",e.DETAILS="details",e.DIALOG="dialog",e.DIR="dir",e.DIV="div",e.DL="dl",e.DT="dt",e.EM="em",e.EMBED="embed",e.FIELDSET="fieldset",e.FIGCAPTION="figcaption",e.FIGURE="figure",e.FONT="font",e.FOOTER="footer",e.FOREIGN_OBJECT="foreignObject",e.FORM="form",e.FRAME="frame",e.FRAMESET="frameset",e.H1="h1",e.H2="h2",e.H3="h3",e.H4="h4",e.H5="h5",e.H6="h6",e.HEAD="head",e.HEADER="header",e.HGROUP="hgroup",e.HR="hr",e.HTML="html",e.I="i",e.IMG="img",e.IMAGE="image",e.INPUT="input",e.IFRAME="iframe",e.KEYGEN="keygen",e.LABEL="label",e.LI="li",e.LINK="link",e.LISTING="listing",e.MAIN="main",e.MALIGNMARK="malignmark",e.MARQUEE="marquee",e.MATH="math",e.MENU="menu",e.META="meta",e.MGLYPH="mglyph",e.MI="mi",e.MO="mo",e.MN="mn",e.MS="ms",e.MTEXT="mtext",e.NAV="nav",e.NOBR="nobr",e.NOFRAMES="noframes",e.NOEMBED="noembed",e.NOSCRIPT="noscript",e.OBJECT="object",e.OL="ol",e.OPTGROUP="optgroup",e.OPTION="option",e.P="p",e.PARAM="param",e.PLAINTEXT="plaintext",e.PRE="pre",e.RB="rb",e.RP="rp",e.RT="rt",e.RTC="rtc",e.RUBY="ruby",e.S="s",e.SCRIPT="script",e.SEARCH="search",e.SECTION="section",e.SELECT="select",e.SOURCE="source",e.SMALL="small",e.SPAN="span",e.STRIKE="strike",e.STRONG="strong",e.STYLE="style",e.SUB="sub",e.SUMMARY="summary",e.SUP="sup",e.TABLE="table",e.TBODY="tbody",e.TEMPLATE="template",e.TEXTAREA="textarea",e.TFOOT="tfoot",e.TD="td",e.TH="th",e.THEAD="thead",e.TITLE="title",e.TR="tr",e.TRACK="track",e.TT="tt",e.U="u",e.UL="ul",e.SVG="svg",e.VAR="var",e.WBR="wbr",e.XMP="xmp"})(U||(U={}));(function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.A=1]="A",e[e.ADDRESS=2]="ADDRESS",e[e.ANNOTATION_XML=3]="ANNOTATION_XML",e[e.APPLET=4]="APPLET",e[e.AREA=5]="AREA",e[e.ARTICLE=6]="ARTICLE",e[e.ASIDE=7]="ASIDE",e[e.B=8]="B",e[e.BASE=9]="BASE",e[e.BASEFONT=10]="BASEFONT",e[e.BGSOUND=11]="BGSOUND",e[e.BIG=12]="BIG",e[e.BLOCKQUOTE=13]="BLOCKQUOTE",e[e.BODY=14]="BODY",e[e.BR=15]="BR",e[e.BUTTON=16]="BUTTON",e[e.CAPTION=17]="CAPTION",e[e.CENTER=18]="CENTER",e[e.CODE=19]="CODE",e[e.COL=20]="COL",e[e.COLGROUP=21]="COLGROUP",e[e.DD=22]="DD",e[e.DESC=23]="DESC",e[e.DETAILS=24]="DETAILS",e[e.DIALOG=25]="DIALOG",e[e.DIR=26]="DIR",e[e.DIV=27]="DIV",e[e.DL=28]="DL",e[e.DT=29]="DT",e[e.EM=30]="EM",e[e.EMBED=31]="EMBED",e[e.FIELDSET=32]="FIELDSET",e[e.FIGCAPTION=33]="FIGCAPTION",e[e.FIGURE=34]="FIGURE",e[e.FONT=35]="FONT",e[e.FOOTER=36]="FOOTER",e[e.FOREIGN_OBJECT=37]="FOREIGN_OBJECT",e[e.FORM=38]="FORM",e[e.FRAME=39]="FRAME",e[e.FRAMESET=40]="FRAMESET",e[e.H1=41]="H1",e[e.H2=42]="H2",e[e.H3=43]="H3",e[e.H4=44]="H4",e[e.H5=45]="H5",e[e.H6=46]="H6",e[e.HEAD=47]="HEAD",e[e.HEADER=48]="HEADER",e[e.HGROUP=49]="HGROUP",e[e.HR=50]="HR",e[e.HTML=51]="HTML",e[e.I=52]="I",e[e.IMG=53]="IMG",e[e.IMAGE=54]="IMAGE",e[e.INPUT=55]="INPUT",e[e.IFRAME=56]="IFRAME",e[e.KEYGEN=57]="KEYGEN",e[e.LABEL=58]="LABEL",e[e.LI=59]="LI",e[e.LINK=60]="LINK",e[e.LISTING=61]="LISTING",e[e.MAIN=62]="MAIN",e[e.MALIGNMARK=63]="MALIGNMARK",e[e.MARQUEE=64]="MARQUEE",e[e.MATH=65]="MATH",e[e.MENU=66]="MENU",e[e.META=67]="META",e[e.MGLYPH=68]="MGLYPH",e[e.MI=69]="MI",e[e.MO=70]="MO",e[e.MN=71]="MN",e[e.MS=72]="MS",e[e.MTEXT=73]="MTEXT",e[e.NAV=74]="NAV",e[e.NOBR=75]="NOBR",e[e.NOFRAMES=76]="NOFRAMES",e[e.NOEMBED=77]="NOEMBED",e[e.NOSCRIPT=78]="NOSCRIPT",e[e.OBJECT=79]="OBJECT",e[e.OL=80]="OL",e[e.OPTGROUP=81]="OPTGROUP",e[e.OPTION=82]="OPTION",e[e.P=83]="P",e[e.PARAM=84]="PARAM",e[e.PLAINTEXT=85]="PLAINTEXT",e[e.PRE=86]="PRE",e[e.RB=87]="RB",e[e.RP=88]="RP",e[e.RT=89]="RT",e[e.RTC=90]="RTC",e[e.RUBY=91]="RUBY",e[e.S=92]="S",e[e.SCRIPT=93]="SCRIPT",e[e.SEARCH=94]="SEARCH",e[e.SECTION=95]="SECTION",e[e.SELECT=96]="SELECT",e[e.SOURCE=97]="SOURCE",e[e.SMALL=98]="SMALL",e[e.SPAN=99]="SPAN",e[e.STRIKE=100]="STRIKE",e[e.STRONG=101]="STRONG",e[e.STYLE=102]="STYLE",e[e.SUB=103]="SUB",e[e.SUMMARY=104]="SUMMARY",e[e.SUP=105]="SUP",e[e.TABLE=106]="TABLE",e[e.TBODY=107]="TBODY",e[e.TEMPLATE=108]="TEMPLATE",e[e.TEXTAREA=109]="TEXTAREA",e[e.TFOOT=110]="TFOOT",e[e.TD=111]="TD",e[e.TH=112]="TH",e[e.THEAD=113]="THEAD",e[e.TITLE=114]="TITLE",e[e.TR=115]="TR",e[e.TRACK=116]="TRACK",e[e.TT=117]="TT",e[e.U=118]="U",e[e.UL=119]="UL",e[e.SVG=120]="SVG",e[e.VAR=121]="VAR",e[e.WBR=122]="WBR",e[e.XMP=123]="XMP"})(c||(c={}));P4=new Map([[U.A,c.A],[U.ADDRESS,c.ADDRESS],[U.ANNOTATION_XML,c.ANNOTATION_XML],[U.APPLET,c.APPLET],[U.AREA,c.AREA],[U.ARTICLE,c.ARTICLE],[U.ASIDE,c.ASIDE],[U.B,c.B],[U.BASE,c.BASE],[U.BASEFONT,c.BASEFONT],[U.BGSOUND,c.BGSOUND],[U.BIG,c.BIG],[U.BLOCKQUOTE,c.BLOCKQUOTE],[U.BODY,c.BODY],[U.BR,c.BR],[U.BUTTON,c.BUTTON],[U.CAPTION,c.CAPTION],[U.CENTER,c.CENTER],[U.CODE,c.CODE],[U.COL,c.COL],[U.COLGROUP,c.COLGROUP],[U.DD,c.DD],[U.DESC,c.DESC],[U.DETAILS,c.DETAILS],[U.DIALOG,c.DIALOG],[U.DIR,c.DIR],[U.DIV,c.DIV],[U.DL,c.DL],[U.DT,c.DT],[U.EM,c.EM],[U.EMBED,c.EMBED],[U.FIELDSET,c.FIELDSET],[U.FIGCAPTION,c.FIGCAPTION],[U.FIGURE,c.FIGURE],[U.FONT,c.FONT],[U.FOOTER,c.FOOTER],[U.FOREIGN_OBJECT,c.FOREIGN_OBJECT],[U.FORM,c.FORM],[U.FRAME,c.FRAME],[U.FRAMESET,c.FRAMESET],[U.H1,c.H1],[U.H2,c.H2],[U.H3,c.H3],[U.H4,c.H4],[U.H5,c.H5],[U.H6,c.H6],[U.HEAD,c.HEAD],[U.HEADER,c.HEADER],[U.HGROUP,c.HGROUP],[U.HR,c.HR],[U.HTML,c.HTML],[U.I,c.I],[U.IMG,c.IMG],[U.IMAGE,c.IMAGE],[U.INPUT,c.INPUT],[U.IFRAME,c.IFRAME],[U.KEYGEN,c.KEYGEN],[U.LABEL,c.LABEL],[U.LI,c.LI],[U.LINK,c.LINK],[U.LISTING,c.LISTING],[U.MAIN,c.MAIN],[U.MALIGNMARK,c.MALIGNMARK],[U.MARQUEE,c.MARQUEE],[U.MATH,c.MATH],[U.MENU,c.MENU],[U.META,c.META],[U.MGLYPH,c.MGLYPH],[U.MI,c.MI],[U.MO,c.MO],[U.MN,c.MN],[U.MS,c.MS],[U.MTEXT,c.MTEXT],[U.NAV,c.NAV],[U.NOBR,c.NOBR],[U.NOFRAMES,c.NOFRAMES],[U.NOEMBED,c.NOEMBED],[U.NOSCRIPT,c.NOSCRIPT],[U.OBJECT,c.OBJECT],[U.OL,c.OL],[U.OPTGROUP,c.OPTGROUP],[U.OPTION,c.OPTION],[U.P,c.P],[U.PARAM,c.PARAM],[U.PLAINTEXT,c.PLAINTEXT],[U.PRE,c.PRE],[U.RB,c.RB],[U.RP,c.RP],[U.RT,c.RT],[U.RTC,c.RTC],[U.RUBY,c.RUBY],[U.S,c.S],[U.SCRIPT,c.SCRIPT],[U.SEARCH,c.SEARCH],[U.SECTION,c.SECTION],[U.SELECT,c.SELECT],[U.SOURCE,c.SOURCE],[U.SMALL,c.SMALL],[U.SPAN,c.SPAN],[U.STRIKE,c.STRIKE],[U.STRONG,c.STRONG],[U.STYLE,c.STYLE],[U.SUB,c.SUB],[U.SUMMARY,c.SUMMARY],[U.SUP,c.SUP],[U.TABLE,c.TABLE],[U.TBODY,c.TBODY],[U.TEMPLATE,c.TEMPLATE],[U.TEXTAREA,c.TEXTAREA],[U.TFOOT,c.TFOOT],[U.TD,c.TD],[U.TH,c.TH],[U.THEAD,c.THEAD],[U.TITLE,c.TITLE],[U.TR,c.TR],[U.TRACK,c.TRACK],[U.TT,c.TT],[U.U,c.U],[U.UL,c.UL],[U.SVG,c.SVG],[U.VAR,c.VAR],[U.WBR,c.WBR],[U.XMP,c.XMP]]);ae=c,Vg={[ee.HTML]:new Set([ae.ADDRESS,ae.APPLET,ae.AREA,ae.ARTICLE,ae.ASIDE,ae.BASE,ae.BASEFONT,ae.BGSOUND,ae.BLOCKQUOTE,ae.BODY,ae.BR,ae.BUTTON,ae.CAPTION,ae.CENTER,ae.COL,ae.COLGROUP,ae.DD,ae.DETAILS,ae.DIR,ae.DIV,ae.DL,ae.DT,ae.EMBED,ae.FIELDSET,ae.FIGCAPTION,ae.FIGURE,ae.FOOTER,ae.FORM,ae.FRAME,ae.FRAMESET,ae.H1,ae.H2,ae.H3,ae.H4,ae.H5,ae.H6,ae.HEAD,ae.HEADER,ae.HGROUP,ae.HR,ae.HTML,ae.IFRAME,ae.IMG,ae.INPUT,ae.LI,ae.LINK,ae.LISTING,ae.MAIN,ae.MARQUEE,ae.MENU,ae.META,ae.NAV,ae.NOEMBED,ae.NOFRAMES,ae.NOSCRIPT,ae.OBJECT,ae.OL,ae.P,ae.PARAM,ae.PLAINTEXT,ae.PRE,ae.SCRIPT,ae.SECTION,ae.SELECT,ae.SOURCE,ae.STYLE,ae.SUMMARY,ae.TABLE,ae.TBODY,ae.TD,ae.TEMPLATE,ae.TEXTAREA,ae.TFOOT,ae.TH,ae.THEAD,ae.TITLE,ae.TR,ae.TRACK,ae.UL,ae.WBR,ae.XMP]),[ee.MATHML]:new Set([ae.MI,ae.MO,ae.MN,ae.MS,ae.MTEXT,ae.ANNOTATION_XML]),[ee.SVG]:new Set([ae.TITLE,ae.FOREIGN_OBJECT,ae.DESC]),[ee.XLINK]:new Set,[ee.XML]:new Set,[ee.XMLNS]:new Set},fu=new Set([ae.H1,ae.H2,ae.H3,ae.H4,ae.H5,ae.H6]),M4=new Set([U.STYLE,U.SCRIPT,U.XMP,U.IFRAME,U.NOEMBED,U.NOFRAMES,U.PLAINTEXT])});function F4(e){return e>=x.DIGIT_0&&e<=x.DIGIT_9}function al(e){return e>=x.LATIN_CAPITAL_A&&e<=x.LATIN_CAPITAL_Z}function B4(e){return e>=x.LATIN_SMALL_A&&e<=x.LATIN_SMALL_Z}function Ga(e){return B4(e)||al(e)}function Iw(e){return Ga(e)||F4(e)}function ah(e){return e+32}function Ow(e){return e===x.SPACE||e===x.LINE_FEED||e===x.TABULATION||e===x.FORM_FEED}function Nw(e){return Ow(e)||e===x.SOLIDUS||e===x.GREATER_THAN_SIGN}function $4(e){return e===x.NULL?Y.nullCharacterReference:e>1114111?Y.characterReferenceOutsideUnicodeRange:Xd(e)?Y.surrogateCharacterReference:Jd(e)?Y.noncharacterCharacterReference:Zd(e)||e===x.CARRIAGE_RETURN?Y.controlCharacterReference:null}var w,Rr,sl,zg=v(()=>{Cw();eh();nh();Zo();il();sa();(function(e){e[e.DATA=0]="DATA",e[e.RCDATA=1]="RCDATA",e[e.RAWTEXT=2]="RAWTEXT",e[e.SCRIPT_DATA=3]="SCRIPT_DATA",e[e.PLAINTEXT=4]="PLAINTEXT",e[e.TAG_OPEN=5]="TAG_OPEN",e[e.END_TAG_OPEN=6]="END_TAG_OPEN",e[e.TAG_NAME=7]="TAG_NAME",e[e.RCDATA_LESS_THAN_SIGN=8]="RCDATA_LESS_THAN_SIGN",e[e.RCDATA_END_TAG_OPEN=9]="RCDATA_END_TAG_OPEN",e[e.RCDATA_END_TAG_NAME=10]="RCDATA_END_TAG_NAME",e[e.RAWTEXT_LESS_THAN_SIGN=11]="RAWTEXT_LESS_THAN_SIGN",e[e.RAWTEXT_END_TAG_OPEN=12]="RAWTEXT_END_TAG_OPEN",e[e.RAWTEXT_END_TAG_NAME=13]="RAWTEXT_END_TAG_NAME",e[e.SCRIPT_DATA_LESS_THAN_SIGN=14]="SCRIPT_DATA_LESS_THAN_SIGN",e[e.SCRIPT_DATA_END_TAG_OPEN=15]="SCRIPT_DATA_END_TAG_OPEN",e[e.SCRIPT_DATA_END_TAG_NAME=16]="SCRIPT_DATA_END_TAG_NAME",e[e.SCRIPT_DATA_ESCAPE_START=17]="SCRIPT_DATA_ESCAPE_START",e[e.SCRIPT_DATA_ESCAPE_START_DASH=18]="SCRIPT_DATA_ESCAPE_START_DASH",e[e.SCRIPT_DATA_ESCAPED=19]="SCRIPT_DATA_ESCAPED",e[e.SCRIPT_DATA_ESCAPED_DASH=20]="SCRIPT_DATA_ESCAPED_DASH",e[e.SCRIPT_DATA_ESCAPED_DASH_DASH=21]="SCRIPT_DATA_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN=22]="SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_OPEN=23]="SCRIPT_DATA_ESCAPED_END_TAG_OPEN",e[e.SCRIPT_DATA_ESCAPED_END_TAG_NAME=24]="SCRIPT_DATA_ESCAPED_END_TAG_NAME",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_START=25]="SCRIPT_DATA_DOUBLE_ESCAPE_START",e[e.SCRIPT_DATA_DOUBLE_ESCAPED=26]="SCRIPT_DATA_DOUBLE_ESCAPED",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH=27]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH=28]="SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH",e[e.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN=29]="SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN",e[e.SCRIPT_DATA_DOUBLE_ESCAPE_END=30]="SCRIPT_DATA_DOUBLE_ESCAPE_END",e[e.BEFORE_ATTRIBUTE_NAME=31]="BEFORE_ATTRIBUTE_NAME",e[e.ATTRIBUTE_NAME=32]="ATTRIBUTE_NAME",e[e.AFTER_ATTRIBUTE_NAME=33]="AFTER_ATTRIBUTE_NAME",e[e.BEFORE_ATTRIBUTE_VALUE=34]="BEFORE_ATTRIBUTE_VALUE",e[e.ATTRIBUTE_VALUE_DOUBLE_QUOTED=35]="ATTRIBUTE_VALUE_DOUBLE_QUOTED",e[e.ATTRIBUTE_VALUE_SINGLE_QUOTED=36]="ATTRIBUTE_VALUE_SINGLE_QUOTED",e[e.ATTRIBUTE_VALUE_UNQUOTED=37]="ATTRIBUTE_VALUE_UNQUOTED",e[e.AFTER_ATTRIBUTE_VALUE_QUOTED=38]="AFTER_ATTRIBUTE_VALUE_QUOTED",e[e.SELF_CLOSING_START_TAG=39]="SELF_CLOSING_START_TAG",e[e.BOGUS_COMMENT=40]="BOGUS_COMMENT",e[e.MARKUP_DECLARATION_OPEN=41]="MARKUP_DECLARATION_OPEN",e[e.COMMENT_START=42]="COMMENT_START",e[e.COMMENT_START_DASH=43]="COMMENT_START_DASH",e[e.COMMENT=44]="COMMENT",e[e.COMMENT_LESS_THAN_SIGN=45]="COMMENT_LESS_THAN_SIGN",e[e.COMMENT_LESS_THAN_SIGN_BANG=46]="COMMENT_LESS_THAN_SIGN_BANG",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH=47]="COMMENT_LESS_THAN_SIGN_BANG_DASH",e[e.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH=48]="COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH",e[e.COMMENT_END_DASH=49]="COMMENT_END_DASH",e[e.COMMENT_END=50]="COMMENT_END",e[e.COMMENT_END_BANG=51]="COMMENT_END_BANG",e[e.DOCTYPE=52]="DOCTYPE",e[e.BEFORE_DOCTYPE_NAME=53]="BEFORE_DOCTYPE_NAME",e[e.DOCTYPE_NAME=54]="DOCTYPE_NAME",e[e.AFTER_DOCTYPE_NAME=55]="AFTER_DOCTYPE_NAME",e[e.AFTER_DOCTYPE_PUBLIC_KEYWORD=56]="AFTER_DOCTYPE_PUBLIC_KEYWORD",e[e.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER=57]="BEFORE_DOCTYPE_PUBLIC_IDENTIFIER",e[e.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED=58]="DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED=59]="DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_PUBLIC_IDENTIFIER=60]="AFTER_DOCTYPE_PUBLIC_IDENTIFIER",e[e.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS=61]="BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS",e[e.AFTER_DOCTYPE_SYSTEM_KEYWORD=62]="AFTER_DOCTYPE_SYSTEM_KEYWORD",e[e.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER=63]="BEFORE_DOCTYPE_SYSTEM_IDENTIFIER",e[e.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED=64]="DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED",e[e.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED=65]="DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED",e[e.AFTER_DOCTYPE_SYSTEM_IDENTIFIER=66]="AFTER_DOCTYPE_SYSTEM_IDENTIFIER",e[e.BOGUS_DOCTYPE=67]="BOGUS_DOCTYPE",e[e.CDATA_SECTION=68]="CDATA_SECTION",e[e.CDATA_SECTION_BRACKET=69]="CDATA_SECTION_BRACKET",e[e.CDATA_SECTION_END=70]="CDATA_SECTION_END",e[e.CHARACTER_REFERENCE=71]="CHARACTER_REFERENCE",e[e.AMBIGUOUS_AMPERSAND=72]="AMBIGUOUS_AMPERSAND"})(w||(w={}));Rr={DATA:w.DATA,RCDATA:w.RCDATA,RAWTEXT:w.RAWTEXT,SCRIPT_DATA:w.SCRIPT_DATA,PLAINTEXT:w.PLAINTEXT,CDATA_SECTION:w.CDATA_SECTION};sl=class{constructor(t,r){this.options=t,this.handler=r,this.paused=!1,this.inLoop=!1,this.inForeignNode=!1,this.lastStartTagName="",this.active=!1,this.state=w.DATA,this.returnState=w.DATA,this.entityStartPos=0,this.consumedAfterSnapshot=-1,this.currentCharacterToken=null,this.currentToken=null,this.currentAttr={name:"",value:""},this.preprocessor=new th(r),this.currentLocation=this.getCurrentLocation(-1),this.entityDecoder=new Ha(Qo,(n,i)=>{this.preprocessor.pos=this.entityStartPos+i-1,this._flushCodePointConsumedAsCharacterReference(n)},r.onParseError?{missingSemicolonAfterCharacterReference:()=>{this._err(Y.missingSemicolonAfterCharacterReference,1)},absenceOfDigitsInNumericCharacterReference:n=>{this._err(Y.absenceOfDigitsInNumericCharacterReference,this.entityStartPos-this.preprocessor.pos+n)},validateNumericCharacterReference:n=>{let i=$4(n);i&&this._err(i,1)}}:void 0)}_err(t,r=0){var n,i;(i=(n=this.handler).onParseError)===null||i===void 0||i.call(n,this.preprocessor.getError(t,r))}getCurrentLocation(t){return this.options.sourceCodeLocationInfo?{startLine:this.preprocessor.line,startCol:this.preprocessor.col-t,startOffset:this.preprocessor.offset-t,endLine:-1,endCol:-1,endOffset:-1}:null}_runParsingLoop(){if(!this.inLoop){for(this.inLoop=!0;this.active&&!this.paused;){this.consumedAfterSnapshot=0;let t=this._consume();this._ensureHibernation()||this._callState(t)}this.inLoop=!1}}pause(){this.paused=!0}resume(t){if(!this.paused)throw new Error("Parser was already resumed");this.paused=!1,!this.inLoop&&(this._runParsingLoop(),this.paused||t?.())}write(t,r,n){this.active=!0,this.preprocessor.write(t,r),this._runParsingLoop(),this.paused||n?.()}insertHtmlAtCurrentPos(t){this.active=!0,this.preprocessor.insertHtmlAtCurrentPos(t),this._runParsingLoop()}_ensureHibernation(){return this.preprocessor.endOfChunkHit?(this.preprocessor.retreat(this.consumedAfterSnapshot),this.consumedAfterSnapshot=0,this.active=!1,!0):!1}_consume(){return this.consumedAfterSnapshot++,this.preprocessor.advance()}_advanceBy(t){this.consumedAfterSnapshot+=t;for(let r=0;r0&&this._err(Y.endTagWithAttributes),t.selfClosing&&this._err(Y.endTagWithTrailingSolidus),this.handler.onEndTag(t)),this.preprocessor.dropParsedChunk()}emitCurrentComment(t){this.prepareToken(t),this.handler.onComment(t),this.preprocessor.dropParsedChunk()}emitCurrentDoctype(t){this.prepareToken(t),this.handler.onDoctype(t),this.preprocessor.dropParsedChunk()}_emitCurrentCharacterToken(t){if(this.currentCharacterToken){switch(t&&this.currentCharacterToken.location&&(this.currentCharacterToken.location.endLine=t.startLine,this.currentCharacterToken.location.endCol=t.startCol,this.currentCharacterToken.location.endOffset=t.startOffset),this.currentCharacterToken.type){case Qe.CHARACTER:{this.handler.onCharacter(this.currentCharacterToken);break}case Qe.NULL_CHARACTER:{this.handler.onNullCharacter(this.currentCharacterToken);break}case Qe.WHITESPACE_CHARACTER:{this.handler.onWhitespaceCharacter(this.currentCharacterToken);break}}this.currentCharacterToken=null}}_emitEOFToken(){let t=this.getCurrentLocation(0);t&&(t.endLine=t.startLine,t.endCol=t.startCol,t.endOffset=t.startOffset),this._emitCurrentCharacterToken(t),this.handler.onEof({type:Qe.EOF,location:t}),this.active=!1}_appendCharToCurrentCharacterToken(t,r){if(this.currentCharacterToken)if(this.currentCharacterToken.type===t){this.currentCharacterToken.chars+=r;return}else this.currentLocation=this.getCurrentLocation(0),this._emitCurrentCharacterToken(this.currentLocation),this.preprocessor.dropParsedChunk();this._createCharacterToken(t,r)}_emitCodePoint(t){let r=Ow(t)?Qe.WHITESPACE_CHARACTER:t===x.NULL?Qe.NULL_CHARACTER:Qe.CHARACTER;this._appendCharToCurrentCharacterToken(r,String.fromCodePoint(t))}_emitChars(t){this._appendCharToCurrentCharacterToken(Qe.CHARACTER,t)}_startCharacterReference(){this.returnState=this.state,this.state=w.CHARACTER_REFERENCE,this.entityStartPos=this.preprocessor.pos,this.entityDecoder.startEntity(this._isCharacterReferenceInAttribute()?Dr.Attribute:Dr.Legacy)}_isCharacterReferenceInAttribute(){return this.returnState===w.ATTRIBUTE_VALUE_DOUBLE_QUOTED||this.returnState===w.ATTRIBUTE_VALUE_SINGLE_QUOTED||this.returnState===w.ATTRIBUTE_VALUE_UNQUOTED}_flushCodePointConsumedAsCharacterReference(t){this._isCharacterReferenceInAttribute()?this.currentAttr.value+=String.fromCodePoint(t):this._emitCodePoint(t)}_callState(t){switch(this.state){case w.DATA:{this._stateData(t);break}case w.RCDATA:{this._stateRcdata(t);break}case w.RAWTEXT:{this._stateRawtext(t);break}case w.SCRIPT_DATA:{this._stateScriptData(t);break}case w.PLAINTEXT:{this._statePlaintext(t);break}case w.TAG_OPEN:{this._stateTagOpen(t);break}case w.END_TAG_OPEN:{this._stateEndTagOpen(t);break}case w.TAG_NAME:{this._stateTagName(t);break}case w.RCDATA_LESS_THAN_SIGN:{this._stateRcdataLessThanSign(t);break}case w.RCDATA_END_TAG_OPEN:{this._stateRcdataEndTagOpen(t);break}case w.RCDATA_END_TAG_NAME:{this._stateRcdataEndTagName(t);break}case w.RAWTEXT_LESS_THAN_SIGN:{this._stateRawtextLessThanSign(t);break}case w.RAWTEXT_END_TAG_OPEN:{this._stateRawtextEndTagOpen(t);break}case w.RAWTEXT_END_TAG_NAME:{this._stateRawtextEndTagName(t);break}case w.SCRIPT_DATA_LESS_THAN_SIGN:{this._stateScriptDataLessThanSign(t);break}case w.SCRIPT_DATA_END_TAG_OPEN:{this._stateScriptDataEndTagOpen(t);break}case w.SCRIPT_DATA_END_TAG_NAME:{this._stateScriptDataEndTagName(t);break}case w.SCRIPT_DATA_ESCAPE_START:{this._stateScriptDataEscapeStart(t);break}case w.SCRIPT_DATA_ESCAPE_START_DASH:{this._stateScriptDataEscapeStartDash(t);break}case w.SCRIPT_DATA_ESCAPED:{this._stateScriptDataEscaped(t);break}case w.SCRIPT_DATA_ESCAPED_DASH:{this._stateScriptDataEscapedDash(t);break}case w.SCRIPT_DATA_ESCAPED_DASH_DASH:{this._stateScriptDataEscapedDashDash(t);break}case w.SCRIPT_DATA_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataEscapedLessThanSign(t);break}case w.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:{this._stateScriptDataEscapedEndTagOpen(t);break}case w.SCRIPT_DATA_ESCAPED_END_TAG_NAME:{this._stateScriptDataEscapedEndTagName(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPE_START:{this._stateScriptDataDoubleEscapeStart(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPED:{this._stateScriptDataDoubleEscaped(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPED_DASH:{this._stateScriptDataDoubleEscapedDash(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPED_DASH_DASH:{this._stateScriptDataDoubleEscapedDashDash(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPED_LESS_THAN_SIGN:{this._stateScriptDataDoubleEscapedLessThanSign(t);break}case w.SCRIPT_DATA_DOUBLE_ESCAPE_END:{this._stateScriptDataDoubleEscapeEnd(t);break}case w.BEFORE_ATTRIBUTE_NAME:{this._stateBeforeAttributeName(t);break}case w.ATTRIBUTE_NAME:{this._stateAttributeName(t);break}case w.AFTER_ATTRIBUTE_NAME:{this._stateAfterAttributeName(t);break}case w.BEFORE_ATTRIBUTE_VALUE:{this._stateBeforeAttributeValue(t);break}case w.ATTRIBUTE_VALUE_DOUBLE_QUOTED:{this._stateAttributeValueDoubleQuoted(t);break}case w.ATTRIBUTE_VALUE_SINGLE_QUOTED:{this._stateAttributeValueSingleQuoted(t);break}case w.ATTRIBUTE_VALUE_UNQUOTED:{this._stateAttributeValueUnquoted(t);break}case w.AFTER_ATTRIBUTE_VALUE_QUOTED:{this._stateAfterAttributeValueQuoted(t);break}case w.SELF_CLOSING_START_TAG:{this._stateSelfClosingStartTag(t);break}case w.BOGUS_COMMENT:{this._stateBogusComment(t);break}case w.MARKUP_DECLARATION_OPEN:{this._stateMarkupDeclarationOpen(t);break}case w.COMMENT_START:{this._stateCommentStart(t);break}case w.COMMENT_START_DASH:{this._stateCommentStartDash(t);break}case w.COMMENT:{this._stateComment(t);break}case w.COMMENT_LESS_THAN_SIGN:{this._stateCommentLessThanSign(t);break}case w.COMMENT_LESS_THAN_SIGN_BANG:{this._stateCommentLessThanSignBang(t);break}case w.COMMENT_LESS_THAN_SIGN_BANG_DASH:{this._stateCommentLessThanSignBangDash(t);break}case w.COMMENT_LESS_THAN_SIGN_BANG_DASH_DASH:{this._stateCommentLessThanSignBangDashDash(t);break}case w.COMMENT_END_DASH:{this._stateCommentEndDash(t);break}case w.COMMENT_END:{this._stateCommentEnd(t);break}case w.COMMENT_END_BANG:{this._stateCommentEndBang(t);break}case w.DOCTYPE:{this._stateDoctype(t);break}case w.BEFORE_DOCTYPE_NAME:{this._stateBeforeDoctypeName(t);break}case w.DOCTYPE_NAME:{this._stateDoctypeName(t);break}case w.AFTER_DOCTYPE_NAME:{this._stateAfterDoctypeName(t);break}case w.AFTER_DOCTYPE_PUBLIC_KEYWORD:{this._stateAfterDoctypePublicKeyword(t);break}case w.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateBeforeDoctypePublicIdentifier(t);break}case w.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypePublicIdentifierDoubleQuoted(t);break}case w.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypePublicIdentifierSingleQuoted(t);break}case w.AFTER_DOCTYPE_PUBLIC_IDENTIFIER:{this._stateAfterDoctypePublicIdentifier(t);break}case w.BETWEEN_DOCTYPE_PUBLIC_AND_SYSTEM_IDENTIFIERS:{this._stateBetweenDoctypePublicAndSystemIdentifiers(t);break}case w.AFTER_DOCTYPE_SYSTEM_KEYWORD:{this._stateAfterDoctypeSystemKeyword(t);break}case w.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateBeforeDoctypeSystemIdentifier(t);break}case w.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED:{this._stateDoctypeSystemIdentifierDoubleQuoted(t);break}case w.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED:{this._stateDoctypeSystemIdentifierSingleQuoted(t);break}case w.AFTER_DOCTYPE_SYSTEM_IDENTIFIER:{this._stateAfterDoctypeSystemIdentifier(t);break}case w.BOGUS_DOCTYPE:{this._stateBogusDoctype(t);break}case w.CDATA_SECTION:{this._stateCdataSection(t);break}case w.CDATA_SECTION_BRACKET:{this._stateCdataSectionBracket(t);break}case w.CDATA_SECTION_END:{this._stateCdataSectionEnd(t);break}case w.CHARACTER_REFERENCE:{this._stateCharacterReference();break}case w.AMBIGUOUS_AMPERSAND:{this._stateAmbiguousAmpersand(t);break}default:throw new Error("Unknown state")}}_stateData(t){switch(t){case x.LESS_THAN_SIGN:{this.state=w.TAG_OPEN;break}case x.AMPERSAND:{this._startCharacterReference();break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this._emitCodePoint(t);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRcdata(t){switch(t){case x.AMPERSAND:{this._startCharacterReference();break}case x.LESS_THAN_SIGN:{this.state=w.RCDATA_LESS_THAN_SIGN;break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this._emitChars(xt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateRawtext(t){switch(t){case x.LESS_THAN_SIGN:{this.state=w.RAWTEXT_LESS_THAN_SIGN;break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this._emitChars(xt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateScriptData(t){switch(t){case x.LESS_THAN_SIGN:{this.state=w.SCRIPT_DATA_LESS_THAN_SIGN;break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this._emitChars(xt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_statePlaintext(t){switch(t){case x.NULL:{this._err(Y.unexpectedNullCharacter),this._emitChars(xt);break}case x.EOF:{this._emitEOFToken();break}default:this._emitCodePoint(t)}}_stateTagOpen(t){if(Ga(t))this._createStartTagToken(),this.state=w.TAG_NAME,this._stateTagName(t);else switch(t){case x.EXCLAMATION_MARK:{this.state=w.MARKUP_DECLARATION_OPEN;break}case x.SOLIDUS:{this.state=w.END_TAG_OPEN;break}case x.QUESTION_MARK:{this._err(Y.unexpectedQuestionMarkInsteadOfTagName),this._createCommentToken(1),this.state=w.BOGUS_COMMENT,this._stateBogusComment(t);break}case x.EOF:{this._err(Y.eofBeforeTagName),this._emitChars("<"),this._emitEOFToken();break}default:this._err(Y.invalidFirstCharacterOfTagName),this._emitChars("<"),this.state=w.DATA,this._stateData(t)}}_stateEndTagOpen(t){if(Ga(t))this._createEndTagToken(),this.state=w.TAG_NAME,this._stateTagName(t);else switch(t){case x.GREATER_THAN_SIGN:{this._err(Y.missingEndTagName),this.state=w.DATA;break}case x.EOF:{this._err(Y.eofBeforeTagName),this._emitChars("");break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this.state=w.SCRIPT_DATA_ESCAPED,this._emitChars(xt);break}case x.EOF:{this._err(Y.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=w.SCRIPT_DATA_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataEscapedLessThanSign(t){t===x.SOLIDUS?this.state=w.SCRIPT_DATA_ESCAPED_END_TAG_OPEN:Ga(t)?(this._emitChars("<"),this.state=w.SCRIPT_DATA_DOUBLE_ESCAPE_START,this._stateScriptDataDoubleEscapeStart(t)):(this._emitChars("<"),this.state=w.SCRIPT_DATA_ESCAPED,this._stateScriptDataEscaped(t))}_stateScriptDataEscapedEndTagOpen(t){Ga(t)?(this.state=w.SCRIPT_DATA_ESCAPED_END_TAG_NAME,this._stateScriptDataEscapedEndTagName(t)):(this._emitChars("");break}case x.NULL:{this._err(Y.unexpectedNullCharacter),this.state=w.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitChars(xt);break}case x.EOF:{this._err(Y.eofInScriptHtmlCommentLikeText),this._emitEOFToken();break}default:this.state=w.SCRIPT_DATA_DOUBLE_ESCAPED,this._emitCodePoint(t)}}_stateScriptDataDoubleEscapedLessThanSign(t){t===x.SOLIDUS?(this.state=w.SCRIPT_DATA_DOUBLE_ESCAPE_END,this._emitChars("/")):(this.state=w.SCRIPT_DATA_DOUBLE_ESCAPED,this._stateScriptDataDoubleEscaped(t))}_stateScriptDataDoubleEscapeEnd(t){if(this.preprocessor.startsWith(Vr.SCRIPT,!1)&&Nw(this.preprocessor.peek(Vr.SCRIPT.length))){this._emitCodePoint(t);for(let r=0;r{sa();Lw=new Set([c.DD,c.DT,c.LI,c.OPTGROUP,c.OPTION,c.P,c.RB,c.RP,c.RT,c.RTC]),Dw=new Set([...Lw,c.CAPTION,c.COLGROUP,c.TBODY,c.TD,c.TFOOT,c.TH,c.THEAD,c.TR]),sh=new Set([c.APPLET,c.CAPTION,c.HTML,c.MARQUEE,c.OBJECT,c.TABLE,c.TD,c.TEMPLATE,c.TH]),H4=new Set([...sh,c.OL,c.UL]),U4=new Set([...sh,c.BUTTON]),kw=new Set([c.ANNOTATION_XML,c.MI,c.MN,c.MO,c.MS,c.MTEXT]),Rw=new Set([c.DESC,c.FOREIGN_OBJECT,c.TITLE]),V4=new Set([c.TR,c.TEMPLATE,c.HTML]),q4=new Set([c.TBODY,c.TFOOT,c.THEAD,c.TEMPLATE,c.HTML]),z4=new Set([c.TABLE,c.TEMPLATE,c.HTML]),Y4=new Set([c.TD,c.TH]),oh=class{get currentTmplContentOrNode(){return this._isInTemplate()?this.treeAdapter.getTemplateContent(this.current):this.current}constructor(t,r,n){this.treeAdapter=r,this.handler=n,this.items=[],this.tagIDs=[],this.stackTop=-1,this.tmplCount=0,this.currentTagId=c.UNKNOWN,this.current=t}_indexOf(t){return this.items.lastIndexOf(t,this.stackTop)}_isInTemplate(){return this.currentTagId===c.TEMPLATE&&this.treeAdapter.getNamespaceURI(this.current)===ee.HTML}_updateCurrentElement(){this.current=this.items[this.stackTop],this.currentTagId=this.tagIDs[this.stackTop]}push(t,r){this.stackTop++,this.items[this.stackTop]=t,this.current=t,this.tagIDs[this.stackTop]=r,this.currentTagId=r,this._isInTemplate()&&this.tmplCount++,this.handler.onItemPush(t,r,!0)}pop(){let t=this.current;this.tmplCount>0&&this._isInTemplate()&&this.tmplCount--,this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!0)}replace(t,r){let n=this._indexOf(t);this.items[n]=r,n===this.stackTop&&(this.current=r)}insertAfter(t,r,n){let i=this._indexOf(t)+1;this.items.splice(i,0,r),this.tagIDs.splice(i,0,n),this.stackTop++,i===this.stackTop&&this._updateCurrentElement(),this.handler.onItemPush(this.current,this.currentTagId,i===this.stackTop)}popUntilTagNamePopped(t){let r=this.stackTop+1;do r=this.tagIDs.lastIndexOf(t,r-1);while(r>0&&this.treeAdapter.getNamespaceURI(this.items[r])!==ee.HTML);this.shortenToLength(r<0?0:r)}shortenToLength(t){for(;this.stackTop>=t;){let r=this.current;this.tmplCount>0&&this._isInTemplate()&&(this.tmplCount-=1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(r,this.stackTop=0;n--)if(t.has(this.tagIDs[n])&&this.treeAdapter.getNamespaceURI(this.items[n])===r)return n;return-1}clearBackTo(t,r){let n=this._indexOfTagNames(t,r);this.shortenToLength(n+1)}clearBackToTableContext(){this.clearBackTo(z4,ee.HTML)}clearBackToTableBodyContext(){this.clearBackTo(q4,ee.HTML)}clearBackToTableRowContext(){this.clearBackTo(V4,ee.HTML)}remove(t){let r=this._indexOf(t);r>=0&&(r===this.stackTop?this.pop():(this.items.splice(r,1),this.tagIDs.splice(r,1),this.stackTop--,this._updateCurrentElement(),this.handler.onItemPop(t,!1)))}tryPeekProperlyNestedBodyElement(){return this.stackTop>=1&&this.tagIDs[1]===c.BODY?this.items[1]:null}contains(t){return this._indexOf(t)>-1}getCommonAncestor(t){let r=this._indexOf(t)-1;return r>=0?this.items[r]:null}isRootHtmlElementCurrent(){return this.stackTop===0&&this.tagIDs[0]===c.HTML}hasInDynamicScope(t,r){for(let n=this.stackTop;n>=0;n--){let i=this.tagIDs[n];switch(this.treeAdapter.getNamespaceURI(this.items[n])){case ee.HTML:{if(i===t)return!0;if(r.has(i))return!1;break}case ee.SVG:{if(Rw.has(i))return!1;break}case ee.MATHML:{if(kw.has(i))return!1;break}}}return!0}hasInScope(t){return this.hasInDynamicScope(t,sh)}hasInListItemScope(t){return this.hasInDynamicScope(t,H4)}hasInButtonScope(t){return this.hasInDynamicScope(t,U4)}hasNumberedHeaderInScope(){for(let t=this.stackTop;t>=0;t--){let r=this.tagIDs[t];switch(this.treeAdapter.getNamespaceURI(this.items[t])){case ee.HTML:{if(fu.has(r))return!0;if(sh.has(r))return!1;break}case ee.SVG:{if(Rw.has(r))return!1;break}case ee.MATHML:{if(kw.has(r))return!1;break}}}return!0}hasInTableScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ee.HTML)switch(this.tagIDs[r]){case t:return!0;case c.TABLE:case c.HTML:return!1}return!0}hasTableBodyContextInTableScope(){for(let t=this.stackTop;t>=0;t--)if(this.treeAdapter.getNamespaceURI(this.items[t])===ee.HTML)switch(this.tagIDs[t]){case c.TBODY:case c.THEAD:case c.TFOOT:return!0;case c.TABLE:case c.HTML:return!1}return!0}hasInSelectScope(t){for(let r=this.stackTop;r>=0;r--)if(this.treeAdapter.getNamespaceURI(this.items[r])===ee.HTML)switch(this.tagIDs[r]){case t:return!0;case c.OPTION:case c.OPTGROUP:break;default:return!1}return!0}generateImpliedEndTags(){for(;Lw.has(this.currentTagId);)this.pop()}generateImpliedEndTagsThoroughly(){for(;Dw.has(this.currentTagId);)this.pop()}generateImpliedEndTagsWithExclusion(t){for(;this.currentTagId!==t&&Dw.has(this.currentTagId);)this.pop()}}});var ci,Mw,uh,Fw=v(()=>{(function(e){e[e.Marker=0]="Marker",e[e.Element=1]="Element"})(ci||(ci={}));Mw={type:ci.Marker},uh=class{constructor(t){this.treeAdapter=t,this.entries=[],this.bookmark=null}_getNoahArkConditionCandidates(t,r){let n=[],i=r.length,a=this.treeAdapter.getTagName(t),o=this.treeAdapter.getNamespaceURI(t);for(let l=0;l[o.name,o.value])),a=0;for(let o=0;oi.get(d.name)===d.value)&&(a+=1,a>=3&&this.entries.splice(l.idx,1))}}insertMarker(){this.entries.unshift(Mw)}pushElement(t,r){this._ensureNoahArkCondition(t),this.entries.unshift({type:ci.Element,element:t,token:r})}insertElementAfterBookmark(t,r){let n=this.entries.indexOf(this.bookmark);this.entries.splice(n,0,{type:ci.Element,element:t,token:r})}removeEntry(t){let r=this.entries.indexOf(t);r>=0&&this.entries.splice(r,1)}clearToLastMarker(){let t=this.entries.indexOf(Mw);t>=0?this.entries.splice(0,t+1):this.entries.length=0}getElementEntryInScopeWithTagName(t){let r=this.entries.find(n=>n.type===ci.Marker||this.treeAdapter.getTagName(n.element)===t);return r&&r.type===ci.Element?r:null}getElementEntry(t){return this.entries.find(r=>r.type===ci.Element&&r.element===t)}}});var Vn,ch=v(()=>{sa();Vn={createDocument(){return{nodeName:"#document",mode:kr.NO_QUIRKS,childNodes:[]}},createDocumentFragment(){return{nodeName:"#document-fragment",childNodes:[]}},createElement(e,t,r){return{nodeName:e,tagName:e,attrs:r,namespaceURI:t,childNodes:[],parentNode:null}},createCommentNode(e){return{nodeName:"#comment",data:e,parentNode:null}},createTextNode(e){return{nodeName:"#text",value:e,parentNode:null}},appendChild(e,t){e.childNodes.push(t),t.parentNode=e},insertBefore(e,t,r){let n=e.childNodes.indexOf(r);e.childNodes.splice(n,0,t),t.parentNode=e},setTemplateContent(e,t){e.content=t},getTemplateContent(e){return e.content},setDocumentType(e,t,r,n){let i=e.childNodes.find(a=>a.nodeName==="#documentType");if(i)i.name=t,i.publicId=r,i.systemId=n;else{let a={nodeName:"#documentType",name:t,publicId:r,systemId:n,parentNode:null};Vn.appendChild(e,a)}},setDocumentMode(e,t){e.mode=t},getDocumentMode(e){return e.mode},detachNode(e){if(e.parentNode){let t=e.parentNode.childNodes.indexOf(e);e.parentNode.childNodes.splice(t,1),e.parentNode=null}},insertText(e,t){if(e.childNodes.length>0){let r=e.childNodes[e.childNodes.length-1];if(Vn.isTextNode(r)){r.value+=t;return}}Vn.appendChild(e,Vn.createTextNode(t))},insertTextBefore(e,t,r){let n=e.childNodes[e.childNodes.indexOf(r)-1];n&&Vn.isTextNode(n)?n.value+=t:Vn.insertBefore(e,Vn.createTextNode(t),r)},adoptAttributes(e,t){let r=new Set(e.attrs.map(n=>n.name));for(let n=0;ne.startsWith(r))}function Vw(e){return e.name===$w&&e.publicId===null&&(e.systemId===null||e.systemId===K4)}function qw(e){if(e.name!==$w)return kr.QUIRKS;let{systemId:t}=e;if(t&&t.toLowerCase()===j4)return kr.QUIRKS;let{publicId:r}=e;if(r!==null){if(r=r.toLowerCase(),G4.has(r))return kr.QUIRKS;let n=t===null?W4:Hw;if(Bw(r,n))return kr.QUIRKS;if(n=t===null?Uw:Q4,Bw(r,n))return kr.LIMITED_QUIRKS}return kr.NO_QUIRKS}var $w,K4,j4,Hw,W4,G4,Uw,Q4,zw=v(()=>{sa();$w="html",K4="about:legacy-compat",j4="http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd",Hw=["+//silmaril//dtd html pro v0r11 19970101//","-//as//dtd html 3.0 aswedit + extensions//","-//advasoft ltd//dtd html 3.0 aswedit + extensions//","-//ietf//dtd html 2.0 level 1//","-//ietf//dtd html 2.0 level 2//","-//ietf//dtd html 2.0 strict level 1//","-//ietf//dtd html 2.0 strict level 2//","-//ietf//dtd html 2.0 strict//","-//ietf//dtd html 2.0//","-//ietf//dtd html 2.1e//","-//ietf//dtd html 3.0//","-//ietf//dtd html 3.2 final//","-//ietf//dtd html 3.2//","-//ietf//dtd html 3//","-//ietf//dtd html level 0//","-//ietf//dtd html level 1//","-//ietf//dtd html level 2//","-//ietf//dtd html level 3//","-//ietf//dtd html strict level 0//","-//ietf//dtd html strict level 1//","-//ietf//dtd html strict level 2//","-//ietf//dtd html strict level 3//","-//ietf//dtd html strict//","-//ietf//dtd html//","-//metrius//dtd metrius presentational//","-//microsoft//dtd internet explorer 2.0 html strict//","-//microsoft//dtd internet explorer 2.0 html//","-//microsoft//dtd internet explorer 2.0 tables//","-//microsoft//dtd internet explorer 3.0 html strict//","-//microsoft//dtd internet explorer 3.0 html//","-//microsoft//dtd internet explorer 3.0 tables//","-//netscape comm. corp.//dtd html//","-//netscape comm. corp.//dtd strict html//","-//o'reilly and associates//dtd html 2.0//","-//o'reilly and associates//dtd html extended 1.0//","-//o'reilly and associates//dtd html extended relaxed 1.0//","-//sq//dtd html 2.0 hotmetal + extensions//","-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//","-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//","-//spyglass//dtd html 2.0 extended//","-//sun microsystems corp.//dtd hotjava html//","-//sun microsystems corp.//dtd hotjava strict html//","-//w3c//dtd html 3 1995-03-24//","-//w3c//dtd html 3.2 draft//","-//w3c//dtd html 3.2 final//","-//w3c//dtd html 3.2//","-//w3c//dtd html 3.2s draft//","-//w3c//dtd html 4.0 frameset//","-//w3c//dtd html 4.0 transitional//","-//w3c//dtd html experimental 19960712//","-//w3c//dtd html experimental 970421//","-//w3c//dtd w3 html//","-//w3o//dtd w3 html 3.0//","-//webtechs//dtd mozilla html 2.0//","-//webtechs//dtd mozilla html//"],W4=[...Hw,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"],G4=new Set(["-//w3o//dtd w3 html strict 3.0//en//","-/w3c/dtd html 4.0 transitional/en","html"]),Uw=["-//w3c//dtd xhtml 1.0 frameset//","-//w3c//dtd xhtml 1.0 transitional//"],Q4=[...Uw,"-//w3c//dtd html 4.01 frameset//","-//w3c//dtd html 4.01 transitional//"]});function Kw(e){let t=e.tagID;return t===c.FONT&&e.attrs.some(({name:n})=>n===Oi.COLOR||n===Oi.SIZE||n===Oi.FACE)||n8.has(t)}function Yg(e){for(let t=0;t{sa();Yw={TEXT_HTML:"text/html",APPLICATION_XML:"application/xhtml+xml"},Z4="definitionurl",J4="definitionURL",e8=new Map(["attributeName","attributeType","baseFrequency","baseProfile","calcMode","clipPathUnits","diffuseConstant","edgeMode","filterUnits","glyphRef","gradientTransform","gradientUnits","kernelMatrix","kernelUnitLength","keyPoints","keySplines","keyTimes","lengthAdjust","limitingConeAngle","markerHeight","markerUnits","markerWidth","maskContentUnits","maskUnits","numOctaves","pathLength","patternContentUnits","patternTransform","patternUnits","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","refX","refY","repeatCount","repeatDur","requiredExtensions","requiredFeatures","specularConstant","specularExponent","spreadMethod","startOffset","stdDeviation","stitchTiles","surfaceScale","systemLanguage","tableValues","targetX","targetY","textLength","viewBox","viewTarget","xChannelSelector","yChannelSelector","zoomAndPan"].map(e=>[e.toLowerCase(),e])),t8=new Map([["xlink:actuate",{prefix:"xlink",name:"actuate",namespace:ee.XLINK}],["xlink:arcrole",{prefix:"xlink",name:"arcrole",namespace:ee.XLINK}],["xlink:href",{prefix:"xlink",name:"href",namespace:ee.XLINK}],["xlink:role",{prefix:"xlink",name:"role",namespace:ee.XLINK}],["xlink:show",{prefix:"xlink",name:"show",namespace:ee.XLINK}],["xlink:title",{prefix:"xlink",name:"title",namespace:ee.XLINK}],["xlink:type",{prefix:"xlink",name:"type",namespace:ee.XLINK}],["xml:lang",{prefix:"xml",name:"lang",namespace:ee.XML}],["xml:space",{prefix:"xml",name:"space",namespace:ee.XML}],["xmlns",{prefix:"",name:"xmlns",namespace:ee.XMLNS}],["xmlns:xlink",{prefix:"xmlns",name:"xlink",namespace:ee.XMLNS}]]),r8=new Map(["altGlyph","altGlyphDef","altGlyphItem","animateColor","animateMotion","animateTransform","clipPath","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","foreignObject","glyphRef","linearGradient","radialGradient","textPath"].map(e=>[e.toLowerCase(),e])),n8=new Set([c.B,c.BIG,c.BLOCKQUOTE,c.BODY,c.BR,c.CENTER,c.CODE,c.DD,c.DIV,c.DL,c.DT,c.EM,c.EMBED,c.H1,c.H2,c.H3,c.H4,c.H5,c.H6,c.HEAD,c.HR,c.I,c.IMG,c.LI,c.LISTING,c.MENU,c.META,c.NOBR,c.OL,c.P,c.PRE,c.RUBY,c.S,c.SMALL,c.SPAN,c.STRONG,c.STRIKE,c.SUB,c.SUP,c.TABLE,c.TT,c.U,c.UL,c.VAR])});function l8(e,t){let r=e.activeFormattingElements.getElementEntryInScopeWithTagName(t.tagName);return r?e.openElements.contains(r.element)?e.openElements.hasInScope(t.tagID)||(r=null):(e.activeFormattingElements.removeEntry(r),r=null):iS(e,t),r}function f8(e,t){let r=null,n=e.openElements.stackTop;for(;n>=0;n--){let i=e.openElements.items[n];if(i===t.element)break;e._isSpecialElement(i,e.openElements.tagIDs[n])&&(r=i)}return r||(e.openElements.shortenToLength(n<0?0:n),e.activeFormattingElements.removeEntry(t)),r}function d8(e,t,r){let n=t,i=e.openElements.getCommonAncestor(t);for(let a=0,o=i;o!==r;a++,o=i){i=e.openElements.getCommonAncestor(o);let l=e.activeFormattingElements.getElementEntry(o),d=l&&a>=u8;!l||d?(d&&e.activeFormattingElements.removeEntry(l),e.openElements.remove(o)):(o=h8(e,l),n===t&&(e.activeFormattingElements.bookmark=l),e.treeAdapter.detachNode(n),e.treeAdapter.appendChild(o,n),n=o)}return n}function h8(e,t){let r=e.treeAdapter.getNamespaceURI(t.element),n=e.treeAdapter.createElement(t.token.tagName,r,t.token.attrs);return e.openElements.replace(t.element,n),t.element=n,n}function p8(e,t,r){let n=e.treeAdapter.getTagName(t),i=Wa(n);if(e._isElementCausesFosterParenting(i))e._fosterParentElement(r);else{let a=e.treeAdapter.getNamespaceURI(t);i===c.TEMPLATE&&a===ee.HTML&&(t=e.treeAdapter.getTemplateContent(t)),e.treeAdapter.appendChild(t,r)}}function m8(e,t,r){let n=e.treeAdapter.getNamespaceURI(r.element),{token:i}=r,a=e.treeAdapter.createElement(i.tagName,n,i.attrs);e._adoptNodes(t,a),e.treeAdapter.appendChild(t,a),e.activeFormattingElements.insertElementAfterBookmark(a,i),e.activeFormattingElements.removeEntry(r),e.openElements.remove(r.element),e.openElements.insertAfter(t,a,i.tagID)}function Xg(e,t){for(let r=0;r=r;n--)e._setEndLocation(e.openElements.items[n],t);if(!e.fragmentContext&&e.openElements.stackTop>=0){let n=e.openElements.items[0],i=e.treeAdapter.getNodeSourceCodeLocation(n);if(i&&!i.endTag&&(e._setEndLocation(n,t),e.openElements.stackTop>=1)){let a=e.openElements.items[1],o=e.treeAdapter.getNodeSourceCodeLocation(a);o&&!o.endTag&&e._setEndLocation(a,t)}}}}function b8(e,t){e._setDocumentType(t);let r=t.forceQuirks?kr.QUIRKS:qw(t);Vw(t)||e._err(t,Y.nonConformingDoctype),e.treeAdapter.setDocumentMode(e.document,r),e.insertionMode=I.BEFORE_HTML}function ol(e,t){e._err(t,Y.missingDoctype,!0),e.treeAdapter.setDocumentMode(e.document,kr.QUIRKS),e.insertionMode=I.BEFORE_HTML,e._processToken(t)}function E8(e,t){t.tagID===c.HTML?(e._insertElement(t,ee.HTML),e.insertionMode=I.BEFORE_HEAD):cl(e,t)}function v8(e,t){let r=t.tagID;(r===c.HTML||r===c.HEAD||r===c.BODY||r===c.BR)&&cl(e,t)}function cl(e,t){e._insertFakeRootElement(),e.insertionMode=I.BEFORE_HEAD,e._processToken(t)}function T8(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.HEAD:{e._insertElement(t,ee.HTML),e.headElement=e.openElements.current,e.insertionMode=I.IN_HEAD;break}default:ll(e,t)}}function x8(e,t){let r=t.tagID;r===c.HEAD||r===c.BODY||r===c.HTML||r===c.BR?ll(e,t):e._err(t,Y.endTagWithoutMatchingOpenElement)}function ll(e,t){e._insertFakeElement(U.HEAD,c.HEAD),e.headElement=e.openElements.current,e.insertionMode=I.IN_HEAD,e._processToken(t)}function li(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.BASE:case c.BASEFONT:case c.BGSOUND:case c.LINK:case c.META:{e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case c.TITLE:{e._switchToTextParsing(t,Rr.RCDATA);break}case c.NOSCRIPT:{e.options.scriptingEnabled?e._switchToTextParsing(t,Rr.RAWTEXT):(e._insertElement(t,ee.HTML),e.insertionMode=I.IN_HEAD_NO_SCRIPT);break}case c.NOFRAMES:case c.STYLE:{e._switchToTextParsing(t,Rr.RAWTEXT);break}case c.SCRIPT:{e._switchToTextParsing(t,Rr.SCRIPT_DATA);break}case c.TEMPLATE:{e._insertTemplate(t),e.activeFormattingElements.insertMarker(),e.framesetOk=!1,e.insertionMode=I.IN_TEMPLATE,e.tmplInsertionModeStack.unshift(I.IN_TEMPLATE);break}case c.HEAD:{e._err(t,Y.misplacedStartTagForHeadElement);break}default:fl(e,t)}}function y8(e,t){switch(t.tagID){case c.HEAD:{e.openElements.pop(),e.insertionMode=I.AFTER_HEAD;break}case c.BODY:case c.BR:case c.HTML:{fl(e,t);break}case c.TEMPLATE:{Ys(e,t);break}default:e._err(t,Y.endTagWithoutMatchingOpenElement)}}function Ys(e,t){e.openElements.tmplCount>0?(e.openElements.generateImpliedEndTagsThoroughly(),e.openElements.currentTagId!==c.TEMPLATE&&e._err(t,Y.closingOfElementWithOpenChildElements),e.openElements.popUntilTagNamePopped(c.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode()):e._err(t,Y.endTagWithoutMatchingOpenElement)}function fl(e,t){e.openElements.pop(),e.insertionMode=I.AFTER_HEAD,e._processToken(t)}function A8(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.BASEFONT:case c.BGSOUND:case c.HEAD:case c.LINK:case c.META:case c.NOFRAMES:case c.STYLE:{li(e,t);break}case c.NOSCRIPT:{e._err(t,Y.nestedNoscriptInHead);break}default:dl(e,t)}}function w8(e,t){switch(t.tagID){case c.NOSCRIPT:{e.openElements.pop(),e.insertionMode=I.IN_HEAD;break}case c.BR:{dl(e,t);break}default:e._err(t,Y.endTagWithoutMatchingOpenElement)}}function dl(e,t){let r=t.type===Qe.EOF?Y.openElementsLeftAfterEof:Y.disallowedContentInNoscriptInHead;e._err(t,r),e.openElements.pop(),e.insertionMode=I.IN_HEAD,e._processToken(t)}function S8(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.BODY:{e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=I.IN_BODY;break}case c.FRAMESET:{e._insertElement(t,ee.HTML),e.insertionMode=I.IN_FRAMESET;break}case c.BASE:case c.BASEFONT:case c.BGSOUND:case c.LINK:case c.META:case c.NOFRAMES:case c.SCRIPT:case c.STYLE:case c.TEMPLATE:case c.TITLE:{e._err(t,Y.abandonedHeadElementChild),e.openElements.push(e.headElement,c.HEAD),li(e,t),e.openElements.remove(e.headElement);break}case c.HEAD:{e._err(t,Y.misplacedStartTagForHeadElement);break}default:hl(e,t)}}function C8(e,t){switch(t.tagID){case c.BODY:case c.HTML:case c.BR:{hl(e,t);break}case c.TEMPLATE:{Ys(e,t);break}default:e._err(t,Y.endTagWithoutMatchingOpenElement)}}function hl(e,t){e._insertFakeElement(U.BODY,c.BODY),e.insertionMode=I.IN_BODY,ph(e,t)}function ph(e,t){switch(t.type){case Qe.CHARACTER:{tS(e,t);break}case Qe.WHITESPACE_CHARACTER:{eS(e,t);break}case Qe.COMMENT:{Gg(e,t);break}case Qe.START_TAG:{Lr(e,t);break}case Qe.END_TAG:{mh(e,t);break}case Qe.EOF:{aS(e,t);break}default:}}function eS(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t)}function tS(e,t){e._reconstructActiveFormattingElements(),e._insertCharacters(t),e.framesetOk=!1}function I8(e,t){e.openElements.tmplCount===0&&e.treeAdapter.adoptAttributes(e.openElements.items[0],t.attrs)}function N8(e,t){let r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e.openElements.tmplCount===0&&(e.framesetOk=!1,e.treeAdapter.adoptAttributes(r,t.attrs))}function O8(e,t){let r=e.openElements.tryPeekProperlyNestedBodyElement();e.framesetOk&&r&&(e.treeAdapter.detachNode(r),e.openElements.popAllUpToHtmlElement(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_FRAMESET)}function D8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML)}function k8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),fu.has(e.openElements.currentTagId)&&e.openElements.pop(),e._insertElement(t,ee.HTML)}function R8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.skipNextNewLine=!0,e.framesetOk=!1}function L8(e,t){let r=e.openElements.tmplCount>0;(!e.formElement||r)&&(e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML),r||(e.formElement=e.openElements.current))}function P8(e,t){e.framesetOk=!1;let r=t.tagID;for(let n=e.openElements.stackTop;n>=0;n--){let i=e.openElements.tagIDs[n];if(r===c.LI&&i===c.LI||(r===c.DD||r===c.DT)&&(i===c.DD||i===c.DT)){e.openElements.generateImpliedEndTagsWithExclusion(i),e.openElements.popUntilTagNamePopped(i);break}if(i!==c.ADDRESS&&i!==c.DIV&&i!==c.P&&e._isSpecialElement(e.openElements.items[n],i))break}e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML)}function M8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.tokenizer.state=Rr.PLAINTEXT}function F8(e,t){e.openElements.hasInScope(c.BUTTON)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(c.BUTTON)),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.framesetOk=!1}function B8(e,t){let r=e.activeFormattingElements.getElementEntryInScopeWithTagName(U.A);r&&(Xg(e,t),e.openElements.remove(r.element),e.activeFormattingElements.removeEntry(r)),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function $8(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function H8(e,t){e._reconstructActiveFormattingElements(),e.openElements.hasInScope(c.NOBR)&&(Xg(e,t),e._reconstructActiveFormattingElements()),e._insertElement(t,ee.HTML),e.activeFormattingElements.pushElement(e.openElements.current,t)}function U8(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.activeFormattingElements.insertMarker(),e.framesetOk=!1}function V8(e,t){e.treeAdapter.getDocumentMode(e.document)!==kr.QUIRKS&&e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=I.IN_TABLE}function rS(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ee.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function nS(e){let t=rh(e,Oi.TYPE);return t!=null&&t.toLowerCase()===s8}function q8(e,t){e._reconstructActiveFormattingElements(),e._appendElement(t,ee.HTML),nS(t)||(e.framesetOk=!1),t.ackSelfClosing=!0}function z8(e,t){e._appendElement(t,ee.HTML),t.ackSelfClosing=!0}function Y8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._appendElement(t,ee.HTML),e.framesetOk=!1,t.ackSelfClosing=!0}function K8(e,t){t.tagName=U.IMG,t.tagID=c.IMG,rS(e,t)}function j8(e,t){e._insertElement(t,ee.HTML),e.skipNextNewLine=!0,e.tokenizer.state=Rr.RCDATA,e.originalInsertionMode=e.insertionMode,e.framesetOk=!1,e.insertionMode=I.TEXT}function W8(e,t){e.openElements.hasInButtonScope(c.P)&&e._closePElement(),e._reconstructActiveFormattingElements(),e.framesetOk=!1,e._switchToTextParsing(t,Rr.RAWTEXT)}function G8(e,t){e.framesetOk=!1,e._switchToTextParsing(t,Rr.RAWTEXT)}function Xw(e,t){e._switchToTextParsing(t,Rr.RAWTEXT)}function Q8(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML),e.framesetOk=!1,e.insertionMode=e.insertionMode===I.IN_TABLE||e.insertionMode===I.IN_CAPTION||e.insertionMode===I.IN_TABLE_BODY||e.insertionMode===I.IN_ROW||e.insertionMode===I.IN_CELL?I.IN_SELECT_IN_TABLE:I.IN_SELECT}function X8(e,t){e.openElements.currentTagId===c.OPTION&&e.openElements.pop(),e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML)}function Z8(e,t){e.openElements.hasInScope(c.RUBY)&&e.openElements.generateImpliedEndTags(),e._insertElement(t,ee.HTML)}function J8(e,t){e.openElements.hasInScope(c.RUBY)&&e.openElements.generateImpliedEndTagsWithExclusion(c.RTC),e._insertElement(t,ee.HTML)}function eM(e,t){e._reconstructActiveFormattingElements(),Yg(t),lh(t),t.selfClosing?e._appendElement(t,ee.MATHML):e._insertElement(t,ee.MATHML),t.ackSelfClosing=!0}function tM(e,t){e._reconstructActiveFormattingElements(),Kg(t),lh(t),t.selfClosing?e._appendElement(t,ee.SVG):e._insertElement(t,ee.SVG),t.ackSelfClosing=!0}function Zw(e,t){e._reconstructActiveFormattingElements(),e._insertElement(t,ee.HTML)}function Lr(e,t){switch(t.tagID){case c.I:case c.S:case c.B:case c.U:case c.EM:case c.TT:case c.BIG:case c.CODE:case c.FONT:case c.SMALL:case c.STRIKE:case c.STRONG:{$8(e,t);break}case c.A:{B8(e,t);break}case c.H1:case c.H2:case c.H3:case c.H4:case c.H5:case c.H6:{k8(e,t);break}case c.P:case c.DL:case c.OL:case c.UL:case c.DIV:case c.DIR:case c.NAV:case c.MAIN:case c.MENU:case c.ASIDE:case c.CENTER:case c.FIGURE:case c.FOOTER:case c.HEADER:case c.HGROUP:case c.DIALOG:case c.DETAILS:case c.ADDRESS:case c.ARTICLE:case c.SEARCH:case c.SECTION:case c.SUMMARY:case c.FIELDSET:case c.BLOCKQUOTE:case c.FIGCAPTION:{D8(e,t);break}case c.LI:case c.DD:case c.DT:{P8(e,t);break}case c.BR:case c.IMG:case c.WBR:case c.AREA:case c.EMBED:case c.KEYGEN:{rS(e,t);break}case c.HR:{Y8(e,t);break}case c.RB:case c.RTC:{Z8(e,t);break}case c.RT:case c.RP:{J8(e,t);break}case c.PRE:case c.LISTING:{R8(e,t);break}case c.XMP:{W8(e,t);break}case c.SVG:{tM(e,t);break}case c.HTML:{I8(e,t);break}case c.BASE:case c.LINK:case c.META:case c.STYLE:case c.TITLE:case c.SCRIPT:case c.BGSOUND:case c.BASEFONT:case c.TEMPLATE:{li(e,t);break}case c.BODY:{N8(e,t);break}case c.FORM:{L8(e,t);break}case c.NOBR:{H8(e,t);break}case c.MATH:{eM(e,t);break}case c.TABLE:{V8(e,t);break}case c.INPUT:{q8(e,t);break}case c.PARAM:case c.TRACK:case c.SOURCE:{z8(e,t);break}case c.IMAGE:{K8(e,t);break}case c.BUTTON:{F8(e,t);break}case c.APPLET:case c.OBJECT:case c.MARQUEE:{U8(e,t);break}case c.IFRAME:{G8(e,t);break}case c.SELECT:{Q8(e,t);break}case c.OPTION:case c.OPTGROUP:{X8(e,t);break}case c.NOEMBED:case c.NOFRAMES:{Xw(e,t);break}case c.FRAMESET:{O8(e,t);break}case c.TEXTAREA:{j8(e,t);break}case c.NOSCRIPT:{e.options.scriptingEnabled?Xw(e,t):Zw(e,t);break}case c.PLAINTEXT:{M8(e,t);break}case c.COL:case c.TH:case c.TD:case c.TR:case c.HEAD:case c.FRAME:case c.TBODY:case c.TFOOT:case c.THEAD:case c.CAPTION:case c.COLGROUP:break;default:Zw(e,t)}}function rM(e,t){if(e.openElements.hasInScope(c.BODY)&&(e.insertionMode=I.AFTER_BODY,e.options.sourceCodeLocationInfo)){let r=e.openElements.tryPeekProperlyNestedBodyElement();r&&e._setEndLocation(r,t)}}function nM(e,t){e.openElements.hasInScope(c.BODY)&&(e.insertionMode=I.AFTER_BODY,hS(e,t))}function iM(e,t){let r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r))}function aM(e){let t=e.openElements.tmplCount>0,{formElement:r}=e;t||(e.formElement=null),(r||t)&&e.openElements.hasInScope(c.FORM)&&(e.openElements.generateImpliedEndTags(),t?e.openElements.popUntilTagNamePopped(c.FORM):r&&e.openElements.remove(r))}function sM(e){e.openElements.hasInButtonScope(c.P)||e._insertFakeElement(U.P,c.P),e._closePElement()}function oM(e){e.openElements.hasInListItemScope(c.LI)&&(e.openElements.generateImpliedEndTagsWithExclusion(c.LI),e.openElements.popUntilTagNamePopped(c.LI))}function uM(e,t){let r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTagsWithExclusion(r),e.openElements.popUntilTagNamePopped(r))}function cM(e){e.openElements.hasNumberedHeaderInScope()&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilNumberedHeaderPopped())}function lM(e,t){let r=t.tagID;e.openElements.hasInScope(r)&&(e.openElements.generateImpliedEndTags(),e.openElements.popUntilTagNamePopped(r),e.activeFormattingElements.clearToLastMarker())}function fM(e){e._reconstructActiveFormattingElements(),e._insertFakeElement(U.BR,c.BR),e.openElements.pop(),e.framesetOk=!1}function iS(e,t){let r=t.tagName,n=t.tagID;for(let i=e.openElements.stackTop;i>0;i--){let a=e.openElements.items[i],o=e.openElements.tagIDs[i];if(n===o&&(n!==c.UNKNOWN||e.treeAdapter.getTagName(a)===r)){e.openElements.generateImpliedEndTagsWithExclusion(n),e.openElements.stackTop>=i&&e.openElements.shortenToLength(i);break}if(e._isSpecialElement(a,o))break}}function mh(e,t){switch(t.tagID){case c.A:case c.B:case c.I:case c.S:case c.U:case c.EM:case c.TT:case c.BIG:case c.CODE:case c.FONT:case c.NOBR:case c.SMALL:case c.STRIKE:case c.STRONG:{Xg(e,t);break}case c.P:{sM(e);break}case c.DL:case c.UL:case c.OL:case c.DIR:case c.DIV:case c.NAV:case c.PRE:case c.MAIN:case c.MENU:case c.ASIDE:case c.BUTTON:case c.CENTER:case c.FIGURE:case c.FOOTER:case c.HEADER:case c.HGROUP:case c.DIALOG:case c.ADDRESS:case c.ARTICLE:case c.DETAILS:case c.SEARCH:case c.SECTION:case c.SUMMARY:case c.LISTING:case c.FIELDSET:case c.BLOCKQUOTE:case c.FIGCAPTION:{iM(e,t);break}case c.LI:{oM(e);break}case c.DD:case c.DT:{uM(e,t);break}case c.H1:case c.H2:case c.H3:case c.H4:case c.H5:case c.H6:{cM(e);break}case c.BR:{fM(e);break}case c.BODY:{rM(e,t);break}case c.HTML:{nM(e,t);break}case c.FORM:{aM(e);break}case c.APPLET:case c.OBJECT:case c.MARQUEE:{lM(e,t);break}case c.TEMPLATE:{Ys(e,t);break}default:iS(e,t)}}function aS(e,t){e.tmplInsertionModeStack.length>0?dS(e,t):Zg(e,t)}function dM(e,t){var r;t.tagID===c.SCRIPT&&((r=e.scriptHandler)===null||r===void 0||r.call(e,e.openElements.current)),e.openElements.pop(),e.insertionMode=e.originalInsertionMode}function hM(e,t){e._err(t,Y.eofInElementThatCanContainOnlyText),e.openElements.pop(),e.insertionMode=e.originalInsertionMode,e.onEof(t)}function Wg(e,t){if(Jw.has(e.openElements.currentTagId))switch(e.pendingCharacterTokens.length=0,e.hasNonWhitespacePendingCharacterToken=!1,e.originalInsertionMode=e.insertionMode,e.insertionMode=I.IN_TABLE_TEXT,t.type){case Qe.CHARACTER:{oS(e,t);break}case Qe.WHITESPACE_CHARACTER:{sS(e,t);break}}else ml(e,t)}function pM(e,t){e.openElements.clearBackToTableContext(),e.activeFormattingElements.insertMarker(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_CAPTION}function mM(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_COLUMN_GROUP}function gM(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(U.COLGROUP,c.COLGROUP),e.insertionMode=I.IN_COLUMN_GROUP,Jg(e,t)}function _M(e,t){e.openElements.clearBackToTableContext(),e._insertElement(t,ee.HTML),e.insertionMode=I.IN_TABLE_BODY}function bM(e,t){e.openElements.clearBackToTableContext(),e._insertFakeElement(U.TBODY,c.TBODY),e.insertionMode=I.IN_TABLE_BODY,gh(e,t)}function EM(e,t){e.openElements.hasInTableScope(c.TABLE)&&(e.openElements.popUntilTagNamePopped(c.TABLE),e._resetInsertionMode(),e._processStartTag(t))}function vM(e,t){nS(t)?e._appendElement(t,ee.HTML):ml(e,t),t.ackSelfClosing=!0}function TM(e,t){!e.formElement&&e.openElements.tmplCount===0&&(e._insertElement(t,ee.HTML),e.formElement=e.openElements.current,e.openElements.pop())}function hu(e,t){switch(t.tagID){case c.TD:case c.TH:case c.TR:{bM(e,t);break}case c.STYLE:case c.SCRIPT:case c.TEMPLATE:{li(e,t);break}case c.COL:{gM(e,t);break}case c.FORM:{TM(e,t);break}case c.TABLE:{EM(e,t);break}case c.TBODY:case c.TFOOT:case c.THEAD:{_M(e,t);break}case c.INPUT:{vM(e,t);break}case c.CAPTION:{pM(e,t);break}case c.COLGROUP:{mM(e,t);break}default:ml(e,t)}}function pl(e,t){switch(t.tagID){case c.TABLE:{e.openElements.hasInTableScope(c.TABLE)&&(e.openElements.popUntilTagNamePopped(c.TABLE),e._resetInsertionMode());break}case c.TEMPLATE:{Ys(e,t);break}case c.BODY:case c.CAPTION:case c.COL:case c.COLGROUP:case c.HTML:case c.TBODY:case c.TD:case c.TFOOT:case c.TH:case c.THEAD:case c.TR:break;default:ml(e,t)}}function ml(e,t){let r=e.fosterParentingEnabled;e.fosterParentingEnabled=!0,ph(e,t),e.fosterParentingEnabled=r}function sS(e,t){e.pendingCharacterTokens.push(t)}function oS(e,t){e.pendingCharacterTokens.push(t),e.hasNonWhitespacePendingCharacterToken=!0}function ul(e,t){let r=0;if(e.hasNonWhitespacePendingCharacterToken)for(;r0&&e.openElements.currentTagId===c.OPTION&&e.openElements.tagIDs[e.openElements.stackTop-1]===c.OPTGROUP&&e.openElements.pop(),e.openElements.currentTagId===c.OPTGROUP&&e.openElements.pop();break}case c.OPTION:{e.openElements.currentTagId===c.OPTION&&e.openElements.pop();break}case c.SELECT:{e.openElements.hasInSelectScope(c.SELECT)&&(e.openElements.popUntilTagNamePopped(c.SELECT),e._resetInsertionMode());break}case c.TEMPLATE:{Ys(e,t);break}default:}}function CM(e,t){let r=t.tagID;r===c.CAPTION||r===c.TABLE||r===c.TBODY||r===c.TFOOT||r===c.THEAD||r===c.TR||r===c.TD||r===c.TH?(e.openElements.popUntilTagNamePopped(c.SELECT),e._resetInsertionMode(),e._processStartTag(t)):lS(e,t)}function IM(e,t){let r=t.tagID;r===c.CAPTION||r===c.TABLE||r===c.TBODY||r===c.TFOOT||r===c.THEAD||r===c.TR||r===c.TD||r===c.TH?e.openElements.hasInTableScope(r)&&(e.openElements.popUntilTagNamePopped(c.SELECT),e._resetInsertionMode(),e.onEndTag(t)):fS(e,t)}function NM(e,t){switch(t.tagID){case c.BASE:case c.BASEFONT:case c.BGSOUND:case c.LINK:case c.META:case c.NOFRAMES:case c.SCRIPT:case c.STYLE:case c.TEMPLATE:case c.TITLE:{li(e,t);break}case c.CAPTION:case c.COLGROUP:case c.TBODY:case c.TFOOT:case c.THEAD:{e.tmplInsertionModeStack[0]=I.IN_TABLE,e.insertionMode=I.IN_TABLE,hu(e,t);break}case c.COL:{e.tmplInsertionModeStack[0]=I.IN_COLUMN_GROUP,e.insertionMode=I.IN_COLUMN_GROUP,Jg(e,t);break}case c.TR:{e.tmplInsertionModeStack[0]=I.IN_TABLE_BODY,e.insertionMode=I.IN_TABLE_BODY,gh(e,t);break}case c.TD:case c.TH:{e.tmplInsertionModeStack[0]=I.IN_ROW,e.insertionMode=I.IN_ROW,_h(e,t);break}default:e.tmplInsertionModeStack[0]=I.IN_BODY,e.insertionMode=I.IN_BODY,Lr(e,t)}}function OM(e,t){t.tagID===c.TEMPLATE&&Ys(e,t)}function dS(e,t){e.openElements.tmplCount>0?(e.openElements.popUntilTagNamePopped(c.TEMPLATE),e.activeFormattingElements.clearToLastMarker(),e.tmplInsertionModeStack.shift(),e._resetInsertionMode(),e.onEof(t)):Zg(e,t)}function DM(e,t){t.tagID===c.HTML?Lr(e,t):hh(e,t)}function hS(e,t){var r;if(t.tagID===c.HTML){if(e.fragmentContext||(e.insertionMode=I.AFTER_AFTER_BODY),e.options.sourceCodeLocationInfo&&e.openElements.tagIDs[0]===c.HTML){e._setEndLocation(e.openElements.items[0],t);let n=e.openElements.items[1];n&&!(!((r=e.treeAdapter.getNodeSourceCodeLocation(n))===null||r===void 0)&&r.endTag)&&e._setEndLocation(n,t)}}else hh(e,t)}function hh(e,t){e.insertionMode=I.IN_BODY,ph(e,t)}function kM(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.FRAMESET:{e._insertElement(t,ee.HTML);break}case c.FRAME:{e._appendElement(t,ee.HTML),t.ackSelfClosing=!0;break}case c.NOFRAMES:{li(e,t);break}default:}}function RM(e,t){t.tagID===c.FRAMESET&&!e.openElements.isRootHtmlElementCurrent()&&(e.openElements.pop(),!e.fragmentContext&&e.openElements.currentTagId!==c.FRAMESET&&(e.insertionMode=I.AFTER_FRAMESET))}function LM(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.NOFRAMES:{li(e,t);break}default:}}function PM(e,t){t.tagID===c.HTML&&(e.insertionMode=I.AFTER_AFTER_FRAMESET)}function MM(e,t){t.tagID===c.HTML?Lr(e,t):fh(e,t)}function fh(e,t){e.insertionMode=I.IN_BODY,ph(e,t)}function FM(e,t){switch(t.tagID){case c.HTML:{Lr(e,t);break}case c.NOFRAMES:{li(e,t);break}default:}}function BM(e,t){t.chars=xt,e._insertCharacters(t)}function $M(e,t){e._insertCharacters(t),e.framesetOk=!1}function pS(e){for(;e.treeAdapter.getNamespaceURI(e.openElements.current)!==ee.HTML&&!e._isIntegrationPoint(e.openElements.currentTagId,e.openElements.current);)e.openElements.pop()}function HM(e,t){if(Kw(t))pS(e),e._startTagOutsideForeignContent(t);else{let r=e._getAdjustedCurrentElement(),n=e.treeAdapter.getNamespaceURI(r);n===ee.MATHML?Yg(t):n===ee.SVG&&(jw(t),Kg(t)),lh(t),t.selfClosing?e._appendElement(t,n):e._insertElement(t,n),t.ackSelfClosing=!0}}function UM(e,t){if(t.tagID===c.P||t.tagID===c.BR){pS(e),e._endTagOutsideForeignContent(t);return}for(let r=e.openElements.stackTop;r>0;r--){let n=e.openElements.items[r];if(e.treeAdapter.getNamespaceURI(n)===ee.HTML){e._endTagOutsideForeignContent(t);break}let i=e.treeAdapter.getTagName(n);if(i.toLowerCase()===t.tagName){t.tagName=i,e.openElements.shortenToLength(r);break}}}var s8,o8,u8,I,c8,Jw,Qw,du,uS,e_=v(()=>{zg();Pw();Fw();ch();zw();jg();il();eh();sa();nh();s8="hidden",o8=8,u8=3;(function(e){e[e.INITIAL=0]="INITIAL",e[e.BEFORE_HTML=1]="BEFORE_HTML",e[e.BEFORE_HEAD=2]="BEFORE_HEAD",e[e.IN_HEAD=3]="IN_HEAD",e[e.IN_HEAD_NO_SCRIPT=4]="IN_HEAD_NO_SCRIPT",e[e.AFTER_HEAD=5]="AFTER_HEAD",e[e.IN_BODY=6]="IN_BODY",e[e.TEXT=7]="TEXT",e[e.IN_TABLE=8]="IN_TABLE",e[e.IN_TABLE_TEXT=9]="IN_TABLE_TEXT",e[e.IN_CAPTION=10]="IN_CAPTION",e[e.IN_COLUMN_GROUP=11]="IN_COLUMN_GROUP",e[e.IN_TABLE_BODY=12]="IN_TABLE_BODY",e[e.IN_ROW=13]="IN_ROW",e[e.IN_CELL=14]="IN_CELL",e[e.IN_SELECT=15]="IN_SELECT",e[e.IN_SELECT_IN_TABLE=16]="IN_SELECT_IN_TABLE",e[e.IN_TEMPLATE=17]="IN_TEMPLATE",e[e.AFTER_BODY=18]="AFTER_BODY",e[e.IN_FRAMESET=19]="IN_FRAMESET",e[e.AFTER_FRAMESET=20]="AFTER_FRAMESET",e[e.AFTER_AFTER_BODY=21]="AFTER_AFTER_BODY",e[e.AFTER_AFTER_FRAMESET=22]="AFTER_AFTER_FRAMESET"})(I||(I={}));c8={startLine:-1,startCol:-1,startOffset:-1,endLine:-1,endCol:-1,endOffset:-1},Jw=new Set([c.TABLE,c.TBODY,c.TFOOT,c.THEAD,c.TR]),Qw={scriptingEnabled:!0,sourceCodeLocationInfo:!1,treeAdapter:Vn,onParseError:null},du=class{constructor(t,r,n=null,i=null){this.fragmentContext=n,this.scriptHandler=i,this.currentToken=null,this.stopped=!1,this.insertionMode=I.INITIAL,this.originalInsertionMode=I.INITIAL,this.headElement=null,this.formElement=null,this.currentNotInHTML=!1,this.tmplInsertionModeStack=[],this.pendingCharacterTokens=[],this.hasNonWhitespacePendingCharacterToken=!1,this.framesetOk=!0,this.skipNextNewLine=!1,this.fosterParentingEnabled=!1,this.options={...Qw,...t},this.treeAdapter=this.options.treeAdapter,this.onParseError=this.options.onParseError,this.onParseError&&(this.options.sourceCodeLocationInfo=!0),this.document=r??this.treeAdapter.createDocument(),this.tokenizer=new sl(this.options,this),this.activeFormattingElements=new uh(this.treeAdapter),this.fragmentContextID=n?Wa(this.treeAdapter.getTagName(n)):c.UNKNOWN,this._setContextModes(n??this.document,this.fragmentContextID),this.openElements=new oh(this.document,this.treeAdapter,this)}static parse(t,r){let n=new this(r);return n.tokenizer.write(t,!0),n.document}static getFragmentParser(t,r){let n={...Qw,...r};t??(t=n.treeAdapter.createElement(U.TEMPLATE,ee.HTML,[]));let i=n.treeAdapter.createElement("documentmock",ee.HTML,[]),a=new this(n,i,t);return a.fragmentContextID===c.TEMPLATE&&a.tmplInsertionModeStack.unshift(I.IN_TEMPLATE),a._initTokenizerForFragmentParsing(),a._insertFakeRootElement(),a._resetInsertionMode(),a._findFormInFragmentContext(),a}getFragment(){let t=this.treeAdapter.getFirstChild(this.document),r=this.treeAdapter.createDocumentFragment();return this._adoptNodes(t,r),r}_err(t,r,n){var i;if(!this.onParseError)return;let a=(i=t.location)!==null&&i!==void 0?i:c8,o={code:r,startLine:a.startLine,startCol:a.startCol,startOffset:a.startOffset,endLine:n?a.startLine:a.endLine,endCol:n?a.startCol:a.endCol,endOffset:n?a.startOffset:a.endOffset};this.onParseError(o)}onItemPush(t,r,n){var i,a;(a=(i=this.treeAdapter).onItemPush)===null||a===void 0||a.call(i,t),n&&this.openElements.stackTop>0&&this._setContextModes(t,r)}onItemPop(t,r){var n,i;if(this.options.sourceCodeLocationInfo&&this._setEndLocation(t,this.currentToken),(i=(n=this.treeAdapter).onItemPop)===null||i===void 0||i.call(n,t,this.openElements.current),r){let a,o;this.openElements.stackTop===0&&this.fragmentContext?(a=this.fragmentContext,o=this.fragmentContextID):{current:a,currentTagId:o}=this.openElements,this._setContextModes(a,o)}}_setContextModes(t,r){let n=t===this.document||this.treeAdapter.getNamespaceURI(t)===ee.HTML;this.currentNotInHTML=!n,this.tokenizer.inForeignNode=!n&&!this._isIntegrationPoint(r,t)}_switchToTextParsing(t,r){this._insertElement(t,ee.HTML),this.tokenizer.state=r,this.originalInsertionMode=this.insertionMode,this.insertionMode=I.TEXT}switchToPlaintextParsing(){this.insertionMode=I.TEXT,this.originalInsertionMode=I.IN_BODY,this.tokenizer.state=Rr.PLAINTEXT}_getAdjustedCurrentElement(){return this.openElements.stackTop===0&&this.fragmentContext?this.fragmentContext:this.openElements.current}_findFormInFragmentContext(){let t=this.fragmentContext;for(;t;){if(this.treeAdapter.getTagName(t)===U.FORM){this.formElement=t;break}t=this.treeAdapter.getParentNode(t)}}_initTokenizerForFragmentParsing(){if(!(!this.fragmentContext||this.treeAdapter.getNamespaceURI(this.fragmentContext)!==ee.HTML))switch(this.fragmentContextID){case c.TITLE:case c.TEXTAREA:{this.tokenizer.state=Rr.RCDATA;break}case c.STYLE:case c.XMP:case c.IFRAME:case c.NOEMBED:case c.NOFRAMES:case c.NOSCRIPT:{this.tokenizer.state=Rr.RAWTEXT;break}case c.SCRIPT:{this.tokenizer.state=Rr.SCRIPT_DATA;break}case c.PLAINTEXT:{this.tokenizer.state=Rr.PLAINTEXT;break}default:}}_setDocumentType(t){let r=t.name||"",n=t.publicId||"",i=t.systemId||"";if(this.treeAdapter.setDocumentType(this.document,r,n,i),t.location){let o=this.treeAdapter.getChildNodes(this.document).find(l=>this.treeAdapter.isDocumentTypeNode(l));o&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}}_attachElementToTree(t,r){if(this.options.sourceCodeLocationInfo){let n=r&&{...r,startTag:r};this.treeAdapter.setNodeSourceCodeLocation(t,n)}if(this._shouldFosterParentOnInsertion())this._fosterParentElement(t);else{let n=this.openElements.currentTmplContentOrNode;this.treeAdapter.appendChild(n,t)}}_appendElement(t,r){let n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location)}_insertElement(t,r){let n=this.treeAdapter.createElement(t.tagName,r,t.attrs);this._attachElementToTree(n,t.location),this.openElements.push(n,t.tagID)}_insertFakeElement(t,r){let n=this.treeAdapter.createElement(t,ee.HTML,[]);this._attachElementToTree(n,null),this.openElements.push(n,r)}_insertTemplate(t){let r=this.treeAdapter.createElement(t.tagName,ee.HTML,t.attrs),n=this.treeAdapter.createDocumentFragment();this.treeAdapter.setTemplateContent(r,n),this._attachElementToTree(r,t.location),this.openElements.push(r,t.tagID),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,null)}_insertFakeRootElement(){let t=this.treeAdapter.createElement(U.HTML,ee.HTML,[]);this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(t,null),this.treeAdapter.appendChild(this.openElements.current,t),this.openElements.push(t,c.HTML)}_appendCommentNode(t,r){let n=this.treeAdapter.createCommentNode(t.data);this.treeAdapter.appendChild(r,n),this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(n,t.location)}_insertCharacters(t){let r,n;if(this._shouldFosterParentOnInsertion()?({parent:r,beforeElement:n}=this._findFosterParentingLocation(),n?this.treeAdapter.insertTextBefore(r,t.chars,n):this.treeAdapter.insertText(r,t.chars)):(r=this.openElements.currentTmplContentOrNode,this.treeAdapter.insertText(r,t.chars)),!t.location)return;let i=this.treeAdapter.getChildNodes(r),a=n?i.lastIndexOf(n):i.length,o=i[a-1];if(this.treeAdapter.getNodeSourceCodeLocation(o)){let{endLine:d,endCol:p,endOffset:g}=t.location;this.treeAdapter.updateNodeSourceCodeLocation(o,{endLine:d,endCol:p,endOffset:g})}else this.options.sourceCodeLocationInfo&&this.treeAdapter.setNodeSourceCodeLocation(o,t.location)}_adoptNodes(t,r){for(let n=this.treeAdapter.getFirstChild(t);n;n=this.treeAdapter.getFirstChild(t))this.treeAdapter.detachNode(n),this.treeAdapter.appendChild(r,n)}_setEndLocation(t,r){if(this.treeAdapter.getNodeSourceCodeLocation(t)&&r.location){let n=r.location,i=this.treeAdapter.getTagName(t),a=r.type===Qe.END_TAG&&i===r.tagName?{endTag:{...n},endLine:n.endLine,endCol:n.endCol,endOffset:n.endOffset}:{endLine:n.startLine,endCol:n.startCol,endOffset:n.startOffset};this.treeAdapter.updateNodeSourceCodeLocation(t,a)}}shouldProcessStartTagTokenInForeignContent(t){if(!this.currentNotInHTML)return!1;let r,n;return this.openElements.stackTop===0&&this.fragmentContext?(r=this.fragmentContext,n=this.fragmentContextID):{current:r,currentTagId:n}=this.openElements,t.tagID===c.SVG&&this.treeAdapter.getTagName(r)===U.ANNOTATION_XML&&this.treeAdapter.getNamespaceURI(r)===ee.MATHML?!1:this.tokenizer.inForeignNode||(t.tagID===c.MGLYPH||t.tagID===c.MALIGNMARK)&&!this._isIntegrationPoint(n,r,ee.HTML)}_processToken(t){switch(t.type){case Qe.CHARACTER:{this.onCharacter(t);break}case Qe.NULL_CHARACTER:{this.onNullCharacter(t);break}case Qe.COMMENT:{this.onComment(t);break}case Qe.DOCTYPE:{this.onDoctype(t);break}case Qe.START_TAG:{this._processStartTag(t);break}case Qe.END_TAG:{this.onEndTag(t);break}case Qe.EOF:{this.onEof(t);break}case Qe.WHITESPACE_CHARACTER:{this.onWhitespaceCharacter(t);break}}}_isIntegrationPoint(t,r,n){let i=this.treeAdapter.getNamespaceURI(r),a=this.treeAdapter.getAttrList(r);return Ww(t,i,a,n)}_reconstructActiveFormattingElements(){let t=this.activeFormattingElements.entries.length;if(t){let r=this.activeFormattingElements.entries.findIndex(i=>i.type===ci.Marker||this.openElements.contains(i.element)),n=r<0?t-1:r-1;for(let i=n;i>=0;i--){let a=this.activeFormattingElements.entries[i];this._insertElement(a.token,this.treeAdapter.getNamespaceURI(a.element)),a.element=this.openElements.current}}}_closeTableCell(){this.openElements.generateImpliedEndTags(),this.openElements.popUntilTableCellPopped(),this.activeFormattingElements.clearToLastMarker(),this.insertionMode=I.IN_ROW}_closePElement(){this.openElements.generateImpliedEndTagsWithExclusion(c.P),this.openElements.popUntilTagNamePopped(c.P)}_resetInsertionMode(){for(let t=this.openElements.stackTop;t>=0;t--)switch(t===0&&this.fragmentContext?this.fragmentContextID:this.openElements.tagIDs[t]){case c.TR:{this.insertionMode=I.IN_ROW;return}case c.TBODY:case c.THEAD:case c.TFOOT:{this.insertionMode=I.IN_TABLE_BODY;return}case c.CAPTION:{this.insertionMode=I.IN_CAPTION;return}case c.COLGROUP:{this.insertionMode=I.IN_COLUMN_GROUP;return}case c.TABLE:{this.insertionMode=I.IN_TABLE;return}case c.BODY:{this.insertionMode=I.IN_BODY;return}case c.FRAMESET:{this.insertionMode=I.IN_FRAMESET;return}case c.SELECT:{this._resetInsertionModeForSelect(t);return}case c.TEMPLATE:{this.insertionMode=this.tmplInsertionModeStack[0];return}case c.HTML:{this.insertionMode=this.headElement?I.AFTER_HEAD:I.BEFORE_HEAD;return}case c.TD:case c.TH:{if(t>0){this.insertionMode=I.IN_CELL;return}break}case c.HEAD:{if(t>0){this.insertionMode=I.IN_HEAD;return}break}}this.insertionMode=I.IN_BODY}_resetInsertionModeForSelect(t){if(t>0)for(let r=t-1;r>0;r--){let n=this.openElements.tagIDs[r];if(n===c.TEMPLATE)break;if(n===c.TABLE){this.insertionMode=I.IN_SELECT_IN_TABLE;return}}this.insertionMode=I.IN_SELECT}_isElementCausesFosterParenting(t){return Jw.has(t)}_shouldFosterParentOnInsertion(){return this.fosterParentingEnabled&&this._isElementCausesFosterParenting(this.openElements.currentTagId)}_findFosterParentingLocation(){for(let t=this.openElements.stackTop;t>=0;t--){let r=this.openElements.items[t];switch(this.openElements.tagIDs[t]){case c.TEMPLATE:{if(this.treeAdapter.getNamespaceURI(r)===ee.HTML)return{parent:this.treeAdapter.getTemplateContent(r),beforeElement:null};break}case c.TABLE:{let n=this.treeAdapter.getParentNode(r);return n?{parent:n,beforeElement:r}:{parent:this.openElements.items[t-1],beforeElement:null}}default:}}return{parent:this.openElements.items[0],beforeElement:null}}_fosterParentElement(t){let r=this._findFosterParentingLocation();r.beforeElement?this.treeAdapter.insertBefore(r.parent,t,r.beforeElement):this.treeAdapter.appendChild(r.parent,t)}_isSpecialElement(t,r){let n=this.treeAdapter.getNamespaceURI(t);return Vg[n].has(r)}onCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){$M(this,t);return}switch(this.insertionMode){case I.INITIAL:{ol(this,t);break}case I.BEFORE_HTML:{cl(this,t);break}case I.BEFORE_HEAD:{ll(this,t);break}case I.IN_HEAD:{fl(this,t);break}case I.IN_HEAD_NO_SCRIPT:{dl(this,t);break}case I.AFTER_HEAD:{hl(this,t);break}case I.IN_BODY:case I.IN_CAPTION:case I.IN_CELL:case I.IN_TEMPLATE:{tS(this,t);break}case I.TEXT:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:{this._insertCharacters(t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{Wg(this,t);break}case I.IN_TABLE_TEXT:{oS(this,t);break}case I.IN_COLUMN_GROUP:{dh(this,t);break}case I.AFTER_BODY:{hh(this,t);break}case I.AFTER_AFTER_BODY:{fh(this,t);break}default:}}onNullCharacter(t){if(this.skipNextNewLine=!1,this.tokenizer.inForeignNode){BM(this,t);return}switch(this.insertionMode){case I.INITIAL:{ol(this,t);break}case I.BEFORE_HTML:{cl(this,t);break}case I.BEFORE_HEAD:{ll(this,t);break}case I.IN_HEAD:{fl(this,t);break}case I.IN_HEAD_NO_SCRIPT:{dl(this,t);break}case I.AFTER_HEAD:{hl(this,t);break}case I.TEXT:{this._insertCharacters(t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{Wg(this,t);break}case I.IN_COLUMN_GROUP:{dh(this,t);break}case I.AFTER_BODY:{hh(this,t);break}case I.AFTER_AFTER_BODY:{fh(this,t);break}default:}}onComment(t){if(this.skipNextNewLine=!1,this.currentNotInHTML){Gg(this,t);return}switch(this.insertionMode){case I.INITIAL:case I.BEFORE_HTML:case I.BEFORE_HEAD:case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:case I.IN_BODY:case I.IN_TABLE:case I.IN_CAPTION:case I.IN_COLUMN_GROUP:case I.IN_TABLE_BODY:case I.IN_ROW:case I.IN_CELL:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:case I.IN_TEMPLATE:case I.IN_FRAMESET:case I.AFTER_FRAMESET:{Gg(this,t);break}case I.IN_TABLE_TEXT:{ul(this,t);break}case I.AFTER_BODY:{g8(this,t);break}case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{_8(this,t);break}default:}}onDoctype(t){switch(this.skipNextNewLine=!1,this.insertionMode){case I.INITIAL:{b8(this,t);break}case I.BEFORE_HEAD:case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:{this._err(t,Y.misplacedDoctype);break}case I.IN_TABLE_TEXT:{ul(this,t);break}default:}}onStartTag(t){this.skipNextNewLine=!1,this.currentToken=t,this._processStartTag(t),t.selfClosing&&!t.ackSelfClosing&&this._err(t,Y.nonVoidHtmlElementStartTagWithTrailingSolidus)}_processStartTag(t){this.shouldProcessStartTagTokenInForeignContent(t)?HM(this,t):this._startTagOutsideForeignContent(t)}_startTagOutsideForeignContent(t){switch(this.insertionMode){case I.INITIAL:{ol(this,t);break}case I.BEFORE_HTML:{E8(this,t);break}case I.BEFORE_HEAD:{T8(this,t);break}case I.IN_HEAD:{li(this,t);break}case I.IN_HEAD_NO_SCRIPT:{A8(this,t);break}case I.AFTER_HEAD:{S8(this,t);break}case I.IN_BODY:{Lr(this,t);break}case I.IN_TABLE:{hu(this,t);break}case I.IN_TABLE_TEXT:{ul(this,t);break}case I.IN_CAPTION:{xM(this,t);break}case I.IN_COLUMN_GROUP:{Jg(this,t);break}case I.IN_TABLE_BODY:{gh(this,t);break}case I.IN_ROW:{_h(this,t);break}case I.IN_CELL:{wM(this,t);break}case I.IN_SELECT:{lS(this,t);break}case I.IN_SELECT_IN_TABLE:{CM(this,t);break}case I.IN_TEMPLATE:{NM(this,t);break}case I.AFTER_BODY:{DM(this,t);break}case I.IN_FRAMESET:{kM(this,t);break}case I.AFTER_FRAMESET:{LM(this,t);break}case I.AFTER_AFTER_BODY:{MM(this,t);break}case I.AFTER_AFTER_FRAMESET:{FM(this,t);break}default:}}onEndTag(t){this.skipNextNewLine=!1,this.currentToken=t,this.currentNotInHTML?UM(this,t):this._endTagOutsideForeignContent(t)}_endTagOutsideForeignContent(t){switch(this.insertionMode){case I.INITIAL:{ol(this,t);break}case I.BEFORE_HTML:{v8(this,t);break}case I.BEFORE_HEAD:{x8(this,t);break}case I.IN_HEAD:{y8(this,t);break}case I.IN_HEAD_NO_SCRIPT:{w8(this,t);break}case I.AFTER_HEAD:{C8(this,t);break}case I.IN_BODY:{mh(this,t);break}case I.TEXT:{dM(this,t);break}case I.IN_TABLE:{pl(this,t);break}case I.IN_TABLE_TEXT:{ul(this,t);break}case I.IN_CAPTION:{yM(this,t);break}case I.IN_COLUMN_GROUP:{AM(this,t);break}case I.IN_TABLE_BODY:{Qg(this,t);break}case I.IN_ROW:{cS(this,t);break}case I.IN_CELL:{SM(this,t);break}case I.IN_SELECT:{fS(this,t);break}case I.IN_SELECT_IN_TABLE:{IM(this,t);break}case I.IN_TEMPLATE:{OM(this,t);break}case I.AFTER_BODY:{hS(this,t);break}case I.IN_FRAMESET:{RM(this,t);break}case I.AFTER_FRAMESET:{PM(this,t);break}case I.AFTER_AFTER_BODY:{fh(this,t);break}default:}}onEof(t){switch(this.insertionMode){case I.INITIAL:{ol(this,t);break}case I.BEFORE_HTML:{cl(this,t);break}case I.BEFORE_HEAD:{ll(this,t);break}case I.IN_HEAD:{fl(this,t);break}case I.IN_HEAD_NO_SCRIPT:{dl(this,t);break}case I.AFTER_HEAD:{hl(this,t);break}case I.IN_BODY:case I.IN_TABLE:case I.IN_CAPTION:case I.IN_COLUMN_GROUP:case I.IN_TABLE_BODY:case I.IN_ROW:case I.IN_CELL:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:{aS(this,t);break}case I.TEXT:{hM(this,t);break}case I.IN_TABLE_TEXT:{ul(this,t);break}case I.IN_TEMPLATE:{dS(this,t);break}case I.AFTER_BODY:case I.IN_FRAMESET:case I.AFTER_FRAMESET:case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{Zg(this,t);break}default:}}onWhitespaceCharacter(t){if(this.skipNextNewLine&&(this.skipNextNewLine=!1,t.chars.charCodeAt(0)===x.LINE_FEED)){if(t.chars.length===1)return;t.chars=t.chars.substr(1)}if(this.tokenizer.inForeignNode){this._insertCharacters(t);return}switch(this.insertionMode){case I.IN_HEAD:case I.IN_HEAD_NO_SCRIPT:case I.AFTER_HEAD:case I.TEXT:case I.IN_COLUMN_GROUP:case I.IN_SELECT:case I.IN_SELECT_IN_TABLE:case I.IN_FRAMESET:case I.AFTER_FRAMESET:{this._insertCharacters(t);break}case I.IN_BODY:case I.IN_CAPTION:case I.IN_CELL:case I.IN_TEMPLATE:case I.AFTER_BODY:case I.AFTER_AFTER_BODY:case I.AFTER_AFTER_FRAMESET:{eS(this,t);break}case I.IN_TABLE:case I.IN_TABLE_BODY:case I.IN_ROW:{Wg(this,t);break}case I.IN_TABLE_TEXT:{sS(this,t);break}default:}}};uS=new Set([c.CAPTION,c.COL,c.COLGROUP,c.TBODY,c.TD,c.TFOOT,c.TH,c.THEAD,c.TR])});function qM(e,t){return t.treeAdapter.isElementNode(e)&&t.treeAdapter.getNamespaceURI(e)===ee.HTML&&VM.has(t.treeAdapter.getTagName(e))}function t_(e,t){let r={...zM,...t};return mS(e,r)}function YM(e,t){let r="",n=t.treeAdapter.isElementNode(e)&&t.treeAdapter.getTagName(e)===U.TEMPLATE&&t.treeAdapter.getNamespaceURI(e)===ee.HTML?t.treeAdapter.getTemplateContent(e):e,i=t.treeAdapter.getChildNodes(n);if(i)for(let a of i)r+=mS(a,t);return r}function mS(e,t){return t.treeAdapter.isElementNode(e)?KM(e,t):t.treeAdapter.isTextNode(e)?WM(e,t):t.treeAdapter.isCommentNode(e)?GM(e,t):t.treeAdapter.isDocumentTypeNode(e)?QM(e,t):""}function KM(e,t){let r=t.treeAdapter.getTagName(e);return`<${r}${jM(e,t)}>${qM(e,t)?"":`${YM(e,t)}`}`}function jM(e,{treeAdapter:t}){let r="";for(let n of t.getAttrList(e)){if(r+=" ",n.namespace)switch(n.namespace){case ee.XML:{r+=`xml:${n.name}`;break}case ee.XMLNS:{n.name!=="xmlns"&&(r+="xmlns:"),r+=n.name;break}case ee.XLINK:{r+=`xlink:${n.name}`;break}default:r+=`${n.prefix}:${n.name}`}else r+=n.name;r+=`="${Jo(n.value)}"`}return r}function WM(e,t){let{treeAdapter:r}=t,n=r.getTextNodeContent(e),i=r.getParentNode(e),a=i&&r.isElementNode(i)&&r.getTagName(i);return a&&r.getNamespaceURI(i)===ee.HTML&&qg(a,t.scriptingEnabled)?n:eu(n)}function GM(e,{treeAdapter:t}){return``}function QM(e,{treeAdapter:t}){return``}var VM,zM,gS=v(()=>{sa();Yc();ch();VM=new Set([U.AREA,U.BASE,U.BASEFONT,U.BGSOUND,U.BR,U.COL,U.EMBED,U.FRAME,U.HR,U.IMG,U.INPUT,U.KEYGEN,U.LINK,U.META,U.PARAM,U.SOURCE,U.TRACK,U.WBR]);zM={treeAdapter:Vn,scriptingEnabled:!0}});function _S(e,t){return du.parse(e,t)}function bS(e,t,r){typeof e=="string"&&(r=t,t=e,e=null);let n=du.getFragmentParser(e,r);return n.tokenizer.write(t,!0),n.getFragment()}var r_=v(()=>{e_();ch();e_();gS();il();jg();sa();nh();zg()});function ES(e){let t=e.includes('"')?"'":'"';return t+e+t}function XM(e,t,r){let n="!DOCTYPE ";return e&&(n+=e),t?n+=` PUBLIC ${ES(t)}`:r&&(n+=" SYSTEM"),r&&(n+=` ${ES(r)}`),n}var oa,vS=v(()=>{r_();_r();oa={isCommentNode:$s,isElementNode:_e,isTextNode:nn,createDocument(){let e=new wn([]);return e["x-mode"]=ih.DOCUMENT_MODE.NO_QUIRKS,e},createDocumentFragment(){return new wn([])},createElement(e,t,r){let n=Object.create(null),i=Object.create(null),a=Object.create(null);for(let l=0;lCd(o)&&o.name==="!doctype");a?a.data=i??null:(a=new Fs("!doctype",i),oa.appendChild(e,a)),a["x-name"]=t,a["x-publicId"]=r,a["x-systemId"]=n},setDocumentMode(e,t){e["x-mode"]=t},getDocumentMode(e){return e["x-mode"]},detachNode(e){if(e.parent){let t=e.parent.children.indexOf(e),{prev:r,next:n}=e;e.prev=null,e.next=null,r&&(r.next=n),n&&(n.prev=r),e.parent.children.splice(t,1),e.parent=null}},insertText(e,t){let r=e.children[e.children.length-1];r&&nn(r)?r.data+=t:oa.appendChild(e,oa.createTextNode(t))},insertTextBefore(e,t,r){let n=e.children[e.children.indexOf(r)-1];n&&nn(n)?n.data+=t:oa.insertBefore(e,oa.createTextNode(t),r)},adoptAttributes(e,t){for(let r=0;r{_r();r_();vS();ZM={treeAdapter:oa}});function ua(e){return e===Ie.Space||e===Ie.NewLine||e===Ie.Tab||e===Ie.FormFeed||e===Ie.CarriageReturn}function bh(e){return e===Ie.Slash||e===Ie.Gt||ua(e)}function JM(e){return e>=Ie.LowerA&&e<=Ie.LowerZ||e>=Ie.UpperA&&e<=Ie.UpperZ}var Ie,ne,qn,br,pu,n_=v(()=>{Zo();(function(e){e[e.Tab=9]="Tab",e[e.NewLine=10]="NewLine",e[e.FormFeed=12]="FormFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.Number=35]="Number",e[e.Amp=38]="Amp",e[e.SingleQuote=39]="SingleQuote",e[e.DoubleQuote=34]="DoubleQuote",e[e.Dash=45]="Dash",e[e.Slash=47]="Slash",e[e.Zero=48]="Zero",e[e.Nine=57]="Nine",e[e.Semi=59]="Semi",e[e.Lt=60]="Lt",e[e.Eq=61]="Eq",e[e.Gt=62]="Gt",e[e.Questionmark=63]="Questionmark",e[e.UpperA=65]="UpperA",e[e.LowerA=97]="LowerA",e[e.UpperF=70]="UpperF",e[e.LowerF=102]="LowerF",e[e.UpperZ=90]="UpperZ",e[e.LowerZ=122]="LowerZ",e[e.LowerX=120]="LowerX",e[e.OpeningSquareBracket=91]="OpeningSquareBracket"})(Ie||(Ie={}));(function(e){e[e.Text=1]="Text",e[e.BeforeTagName=2]="BeforeTagName",e[e.InTagName=3]="InTagName",e[e.InSelfClosingTag=4]="InSelfClosingTag",e[e.BeforeClosingTagName=5]="BeforeClosingTagName",e[e.InClosingTagName=6]="InClosingTagName",e[e.AfterClosingTagName=7]="AfterClosingTagName",e[e.BeforeAttributeName=8]="BeforeAttributeName",e[e.InAttributeName=9]="InAttributeName",e[e.AfterAttributeName=10]="AfterAttributeName",e[e.BeforeAttributeValue=11]="BeforeAttributeValue",e[e.InAttributeValueDq=12]="InAttributeValueDq",e[e.InAttributeValueSq=13]="InAttributeValueSq",e[e.InAttributeValueNq=14]="InAttributeValueNq",e[e.BeforeDeclaration=15]="BeforeDeclaration",e[e.InDeclaration=16]="InDeclaration",e[e.InProcessingInstruction=17]="InProcessingInstruction",e[e.BeforeComment=18]="BeforeComment",e[e.CDATASequence=19]="CDATASequence",e[e.InSpecialComment=20]="InSpecialComment",e[e.InCommentLike=21]="InCommentLike",e[e.BeforeSpecialS=22]="BeforeSpecialS",e[e.BeforeSpecialT=23]="BeforeSpecialT",e[e.SpecialStartSequence=24]="SpecialStartSequence",e[e.InSpecialTag=25]="InSpecialTag",e[e.InEntity=26]="InEntity"})(ne||(ne={}));(function(e){e[e.NoValue=0]="NoValue",e[e.Unquoted=1]="Unquoted",e[e.Single=2]="Single",e[e.Double=3]="Double"})(qn||(qn={}));br={Cdata:new Uint8Array([67,68,65,84,65,91]),CdataEnd:new Uint8Array([93,93,62]),CommentEnd:new Uint8Array([45,45,62]),ScriptEnd:new Uint8Array([60,47,115,99,114,105,112,116]),StyleEnd:new Uint8Array([60,47,115,116,121,108,101]),TitleEnd:new Uint8Array([60,47,116,105,116,108,101]),TextareaEnd:new Uint8Array([60,47,116,101,120,116,97,114,101,97])},pu=class{constructor({xmlMode:t=!1,decodeEntities:r=!0},n){this.cbs=n,this.state=ne.Text,this.buffer="",this.sectionStart=0,this.index=0,this.entityStart=0,this.baseState=ne.Text,this.isSpecial=!1,this.running=!0,this.offset=0,this.currentSequence=void 0,this.sequenceIndex=0,this.xmlMode=t,this.decodeEntities=r,this.entityDecoder=new Ha(t?Id:Qo,(i,a)=>this.emitCodePoint(i,a))}reset(){this.state=ne.Text,this.buffer="",this.sectionStart=0,this.index=0,this.baseState=ne.Text,this.currentSequence=void 0,this.running=!0,this.offset=0}write(t){this.offset+=this.buffer.length,this.buffer=t,this.parse()}end(){this.running&&this.finish()}pause(){this.running=!1}resume(){this.running=!0,this.indexthis.sectionStart&&this.cbs.ontext(this.sectionStart,this.index),this.state=ne.BeforeTagName,this.sectionStart=this.index):this.decodeEntities&&t===Ie.Amp&&this.startEntity()}stateSpecialStartSequence(t){let r=this.sequenceIndex===this.currentSequence.length;if(!(r?bh(t):(t|32)===this.currentSequence[this.sequenceIndex]))this.isSpecial=!1;else if(!r){this.sequenceIndex++;return}this.sequenceIndex=0,this.state=ne.InTagName,this.stateInTagName(t)}stateInSpecialTag(t){if(this.sequenceIndex===this.currentSequence.length){if(t===Ie.Gt||ua(t)){let r=this.index-this.currentSequence.length;if(this.sectionStart=0?(this.state=this.baseState,t===0&&(this.index=this.entityStart)):this.index=this.offset+this.buffer.length-1}cleanup(){this.running&&this.sectionStart!==this.index&&(this.state===ne.Text||this.state===ne.InSpecialTag&&this.sequenceIndex===0?(this.cbs.ontext(this.sectionStart,this.index),this.sectionStart=this.index):(this.state===ne.InAttributeValueDq||this.state===ne.InAttributeValueSq||this.state===ne.InAttributeValueNq)&&(this.cbs.onattribdata(this.sectionStart,this.index),this.sectionStart=this.index))}shouldContinue(){return this.index=t||(this.state===ne.InCommentLike?this.currentSequence===br.CdataEnd?this.cbs.oncdata(this.sectionStart,t,0):this.cbs.oncomment(this.sectionStart,t,0):this.state===ne.InTagName||this.state===ne.BeforeAttributeName||this.state===ne.BeforeAttributeValue||this.state===ne.AfterAttributeName||this.state===ne.InAttributeName||this.state===ne.InAttributeValueSq||this.state===ne.InAttributeValueDq||this.state===ne.InAttributeValueNq||this.state===ne.InClosingTagName||this.cbs.ontext(this.sectionStart,t))}emitCodePoint(t,r){this.baseState!==ne.Text&&this.baseState!==ne.InSpecialTag?(this.sectionStart{n_();Zo();mu=new Set(["input","option","optgroup","select","button","datalist","textarea"]),pt=new Set(["p"]),AS=new Set(["thead","tbody"]),wS=new Set(["dd","dt"]),SS=new Set(["rt","rp"]),eF=new Map([["tr",new Set(["tr","th","td"])],["th",new Set(["th"])],["td",new Set(["thead","th","td"])],["body",new Set(["head","link","script"])],["li",new Set(["li"])],["p",pt],["h1",pt],["h2",pt],["h3",pt],["h4",pt],["h5",pt],["h6",pt],["select",mu],["input",mu],["output",mu],["button",mu],["datalist",mu],["textarea",mu],["option",new Set(["option"])],["optgroup",new Set(["optgroup","option"])],["dd",wS],["dt",wS],["address",pt],["article",pt],["aside",pt],["blockquote",pt],["details",pt],["div",pt],["dl",pt],["fieldset",pt],["figcaption",pt],["figure",pt],["footer",pt],["form",pt],["header",pt],["hr",pt],["main",pt],["nav",pt],["ol",pt],["pre",pt],["section",pt],["table",pt],["ul",pt],["rt",SS],["rp",SS],["tbody",AS],["tfoot",AS]]),tF=new Set(["area","base","basefont","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr"]),CS=new Set(["math","svg"]),IS=new Set(["mi","mo","mn","ms","mtext","annotation-xml","foreignobject","desc","title"]),rF=/\s|\//,gl=class{constructor(t,r={}){var n,i,a,o,l,d;this.options=r,this.startIndex=0,this.endIndex=0,this.openTagStart=0,this.tagname="",this.attribname="",this.attribvalue="",this.attribs=null,this.stack=[],this.buffers=[],this.bufferOffset=0,this.writeIndex=0,this.ended=!1,this.cbs=t??{},this.htmlMode=!this.options.xmlMode,this.lowerCaseTagNames=(n=r.lowerCaseTags)!==null&&n!==void 0?n:this.htmlMode,this.lowerCaseAttributeNames=(i=r.lowerCaseAttributeNames)!==null&&i!==void 0?i:this.htmlMode,this.recognizeSelfClosing=(a=r.recognizeSelfClosing)!==null&&a!==void 0?a:!this.htmlMode,this.tokenizer=new((o=r.Tokenizer)!==null&&o!==void 0?o:pu)(this.options,this),this.foreignContext=[!this.htmlMode],(d=(l=this.cbs).onparserinit)===null||d===void 0||d.call(l,this)}ontext(t,r){var n,i;let a=this.getSlice(t,r);this.endIndex=r-1,(i=(n=this.cbs).ontext)===null||i===void 0||i.call(n,a),this.startIndex=r}ontextentity(t,r){var n,i;this.endIndex=r-1,(i=(n=this.cbs).ontext)===null||i===void 0||i.call(n,Xo(t)),this.startIndex=r}isVoidElement(t){return this.htmlMode&&tF.has(t)}onopentagname(t,r){this.endIndex=r;let n=this.getSlice(t,r);this.lowerCaseTagNames&&(n=n.toLowerCase()),this.emitOpenTag(n)}emitOpenTag(t){var r,n,i,a;this.openTagStart=this.startIndex,this.tagname=t;let o=this.htmlMode&&eF.get(t);if(o)for(;this.stack.length>0&&o.has(this.stack[0]);){let l=this.stack.shift();(n=(r=this.cbs).onclosetag)===null||n===void 0||n.call(r,l,!0)}this.isVoidElement(t)||(this.stack.unshift(t),this.htmlMode&&(CS.has(t)?this.foreignContext.unshift(!0):IS.has(t)&&this.foreignContext.unshift(!1))),(a=(i=this.cbs).onopentagname)===null||a===void 0||a.call(i,t),this.cbs.onopentag&&(this.attribs={})}endOpenTag(t){var r,n;this.startIndex=this.openTagStart,this.attribs&&((n=(r=this.cbs).onopentag)===null||n===void 0||n.call(r,this.tagname,this.attribs,t),this.attribs=null),this.cbs.onclosetag&&this.isVoidElement(this.tagname)&&this.cbs.onclosetag(this.tagname,!0),this.tagname=""}onopentagend(t){this.endIndex=t,this.endOpenTag(!1),this.startIndex=t+1}onclosetag(t,r){var n,i,a,o,l,d,p,g;this.endIndex=r;let E=this.getSlice(t,r);if(this.lowerCaseTagNames&&(E=E.toLowerCase()),this.htmlMode&&(CS.has(E)||IS.has(E))&&this.foreignContext.shift(),this.isVoidElement(E))this.htmlMode&&E==="br"&&((o=(a=this.cbs).onopentagname)===null||o===void 0||o.call(a,"br"),(d=(l=this.cbs).onopentag)===null||d===void 0||d.call(l,"br",{},!0),(g=(p=this.cbs).onclosetag)===null||g===void 0||g.call(p,"br",!1));else{let _=this.stack.indexOf(E);if(_!==-1)for(let y=0;y<=_;y++){let C=this.stack.shift();(i=(n=this.cbs).onclosetag)===null||i===void 0||i.call(n,C,y!==_)}else this.htmlMode&&E==="p"&&(this.emitOpenTag("p"),this.closeCurrentTag(!0))}this.startIndex=r+1}onselfclosingtag(t){this.endIndex=t,this.recognizeSelfClosing||this.foreignContext[0]?(this.closeCurrentTag(!1),this.startIndex=t+1):this.onopentagend(t)}closeCurrentTag(t){var r,n;let i=this.tagname;this.endOpenTag(t),this.stack[0]===i&&((n=(r=this.cbs).onclosetag)===null||n===void 0||n.call(r,i,!t),this.stack.shift())}onattribname(t,r){this.startIndex=t;let n=this.getSlice(t,r);this.attribname=this.lowerCaseAttributeNames?n.toLowerCase():n}onattribdata(t,r){this.attribvalue+=this.getSlice(t,r)}onattribentity(t){this.attribvalue+=Xo(t)}onattribend(t,r){var n,i;this.endIndex=r,(i=(n=this.cbs).onattribute)===null||i===void 0||i.call(n,this.attribname,this.attribvalue,t===qn.Double?'"':t===qn.Single?"'":t===qn.NoValue?void 0:null),this.attribs&&!Object.prototype.hasOwnProperty.call(this.attribs,this.attribname)&&(this.attribs[this.attribname]=this.attribvalue),this.attribvalue=""}getInstructionName(t){let r=t.search(rF),n=r<0?t:t.substr(0,r);return this.lowerCaseTagNames&&(n=n.toLowerCase()),n}ondeclaration(t,r){this.endIndex=r;let n=this.getSlice(t,r);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(n);this.cbs.onprocessinginstruction(`!${i}`,`!${n}`)}this.startIndex=r+1}onprocessinginstruction(t,r){this.endIndex=r;let n=this.getSlice(t,r);if(this.cbs.onprocessinginstruction){let i=this.getInstructionName(n);this.cbs.onprocessinginstruction(`?${i}`,`?${n}`)}this.startIndex=r+1}oncomment(t,r,n){var i,a,o,l;this.endIndex=r,(a=(i=this.cbs).oncomment)===null||a===void 0||a.call(i,this.getSlice(t,r-n)),(l=(o=this.cbs).oncommentend)===null||l===void 0||l.call(o),this.startIndex=r+1}oncdata(t,r,n){var i,a,o,l,d,p,g,E,_,y;this.endIndex=r;let C=this.getSlice(t,r-n);!this.htmlMode||this.options.recognizeCDATA?((a=(i=this.cbs).oncdatastart)===null||a===void 0||a.call(i),(l=(o=this.cbs).ontext)===null||l===void 0||l.call(o,C),(p=(d=this.cbs).oncdataend)===null||p===void 0||p.call(d)):((E=(g=this.cbs).oncomment)===null||E===void 0||E.call(g,`[CDATA[${C}]]`),(y=(_=this.cbs).oncommentend)===null||y===void 0||y.call(_)),this.startIndex=r+1}onend(){var t,r;if(this.cbs.onclosetag){this.endIndex=this.startIndex;for(let n=0;n=this.buffers[0].length;)this.shiftBuffer();let n=this.buffers[0].slice(t-this.bufferOffset,r-this.bufferOffset);for(;r-this.bufferOffset>this.buffers[0].length;)this.shiftBuffer(),n+=this.buffers[0].slice(0,r-this.bufferOffset);return n}shiftBuffer(){this.bufferOffset+=this.buffers[0].length,this.writeIndex--,this.buffers.shift()}write(t){var r,n;if(this.ended){(n=(r=this.cbs).onerror)===null||n===void 0||n.call(r,new Error(".write() after done!"));return}this.buffers.push(t),this.tokenizer.running&&(this.tokenizer.write(t),this.writeIndex++)}end(t){var r,n;if(this.ended){(n=(r=this.cbs).onerror)===null||n===void 0||n.call(r,new Error(".end() after done!"));return}t&&this.write(t),this.ended=!0,this.tokenizer.end()}pause(){this.tokenizer.pause()}resume(){for(this.tokenizer.resume();this.tokenizer.running&&this.writeIndex{i_();i_();_r();_r();n_();Ko();ui();ui();ui()});var nF,iF,DS=v(()=>{Aw();Fg();yS();G0();OS();nF=fw((e,t,r,n)=>t._useHtmlParser2?NS(e,t):TS(e,t,r,n)),iF=yw(nF,(e,t)=>t._useHtmlParser2?Od(e,t):xS(e))});var kS={};Nn(kS,{contains:()=>Wc,load:()=>iF,merge:()=>ng});var RS=v(()=>{nu();DS()});var PS=Pi((ose,LS)=>{"use strict";var aF=(RS(),B_(kS));function sF(e){let t=aF.load(e),r=[];return[{tagName:"a",attr:"href"},{tagName:"area",attr:"href"},{tagName:"link",attr:"href"},{tagName:"audio",attr:"src"},{tagName:"embed",attr:"src"},{tagName:"iframe",attr:"src"},{tagName:"input",attr:"src"},{tagName:"img",attr:"src"},{tagName:"javascript",attr:"src"},{tagName:"source",attr:"src"},{tagName:"track",attr:"src"},{tagName:"video",attr:"src"}].forEach(({tagName:n,attr:i})=>{t(n).each((a,o)=>{t(o).attr(i)&&r.push(t(o).attr(i))})}),r}LS.exports=sF});var BS=Pi((use,FS)=>{"use strict";var{marked:MS}=DA(),oF=PS();FS.exports=function(t,r=!1){MS.setOptions({mangle:!1});let n=MS(t);return oF(n)}});var zS={};Nn(zS,{default:()=>uF,getServer:()=>qS});function qS(e){let t=_0(e),r=US.createServer(async function(n,i){i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE"),i.setHeader("Access-Control-Allow-Headers","Access-Control-Allow-Headers, Origin, Authorization,Accept,x-client-id, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, hypothesis-client-version"),i.setHeader("Access-Control-Allow-Credentials","true");try{if(n.url){let a=VS.parse(n.url,!0);if(a.pathname==="/search"){let o=a.query.q,l=await t.search(o);i.statusCode=200,i.setHeader("Content-Type","application/json"),i.end(JSON.stringify(l))}else i.end()}}catch(a){i.statusCode=500,i.end(a)}});return{listen(n){console.debug(`Omnisearch - Starting HTTP server on port ${n}`),r.listen({port:parseInt(n),host:e.settings.DANGER_httpHost??"localhost"},()=>{console.log(`Omnisearch - Started HTTP server on port ${n}`),e.settings.DANGER_httpHost&&e.settings.DANGER_httpHost!=="localhost"?new _l.Notice(`Omnisearch - Started non-localhost HTTP server at ${e.settings.DANGER_httpHost}:${n}`,12e4):e.settings.httpApiNotice&&new _l.Notice(`Omnisearch - Started HTTP server on port ${n}`)}),r.on("error",i=>{console.error(i),new _l.Notice(`Omnisearch - Cannot start HTTP server on ${n}. See console for more details.`)})},close(){r.close(),console.log("Omnisearch - Terminated HTTP server"),e.settings.httpApiEnabled&&e.settings.httpApiNotice&&new _l.Notice("Omnisearch - Terminated HTTP server")}}}var US,VS,_l,uF,YS=v(()=>{US=ln(require("http")),VS=ln(require("url")),_l=require("obsidian");b0();uF=qS});var lF={};Nn(lF,{default:()=>Ch});module.exports=B_(lF);var zn=require("obsidian");Lc();Ao();mr();mr();mr();en();b0();var pd=ln(rA(),1),nA=Symbol.for("Dexie"),md=globalThis[nA]||(globalThis[nA]=pd.default);if(pd.default.semVer!==md.semVer)throw new Error(`Two different versions of Dexie loaded in the same app: ${pd.default.semVer} and ${md.semVer}`);var{liveQuery:ere,mergeRanges:tre,rangesOverlap:rre,RangeSet:nre,cmp:ire,Entity:are,PropModification:sre,replacePrefix:ore,add:ure,remove:cre}=md;var iA=md;var T0=require("obsidian"),qo=class extends iA{constructor(r){super(qo.getDbName(r.app.appId));this.plugin=r;this.version(qo.dbVersion).stores({searchHistory:"++id",minisearch:"date",embeds:"embedded"})}static getDbName(r){return"omnisearch/cache/"+r}async getMinisearchCache(){try{return(await this.plugin.database.minisearch.toArray())[0]}catch(r){return new T0.Notice("Omnisearch - Cache missing or invalid. Some freezes may occur while Omnisearch indexes your vault."),console.error("Omnisearch - Error while loading Minisearch cache"),console.error(r),null}}async writeMinisearchCache(){let r=this.plugin.searchEngine.getSerializedMiniSearch(),n=this.plugin.searchEngine.getSerializedIndexedDocuments(),i=this.plugin.database;await i.minisearch.clear(),await i.minisearch.add({date:new Date().toISOString(),paths:n,data:r}),console.debug("Omnisearch - Search cache written")}async clearOldDatabases(){let r=(await indexedDB.databases()).filter(n=>n.name===qo.getDbName(this.plugin.app.appId)&&n.version!==qo.dbVersion*10);if(r.length){console.debug("Omnisearch - Those IndexedDb databases will be deleted:");for(let n of r)n.name&&indexedDB.deleteDatabase(n.name)}}async clearCache(){await this.minisearch.clear(),await this.embeds.clear(),new T0.Notice("Omnisearch - Cache cleared. Please restart Obsidian.")}},Pc=qo;Pc.dbVersion=10;function bd(e,t,r,n){function i(a){return a instanceof r?a:new r(function(o){o(a)})}return new(r||(r=Promise))(function(a,o){function l(g){try{p(n.next(g))}catch(E){o(E)}}function d(g){try{p(n.throw(g))}catch(E){o(E)}}function p(g){g.done?a(g.value):i(g.value).then(l,d)}p((n=n.apply(e,t||[])).next())})}var Z6="ENTRIES",cA="KEYS",lA="VALUES",gr="",Mc=class{constructor(t,r){let n=t._tree,i=Array.from(n.keys());this.set=t,this._type=r,this._path=i.length>0?[{node:n,keys:i}]:[]}next(){let t=this.dive();return this.backtrack(),t}dive(){if(this._path.length===0)return{done:!0,value:void 0};let{node:t,keys:r}=zo(this._path);if(zo(r)===gr)return{done:!1,value:this.result()};let n=t.get(zo(r));return this._path.push({node:n,keys:Array.from(n.keys())}),this.dive()}backtrack(){if(this._path.length===0)return;let t=zo(this._path).keys;t.pop(),!(t.length>0)&&(this._path.pop(),this.backtrack())}key(){return this.set._prefix+this._path.map(({keys:t})=>zo(t)).filter(t=>t!==gr).join("")}value(){return zo(this._path).node.get(gr)}result(){switch(this._type){case lA:return this.value();case cA:return this.key();default:return[this.key(),this.value()]}}[Symbol.iterator](){return this}},zo=e=>e[e.length-1],J6=(e,t,r)=>{let n=new Map;if(t===void 0)return n;let i=t.length+1,a=i+r,o=new Uint8Array(a*i).fill(r+1);for(let l=0;l{let d=a*o;e:for(let p of e.keys())if(p===gr){let g=i[d-1];g<=r&&n.set(l,[e.get(p),g])}else{let g=a;for(let E=0;Er)continue e}fA(e.get(p),t,r,n,i,g,o,l+p)}},Ci=class{constructor(t=new Map,r=""){this._size=void 0,this._tree=t,this._prefix=r}atPrefix(t){if(!t.startsWith(this._prefix))throw new Error("Mismatched prefix");let[r,n]=Ed(this._tree,t.slice(this._prefix.length));if(r===void 0){let[i,a]=N0(n);for(let o of i.keys())if(o!==gr&&o.startsWith(a)){let l=new Map;return l.set(o.slice(a.length),i.get(o)),new Ci(l,t)}}return new Ci(r,t)}clear(){this._size=void 0,this._tree.clear()}delete(t){return this._size=void 0,eR(this._tree,t)}entries(){return new Mc(this,Z6)}forEach(t){for(let[r,n]of this)t(r,n,this)}fuzzyGet(t,r){return J6(this._tree,t,r)}get(t){let r=S0(this._tree,t);return r!==void 0?r.get(gr):void 0}has(t){let r=S0(this._tree,t);return r!==void 0&&r.has(gr)}keys(){return new Mc(this,cA)}set(t,r){if(typeof t!="string")throw new Error("key must be a string");return this._size=void 0,x0(this._tree,t).set(gr,r),this}get size(){if(this._size)return this._size;this._size=0;let t=this.entries();for(;!t.next().done;)this._size+=1;return this._size}update(t,r){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;let n=x0(this._tree,t);return n.set(gr,r(n.get(gr))),this}fetch(t,r){if(typeof t!="string")throw new Error("key must be a string");this._size=void 0;let n=x0(this._tree,t),i=n.get(gr);return i===void 0&&n.set(gr,i=r()),i}values(){return new Mc(this,lA)}[Symbol.iterator](){return this.entries()}static from(t){let r=new Ci;for(let[n,i]of t)r.set(n,i);return r}static fromObject(t){return Ci.from(Object.entries(t))}},Ed=(e,t,r=[])=>{if(t.length===0||e==null)return[e,r];for(let n of e.keys())if(n!==gr&&t.startsWith(n))return r.push([e,n]),Ed(e.get(n),t.slice(n.length),r);return r.push([e,t]),Ed(void 0,"",r)},S0=(e,t)=>{if(t.length===0||e==null)return e;for(let r of e.keys())if(r!==gr&&t.startsWith(r))return S0(e.get(r),t.slice(r.length))},x0=(e,t)=>{let r=t.length;e:for(let n=0;e&&n{let[r,n]=Ed(e,t);if(r!==void 0){if(r.delete(gr),r.size===0)dA(n);else if(r.size===1){let[i,a]=r.entries().next().value;hA(n,i,a)}}},dA=e=>{if(e.length===0)return;let[t,r]=N0(e);if(t.delete(r),t.size===0)dA(e.slice(0,-1));else if(t.size===1){let[n,i]=t.entries().next().value;n!==gr&&hA(e.slice(0,-1),n,i)}},hA=(e,t,r)=>{if(e.length===0)return;let[n,i]=N0(e);n.set(i+t,r),n.delete(i)},N0=e=>e[e.length-1],O0="or",pA="and",tR="and_not",Ii=class{constructor(t){if(t?.fields==null)throw new Error('MiniSearch: option "fields" must be provided');let r=t.autoVacuum==null||t.autoVacuum===!0?w0:t.autoVacuum;this._options=Object.assign(Object.assign(Object.assign({},A0),t),{autoVacuum:r,searchOptions:Object.assign(Object.assign({},aA),t.searchOptions||{}),autoSuggestOptions:Object.assign(Object.assign({},sR),t.autoSuggestOptions||{})}),this._index=new Ci,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldIds={},this._fieldLength=new Map,this._avgFieldLength=[],this._nextId=0,this._storedFields=new Map,this._dirtCount=0,this._currentVacuum=null,this._enqueuedVacuum=null,this._enqueuedVacuumConditions=I0,this.addFields(this._options.fields)}add(t){let{extractField:r,tokenize:n,processTerm:i,fields:a,idField:o}=this._options,l=r(t,o);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${o}"`);if(this._idToShortId.has(l))throw new Error(`MiniSearch: duplicate ID ${l}`);let d=this.addDocumentId(l);this.saveStoredFields(d,t);for(let p of a){let g=r(t,p);if(g==null)continue;let E=n(g.toString(),p),_=this._fieldIds[p],y=new Set(E).size;this.addFieldLength(d,_,this._documentCount-1,y);for(let C of E){let k=i(C,p);if(Array.isArray(k))for(let P of k)this.addTerm(_,d,P);else k&&this.addTerm(_,d,k)}}}addAll(t){for(let r of t)this.add(r)}addAllAsync(t,r={}){let{chunkSize:n=10}=r,i={chunk:[],promise:Promise.resolve()},{chunk:a,promise:o}=t.reduce(({chunk:l,promise:d},p,g)=>(l.push(p),(g+1)%n===0?{chunk:[],promise:d.then(()=>new Promise(E=>setTimeout(E,0))).then(()=>this.addAll(l))}:{chunk:l,promise:d}),i);return o.then(()=>this.addAll(a))}remove(t){let{tokenize:r,processTerm:n,extractField:i,fields:a,idField:o}=this._options,l=i(t,o);if(l==null)throw new Error(`MiniSearch: document does not have ID field "${o}"`);let d=this._idToShortId.get(l);if(d==null)throw new Error(`MiniSearch: cannot remove document with ID ${l}: it is not in the index`);for(let p of a){let g=i(t,p);if(g==null)continue;let E=r(g.toString(),p),_=this._fieldIds[p],y=new Set(E).size;this.removeFieldLength(d,_,this._documentCount,y);for(let C of E){let k=n(C,p);if(Array.isArray(k))for(let P of k)this.removeTerm(_,d,P);else k&&this.removeTerm(_,d,k)}}this._storedFields.delete(d),this._documentIds.delete(d),this._idToShortId.delete(l),this._fieldLength.delete(d),this._documentCount-=1}removeAll(t){if(t)for(let r of t)this.remove(r);else{if(arguments.length>0)throw new Error("Expected documents to be present. Omit the argument to remove all documents.");this._index=new Ci,this._documentCount=0,this._documentIds=new Map,this._idToShortId=new Map,this._fieldLength=new Map,this._avgFieldLength=[],this._storedFields=new Map,this._nextId=0}}discard(t){let r=this._idToShortId.get(t);if(r==null)throw new Error(`MiniSearch: cannot discard document with ID ${t}: it is not in the index`);this._idToShortId.delete(t),this._documentIds.delete(r),this._storedFields.delete(r),(this._fieldLength.get(r)||[]).forEach((n,i)=>{this.removeFieldLength(r,i,this._documentCount,n)}),this._fieldLength.delete(r),this._documentCount-=1,this._dirtCount+=1,this.maybeAutoVacuum()}maybeAutoVacuum(){if(this._options.autoVacuum===!1)return;let{minDirtFactor:t,minDirtCount:r,batchSize:n,batchWait:i}=this._options.autoVacuum;this.conditionalVacuum({batchSize:n,batchWait:i},{minDirtCount:r,minDirtFactor:t})}discardAll(t){let r=this._options.autoVacuum;try{this._options.autoVacuum=!1;for(let n of t)this.discard(n)}finally{this._options.autoVacuum=r}this.maybeAutoVacuum()}replace(t){let{idField:r,extractField:n}=this._options,i=n(t,r);this.discard(i),this.add(t)}vacuum(t={}){return this.conditionalVacuum(t)}conditionalVacuum(t,r){return this._currentVacuum?(this._enqueuedVacuumConditions=this._enqueuedVacuumConditions&&r,this._enqueuedVacuum!=null?this._enqueuedVacuum:(this._enqueuedVacuum=this._currentVacuum.then(()=>{let n=this._enqueuedVacuumConditions;return this._enqueuedVacuumConditions=I0,this.performVacuuming(t,n)}),this._enqueuedVacuum)):this.vacuumConditionsMet(r)===!1?Promise.resolve():(this._currentVacuum=this.performVacuuming(t),this._currentVacuum)}performVacuuming(t,r){return bd(this,void 0,void 0,function*(){let n=this._dirtCount;if(this.vacuumConditionsMet(r)){let i=t.batchSize||C0.batchSize,a=t.batchWait||C0.batchWait,o=1;for(let[l,d]of this._index){for(let[p,g]of d)for(let[E]of g)this._documentIds.has(E)||(g.size<=1?d.delete(p):g.delete(E));this._index.get(l).size===0&&this._index.delete(l),o%i===0&&(yield new Promise(p=>setTimeout(p,a))),o+=1}this._dirtCount-=n}yield null,this._currentVacuum=this._enqueuedVacuum,this._enqueuedVacuum=null})}vacuumConditionsMet(t){if(t==null)return!0;let{minDirtCount:r,minDirtFactor:n}=t;return r=r||w0.minDirtCount,n=n||w0.minDirtFactor,this.dirtCount>=r&&this.dirtFactor>=n}get isVacuuming(){return this._currentVacuum!=null}get dirtCount(){return this._dirtCount}get dirtFactor(){return this._dirtCount/(1+this._documentCount+this._dirtCount)}has(t){return this._idToShortId.has(t)}getStoredFields(t){let r=this._idToShortId.get(t);if(r!=null)return this._storedFields.get(r)}search(t,r={}){let n=this.executeQuery(t,r),i=[];for(let[a,{score:o,terms:l,match:d}]of n){let p=l.length||1,g={id:this._documentIds.get(a),score:o*p,terms:Object.keys(d),queryTerms:l,match:d};Object.assign(g,this._storedFields.get(a)),(r.filter==null||r.filter(g))&&i.push(g)}return t===Ii.wildcard&&r.boostDocument==null&&this._options.searchOptions.boostDocument==null||i.sort(oA),i}autoSuggest(t,r={}){r=Object.assign(Object.assign({},this._options.autoSuggestOptions),r);let n=new Map;for(let{score:a,terms:o}of this.search(t,r)){let l=o.join(" "),d=n.get(l);d!=null?(d.score+=a,d.count+=1):n.set(l,{score:a,terms:o,count:1})}let i=[];for(let[a,{score:o,terms:l,count:d}]of n)i.push({suggestion:a,terms:l,score:o/d});return i.sort(oA),i}get documentCount(){return this._documentCount}get termCount(){return this._index.size}static loadJSON(t,r){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJS(JSON.parse(t),r)}static loadJSONAsync(t,r){return bd(this,void 0,void 0,function*(){if(r==null)throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");return this.loadJSAsync(JSON.parse(t),r)})}static getDefault(t){if(A0.hasOwnProperty(t))return y0(A0,t);throw new Error(`MiniSearch: unknown option "${t}"`)}static loadJS(t,r){let{index:n,documentIds:i,fieldLength:a,storedFields:o,serializationVersion:l}=t,d=this.instantiateMiniSearch(t,r);d._documentIds=gd(i),d._fieldLength=gd(a),d._storedFields=gd(o);for(let[p,g]of d._documentIds)d._idToShortId.set(g,p);for(let[p,g]of n){let E=new Map;for(let _ of Object.keys(g)){let y=g[_];l===1&&(y=y.ds),E.set(parseInt(_,10),gd(y))}d._index.set(p,E)}return d}static loadJSAsync(t,r){return bd(this,void 0,void 0,function*(){let{index:n,documentIds:i,fieldLength:a,storedFields:o,serializationVersion:l}=t,d=this.instantiateMiniSearch(t,r);d._documentIds=yield _d(i),d._fieldLength=yield _d(a),d._storedFields=yield _d(o);for(let[g,E]of d._documentIds)d._idToShortId.set(E,g);let p=0;for(let[g,E]of n){let _=new Map;for(let y of Object.keys(E)){let C=E[y];l===1&&(C=C.ds),_.set(parseInt(y,10),yield _d(C))}++p%1e3===0&&(yield mA(0)),d._index.set(g,_)}return d})}static instantiateMiniSearch(t,r){let{documentCount:n,nextId:i,fieldIds:a,averageFieldLength:o,dirtCount:l,serializationVersion:d}=t;if(d!==1&&d!==2)throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");let p=new Ii(r);return p._documentCount=n,p._nextId=i,p._idToShortId=new Map,p._fieldIds=a,p._avgFieldLength=o,p._dirtCount=l||0,p._index=new Ci,p}executeQuery(t,r={}){if(t===Ii.wildcard)return this.executeWildcardQuery(r);if(typeof t!="string"){let _=Object.assign(Object.assign(Object.assign({},r),t),{queries:void 0}),y=t.queries.map(C=>this.executeQuery(C,_));return this.combineResults(y,_.combineWith)}let{tokenize:n,processTerm:i,searchOptions:a}=this._options,o=Object.assign(Object.assign({tokenize:n,processTerm:i},a),r),{tokenize:l,processTerm:d}=o,E=l(t).flatMap(_=>d(_)).filter(_=>!!_).map(aR(o)).map(_=>this.executeQuerySpec(_,o));return this.combineResults(E,o.combineWith)}executeQuerySpec(t,r){let n=Object.assign(Object.assign({},this._options.searchOptions),r),i=(n.fields||this._options.fields).reduce((k,P)=>Object.assign(Object.assign({},k),{[P]:y0(n.boost,P)||1}),{}),{boostDocument:a,weights:o,maxFuzzy:l,bm25:d}=n,{fuzzy:p,prefix:g}=Object.assign(Object.assign({},aA.weights),o),E=this._index.get(t.term),_=this.termResults(t.term,t.term,1,t.termBoost,E,i,a,d),y,C;if(t.prefix&&(y=this._index.atPrefix(t.term)),t.fuzzy){let k=t.fuzzy===!0?.2:t.fuzzy,P=k<1?Math.min(l,Math.round(t.term.length*k)):k;P&&(C=this._index.fuzzyGet(t.term,P))}if(y)for(let[k,P]of y){let N=k.length-t.term.length;if(!N)continue;C?.delete(k);let L=g*k.length/(k.length+.3*N);this.termResults(t.term,k,L,t.termBoost,P,i,a,d,_)}if(C)for(let k of C.keys()){let[P,N]=C.get(k);if(!N)continue;let L=p*k.length/(k.length+N);this.termResults(t.term,k,L,t.termBoost,P,i,a,d,_)}return _}executeWildcardQuery(t){let r=new Map,n=Object.assign(Object.assign({},this._options.searchOptions),t);for(let[i,a]of this._documentIds){let o=n.boostDocument?n.boostDocument(a,"",this._storedFields.get(i)):1;r.set(i,{score:o,terms:[],match:{}})}return r}combineResults(t,r=O0){if(t.length===0)return new Map;let n=r.toLowerCase(),i=rR[n];if(!i)throw new Error(`Invalid combination operator: ${r}`);return t.reduce(i)||new Map}toJSON(){let t=[];for(let[r,n]of this._index){let i={};for(let[a,o]of n)i[a]=Object.fromEntries(o);t.push([r,i])}return{documentCount:this._documentCount,nextId:this._nextId,documentIds:Object.fromEntries(this._documentIds),fieldIds:this._fieldIds,fieldLength:Object.fromEntries(this._fieldLength),averageFieldLength:this._avgFieldLength,storedFields:Object.fromEntries(this._storedFields),dirtCount:this._dirtCount,index:t,serializationVersion:2}}termResults(t,r,n,i,a,o,l,d,p=new Map){if(a==null)return p;for(let g of Object.keys(o)){let E=o[g],_=this._fieldIds[g],y=a.get(_);if(y==null)continue;let C=y.size,k=this._avgFieldLength[_];for(let P of y.keys()){if(!this._documentIds.has(P)){this.removeTerm(_,P,r),C-=1;continue}let N=l?l(this._documentIds.get(P),r,this._storedFields.get(P)):1;if(!N)continue;let L=y.get(P),H=this._fieldLength.get(P)[_],R=iR(L,C,this._documentCount,H,k,d),B=n*i*E*N*R,V=p.get(P);if(V){V.score+=B,oR(V.terms,t);let X=y0(V.match,r);X?X.push(g):V.match[r]=[g]}else p.set(P,{score:B,terms:[t],match:{[r]:[g]}})}}return p}addTerm(t,r,n){let i=this._index.fetch(n,uA),a=i.get(t);if(a==null)a=new Map,a.set(r,1),i.set(t,a);else{let o=a.get(r);a.set(r,(o||0)+1)}}removeTerm(t,r,n){if(!this._index.has(n)){this.warnDocumentChanged(r,t,n);return}let i=this._index.fetch(n,uA),a=i.get(t);a==null||a.get(r)==null?this.warnDocumentChanged(r,t,n):a.get(r)<=1?a.size<=1?i.delete(t):a.delete(r):a.set(r,a.get(r)-1),this._index.get(n).size===0&&this._index.delete(n)}warnDocumentChanged(t,r,n){for(let i of Object.keys(this._fieldIds))if(this._fieldIds[i]===r){this._options.logger("warn",`MiniSearch: document with ID ${this._documentIds.get(t)} has changed before removal: term "${n}" was not present in field "${i}". Removing a document after it has changed can corrupt the index!`,"version_conflict");return}}addDocumentId(t){let r=this._nextId;return this._idToShortId.set(t,r),this._documentIds.set(r,t),this._documentCount+=1,this._nextId+=1,r}addFields(t){for(let r=0;rObject.prototype.hasOwnProperty.call(e,t)?e[t]:void 0,rR={[O0]:(e,t)=>{for(let r of t.keys()){let n=e.get(r);if(n==null)e.set(r,t.get(r));else{let{score:i,terms:a,match:o}=t.get(r);n.score=n.score+i,n.match=Object.assign(n.match,o),sA(n.terms,a)}}return e},[pA]:(e,t)=>{let r=new Map;for(let n of t.keys()){let i=e.get(n);if(i==null)continue;let{score:a,terms:o,match:l}=t.get(n);sA(i.terms,o),r.set(n,{score:i.score+a,terms:i.terms,match:Object.assign(i.match,l)})}return r},[tR]:(e,t)=>{for(let r of t.keys())e.delete(r);return e}},nR={k:1.2,b:.7,d:.5},iR=(e,t,r,n,i,a)=>{let{k:o,b:l,d}=a;return Math.log(1+(r-t+.5)/(t+.5))*(d+e*(o+1)/(e+o*(1-l+l*n/i)))},aR=e=>(t,r,n)=>{let i=typeof e.fuzzy=="function"?e.fuzzy(t,r,n):e.fuzzy||!1,a=typeof e.prefix=="function"?e.prefix(t,r,n):e.prefix===!0,o=typeof e.boostTerm=="function"?e.boostTerm(t,r,n):1;return{term:t,fuzzy:i,prefix:a,termBoost:o}},A0={idField:"id",extractField:(e,t)=>e[t],tokenize:e=>e.split(uR),processTerm:e=>e.toLowerCase(),fields:void 0,searchOptions:void 0,storeFields:[],logger:(e,t)=>{typeof console?.[e]=="function"&&console[e](t)},autoVacuum:!0},aA={combineWith:O0,prefix:!1,fuzzy:!1,maxFuzzy:6,boost:{},weights:{fuzzy:.45,prefix:.375},bm25:nR},sR={combineWith:pA,prefix:(e,t,r)=>t===r.length-1},C0={batchSize:1e3,batchWait:10},I0={minDirtFactor:.1,minDirtCount:20},w0=Object.assign(Object.assign({},C0),I0),oR=(e,t)=>{e.includes(t)||e.push(t)},sA=(e,t)=>{for(let r of t)e.includes(r)||e.push(r)},oA=({score:e},{score:t})=>t-e,uA=()=>new Map,gd=e=>{let t=new Map;for(let r of Object.keys(e))t.set(parseInt(r,10),e[r]);return t},_d=e=>bd(void 0,void 0,void 0,function*(){let t=new Map,r=0;for(let n of Object.keys(e))t.set(parseInt(n,10),e[n]),++r%1e3===0&&(yield mA(0));return t}),mA=e=>new Promise(t=>setTimeout(t,e)),uR=/[\n\r\p{Z}\p{P}]+/u;en();Nr();var HS=require("obsidian");Oc();en();Nr();var $S=BS(),Eh=class{constructor(t){this.plugin=t}tokenizeForIndexing(t){try{let r=this.tokenizeWords(t),n=[];if(this.plugin.settings.tokenizeUrls)try{n=$S(t)}catch(a){Ke("Error extracting urls",a)}let i=this.tokenizeTokens(t,{skipChs:!0});return i=[...i.flatMap(a=>[a,...Am(a),...ym(a)]),...r],n.length&&(i=[...i,...n]),i=[...new Set(i)],i}catch(r){return console.error("Error tokenizing text, skipping document",r),[]}}tokenizeForSearch(t){let r=$S(t);t=r.reduce((i,a)=>i.replace(a,""),t);let n=[...this.tokenizeTokens(t),...r].filter(Boolean);return{combineWith:"OR",queries:[{combineWith:"AND",queries:n},{combineWith:"AND",queries:this.tokenizeWords(t).filter(Boolean)},{combineWith:"AND",queries:n.flatMap(Am)},{combineWith:"AND",queries:n.flatMap(ym)}]}}tokenizeWords(t,{skipChs:r=!1}={}){let n=t.split(sv);return r?n:this.tokenizeChsWord(n)}tokenizeTokens(t,{skipChs:r=!1}={}){let n=t.split(yf);return r?n:this.tokenizeChsWord(n)}tokenizeChsWord(t){let r=this.plugin.getChsSegmenter();return r?t.flatMap(n=>nv.test(n)?r.cut(n,{search:!0}):[n]):t}};var vh=class{constructor(t){this.plugin=t;this.indexedDocuments=new Map;this.tokenizer=new Eh(t),this.minisearch=new Ii(this.getOptions())}async loadCache(){await this.plugin.embedsRepository.loadFromCache();let t=await this.plugin.database.getMinisearchCache();return t?(this.minisearch=await Ii.loadJSAsync(t.data,this.getOptions()),this.indexedDocuments=new Map(t.paths.map(r=>[r.path,r.mtime])),!0):(console.log("Omnisearch - No cache found"),!1)}getDocumentsToReindex(t){let r=new Map(t.map(a=>[a.path,a.mtime])),n=t.filter(a=>!this.indexedDocuments.has(a.path)||this.indexedDocuments.get(a.path)!==a.mtime),i=[...this.indexedDocuments].filter(([a,o])=>!r.has(a)||r.get(a)!==o).map(a=>({path:a[0],mtime:a[1]}));return{toAdd:n,toRemove:i}}async addFromPaths(t){Ke("Adding files",t);let r=(await Promise.all(t.map(async i=>await this.plugin.documentsRepository.getDocument(i)))).filter(i=>!!i?.path);Ke("Sorting documents to first index markdown"),r=n0(r,i=>i.path.endsWith(".md")?0:1),this.removeFromPaths(r.filter(i=>this.indexedDocuments.has(i.path)).map(i=>i.path));let n=dv(r,500);for(let i of n){Ke("Indexing into search engine",i),i.forEach(o=>this.indexedDocuments.set(o.path,o.mtime));let a=i.filter(o=>this.minisearch.has(o.path));this.removeFromPaths(a.map(o=>o.path)),await this.minisearch.addAllAsync(i)}}removeFromPaths(t){t.forEach(n=>this.indexedDocuments.delete(n));let r=t.filter(n=>this.minisearch.has(n));this.minisearch.discardAll(r)}async search(t,r){let n=this.plugin.settings;if(t.isEmpty())return[];Ke("=== New search ==="),Ke("Starting search for",t);let i;switch(n.fuzziness){case"0":i=0;break;case"1":i=.1;break;default:i=.2;break}let a=this.tokenizer.tokenizeForSearch(t.segmentsToStr());Ke(JSON.stringify(a,null,1));let o=this.minisearch.search(a,{prefix:E=>E.length>=r.prefixLength,fuzzy:E=>E.length<=3?0:E.length<=5?i/2:i,boost:{basename:n.weightBasename,aliases:n.weightBasename,displayTitle:n.weightBasename,directory:n.weightDirectory,headings1:n.weightH1,headings2:n.weightH2,headings3:n.weightH3,tags:n.weightUnmarkedTags,unmarkedTags:n.weightUnmarkedTags},tokenize:E=>[E],boostDocument(E,_,y){if(!y?.mtime||n.recencyBoost==="0")return 1;let C=y?.mtime,P=(new Date().valueOf()-C)/(24*3600),N={["1"]:-3,["2"]:-.3,["3"]:-.1};return 1+Math.exp(N[n.recencyBoost]*P)}});if(Ke(`Found ${o.length} results`,o),t.query.ext?.length&&(o=o.filter(E=>{let _="."+E.id.split(".").pop();return t.query.ext?.some(y=>_.startsWith(y.startsWith(".")?y:"."+y))})),t.query.path&&(o=o.filter(E=>t.query.path?.some(_=>E.id.toLowerCase().includes(_.toLowerCase())))),t.query.exclude.path&&(o=o.filter(E=>!t.query.exclude.path?.some(_=>E.id.toLowerCase().includes(_.toLowerCase())))),!o.length)return[];if(r.singleFilePath)return o.filter(E=>E.id===r.singleFilePath);Ke("searching with downranked folders",n.downrankedFoldersFilters),n.hideExcluded?o=o.filter(E=>!(this.plugin.app.metadataCache.isUserIgnored&&this.plugin.app.metadataCache.isUserIgnored(E.id))):o.forEach(E=>{this.plugin.app.metadataCache.isUserIgnored&&this.plugin.app.metadataCache.isUserIgnored(E.id)&&(E.score/=10)});let l=t.getTags();for(let E of o){let _=E.id;if(n.downrankedFoldersFilters.length>0){let C=!1;n.downrankedFoldersFilters.forEach(N=>{_.startsWith(N)&&(_===N||_.startsWith(N+"/"))&&(Ke("searching with downranked folders in path: ",_),C=!0)}),C&&(E.score/=10);let k=_.split("/"),P=k.length;for(let N=0;NP.includes(N))&&(Ke(`Boosting field "${C}" x${k} for ${_}`),E.score*=k)}for(let C of l)(E.tags??[]).includes(C)&&(E.score*=100)}Ke("Sorting and limiting results"),o=o.sort((E,_)=>_.score-E.score).slice(0,50),Ke("Filtered results:",o),o.length&&Ke("First result:",o[0]);let d=await Promise.all(o.map(async E=>{let _=await this.plugin.documentsRepository.getDocument(E.id);return _||(console.warn(`Omnisearch - Note "${E.id}" not in the live cache`),hc(!0)),_})),p=t.getExactTerms();p.length&&(Ke("Filtering with quoted terms: ",p),o=o.filter(E=>{let _=d.find(k=>k.path===E.id),y=_?.path.toLowerCase()??"",C=(_?.cleanedContent??"").toLowerCase();return p.every(k=>C.includes(k)||Wi(y,this.plugin.settings.ignoreArabicDiacritics).includes(k))}));let g=t.query.exclude.text;return g.length&&(Ke("Filtering with exclusions"),o=o.filter(E=>{let _=(d.find(y=>y.path===E.id)?.content??"").toLowerCase();return g.every(y=>!_.includes(y))})),Ke("Deduping"),o=o.filter((E,_,y)=>y.findIndex(C=>C.id===E.id)===_),o}async getSuggestions(t,r){let n;this.plugin.settings.simpleSearch?n=await this.search(t,{prefixLength:3,singleFilePath:r?.singleFilePath}):n=await this.search(t,{prefixLength:1,singleFilePath:r?.singleFilePath});let i=await Promise.all(n.map(async l=>await this.plugin.documentsRepository.getDocument(l.id))),a=i.length;for(let l=0;l{Ke("Locating matches for",l.id);let d=i.find(_=>_.path===l.id);d||(console.warn(`Omnisearch - Note "${l.id}" not in the live cache`),d={content:"",basename:l.id,path:l.id});let p=[...l.terms,...t.getExactTerms(),...t.getTags()];Ke("Matching tokens:",p),Ke("Getting matches locations...");let g=this.plugin.textProcessor.getMatches(d.content,p,t);return Ke(`Matches for note "${d.path}"`,g),{score:l.score,foundWords:p,matches:g,isEmbed:l.isEmbed,...d}});return Ke("Suggestions:",o),o}getSerializedMiniSearch(){return this.minisearch.toJSON()}getSerializedIndexedDocuments(){return Array.from(this.indexedDocuments).map(([t,r])=>({path:t,mtime:r}))}getOptions(){return{tokenize:this.tokenizer.tokenizeForIndexing.bind(this.tokenizer),extractField:(t,r)=>{if(r==="directory"){let n=t.path.split("/");return n.pop(),n.join("/")}return t[r]},processTerm:t=>(this.plugin.settings.ignoreDiacritics?Wi(t,this.plugin.settings.ignoreArabicDiacritics):t).toLowerCase(),idField:"path",fields:["basename","directory","aliases","content","headings1","headings2","headings3"],storeFields:["tags","mtime"],logger(t,r,n){n==="version_conflict"&&new HS.Notice("Omnisearch - Your index cache may be incorrect or corrupted. If this message keeps appearing, go to Settings to clear the cache.",5e3)}}}};var xh=require("obsidian");Nr();_c();var Th=class{constructor(t){this.plugin=t;this.documents=new Map;this.errorsCount=0;this.errorsWarned=!1;setInterval(()=>{this.errorsCount>0&&--this.errorsCount},1e3)}async addDocument(t){try{let r=await this.getAndMapIndexedDocument(t);if(!r.path){console.error(`Missing .path field in IndexedDocument "${r.basename}", skipping`);return}this.documents.set(t,r),this.plugin.embedsRepository.refreshEmbedsForNote(t)}catch(r){console.warn(`Omnisearch: Error while adding "${t}" to live cache`,r),this.removeDocument(t),hc()}}removeDocument(t){this.documents.delete(t)}async getDocument(t){if(this.documents.has(t))return this.documents.get(t);Ke("Generating IndexedDocument from",t),await this.addDocument(t);let r=this.documents.get(t);return r||(console.error("Omnisearch",t,"cannot be read"),hc()),r}async getAndMapIndexedDocument(t){t=(0,xh.normalizePath)(t);let r=this.plugin.app,n=r.vault.getAbstractFileByPath(t);if(!n)throw new Error(`Invalid file path: "${t}"`);if(!(n instanceof xh.TFile))throw new Error(`Not a TFile: "${t}"`);let i=null,a=this.plugin.getTextExtractor(),o=this.plugin.getAIImageAnalyzer();if(this.plugin.notesIndexer.isFilePlaintext(t))i=await r.vault.cachedRead(n);else if(Ai(t)){let g=await r.vault.cachedRead(n),E=g?JSON.parse(g):{},_=[];for(let y of E.nodes??[])y.type==="text"?_.push(y.text):y.type==="file"&&_.push(y.file);for(let y of(E.edges??[]).filter(C=>!!C.label))_.push(y.label);i=_.join(`\r -`)}else if(dc(t))try{let g=JSON.parse(await r.vault.cachedRead(n)),E=[],_=y=>{for(let C in y)typeof y[C]=="object"?_(y[C]):C==="content"&&E.push(y[C])};_(g),i=E.join(`\r -`)}catch(g){console.error("Omnisearch: Error while parsing Dataloom file",t),console.error(g)}else Mn(t)&&(this.plugin.settings.imagesIndexing&&a?.canFileBeExtracted(t)||this.plugin.settings.aiImageIndexing&&o?.canBeAnalyzed(n))?(this.plugin.settings.imagesIndexing&&a?.canFileBeExtracted(t)&&(i=await a.extractText(n)),this.plugin.settings.aiImageIndexing&&o?.canBeAnalyzed(n)&&(i=await o.analyzeImage(n)+(i??""))):ti(t)&&this.plugin.settings.PDFIndexing&&a?.canFileBeExtracted(t)?i=await a.extractText(n):fv(t)&&this.plugin.settings.officeIndexing&&a?.canFileBeExtracted(t)?i=await a.extractText(n):this.plugin.notesIndexer.isFilenameIndexable(t)&&(i=n.path);i==null&&(console.warn(`Omnisearch: ${i} content for file`,n.path),i="");let l=r.metadataCache.getFileCache(n);if(l){let g=gv(this.plugin.app,n,l);for(let E of g.filter(_=>!this.documents.has(_))){let _=this.plugin.notesIndexer.generateIndexableNonexistingDocument(E,n.path)}if(l.frontmatter?.["excalidraw-plugin"]){let E=l.sections?.filter(_=>_.type==="comment")??[];for(let{start:_,end:y}of E.map(C=>C.position))i=i.substring(0,_.offset-1)+i.substring(y.offset)}}let d;this.plugin.settings.displayTitle==="#heading"?d=l?.headings?.find(g=>g.level===1)?.heading??"":d=l?.frontmatter?.[this.plugin.settings.displayTitle]??"";let p=lv(l);return{basename:n.basename,displayTitle:d,content:i,cleanedContent:uv(Wi(i)),path:n.path,mtime:n.stat.mtime,tags:p,unmarkedTags:p.map(g=>g.replace("#","")),aliases:cv(l).join(""),headings1:l?Af(l,1).join(" "):"",headings2:l?Af(l,2).join(" "):"",headings3:l?Af(l,3).join(" "):""}}};Nr();_c();Nr();var yh=class{constructor(t){this.plugin=t;this.notesToReindex=new Set}flagNoteForReindex(t){this.notesToReindex.add(t)}async refreshIndex(){for(let r of this.notesToReindex)Ke("Updating file",r.path),await this.plugin.documentsRepository.addDocument(r.path);let t=[...this.notesToReindex].map(r=>r.path);t.length&&(this.plugin.searchEngine.removeFromPaths(t),await this.plugin.searchEngine.addFromPaths(t),this.notesToReindex.clear())}isFileIndexable(t){return this.isFilenameIndexable(t)||this.isContentIndexable(t)}isContentIndexable(t){let r=this.plugin.settings,n=!!this.plugin.getTextExtractor(),i=!!this.plugin.getAIImageAnalyzer(),a=n&&r.PDFIndexing,o=n&&r.imagesIndexing,l=i&&r.aiImageIndexing;return this.isFilePlaintext(t)||Ai(t)||dc(t)||a&&ti(t)||o&&Mn(t)||l&&Mn(t)}isFilenameIndexable(t){return this.canIndexUnsupportedFiles()||this.isFilePlaintext(t)||Ai(t)||dc(t)}canIndexUnsupportedFiles(){return this.plugin.settings.unsupportedFilesIndexing==="yes"||this.plugin.settings.unsupportedFilesIndexing==="default"&&!!this.plugin.app.vault.getConfig("showUnsupportedFiles")}generateIndexableNonexistingDocument(t,r){return t=Nm(t),{path:t+(t.endsWith(".md")?"":".md"),basename:t,displayTitle:"",mtime:0,content:"",cleanedContent:"",tags:[],unmarkedTags:[],aliases:"",headings1:"",headings2:"",headings3:"",doesNotExist:!0,parent:r}}isFilePlaintext(t){return[...this.plugin.settings.indexedFileTypes,"md"].some(r=>t.endsWith(`.${r}`))}};s0();var wh=require("obsidian");Nr();var Ah=class{constructor(t){this.plugin=t;this.embeds=new Map}addEmbed(t,r){this.embeds.has(t)||this.embeds.set(t,new Set),this.embeds.get(t).add(r)}removeFile(t){this.embeds.delete(t),this.refreshEmbedsForNote(t)}renameFile(t,r){this.embeds.has(t)&&(this.embeds.set(r,this.embeds.get(t)),this.embeds.delete(t)),this.embeds.forEach((n,i)=>{n.has(t)&&(n.delete(t),n.add(r))})}refreshEmbedsForNote(t){this.embeds.forEach((r,n)=>{r.has(t)&&r.delete(t)}),this.addEmbedsForNote(t)}getEmbeds(t){return this.embeds.has(t)?[...this.embeds.get(t)]:[]}async writeToCache(){Ke("Writing embeds to cache");let t=this.plugin.database,r=[];for(let[n,i]of this.embeds)r.push({embedded:n,referencedBy:[...i]});await t.embeds.clear(),await t.embeds.bulkAdd(r)}async loadFromCache(){try{let t=this.plugin.database;if(!t.embeds){Ke("No embeds in cache");return}Ke("Loading embeds from cache");let r=await t.embeds.toArray();for(let{embedded:n,referencedBy:i}of r)for(let a of i)this.addEmbed(n,a)}catch{this.plugin.database.clearCache(),console.error("Omnisearch - Error while loading embeds cache"),new wh.Notice("Omnisearch - There was an error while loading the cache. Please restart Obsidian.")}}addEmbedsForNote(t){let r=(this.plugin.app.metadataCache.getCache(t)?.embeds??[]).map(n=>this.plugin.app.metadataCache.getFirstLinkpathDest((0,wh.getLinkpath)(n.link),t)).filter(n=>!!n);for(let n of r)this.addEmbed(n.path,t)}};var Sh=class{constructor(t){this.plugin=t;this.nextQueryIsEmpty=!1}async addToHistory(t){if(!t){this.nextQueryIsEmpty=!0;return}this.nextQueryIsEmpty=!1;let r=this.plugin.database,n=await r.searchHistory.toArray();n=n.filter(i=>i.query!==t).reverse(),n.unshift({query:t}),n=n.slice(0,10),await r.searchHistory.clear(),await r.searchHistory.bulkAdd(n)}async getHistory(){let t=(await this.plugin.database.searchHistory.toArray()).reverse().map(r=>r.query);return this.nextQueryIsEmpty&&t.unshift(""),t}};var Ch=class extends zn.Plugin{constructor(r,n){super(r,n);this.apiHttpServer=null;this.settings=Dc(this.app);this.embedsRepository=new Ah(this);this.database=new Pc(this);this.notesIndexer=new yh(this);this.textProcessor=new id(this);this.searchEngine=new vh(this);this.searchHistory=new Sh(this);this.documentsRepository=new Th(this)}async onload(){if(this.settings=await Dy(this),this.addSettingTab(new nd(this)),zn.Platform.isMobile||Promise.resolve().then(()=>(YS(),zS)).then(i=>this.apiHttpServer=i.getServer(this)),If(this.app)){console.debug("Plugin disabled");return}await cF(this.app),await this.database.clearOldDatabases(),tA(this);let r=this.settings;r.ribbonIcon&&this.addRibbonButton(),Me.disable("vault"),Me.disable("infile"),Me.on("global",xf.ToggleExcerpts,()=>{Fa.set(!r.showExcerpt)}),this.addCommand({id:"show-modal",name:"Vault search",callback:()=>{new ta(this).open()}}),this.addCommand({id:"show-modal-infile",name:"In-file search",editorCallback:(i,a)=>{a.file&&new ks(this,a.file).open()}});let n=this.searchEngine;this.app.workspace.onLayoutReady(async()=>{this.registerEvent(this.app.vault.on("create",i=>{i instanceof zn.TFile&&this.notesIndexer.isFileIndexable(i.path)&&(Ke("Indexing new file",i.path),n.addFromPaths([i.path]),this.embedsRepository.refreshEmbedsForNote(i.path))})),this.registerEvent(this.app.vault.on("delete",i=>{i instanceof zn.TFile&&(Ke("Removing file",i.path),this.documentsRepository.removeDocument(i.path),n.removeFromPaths([i.path]),this.embedsRepository.removeFile(i.path))})),this.registerEvent(this.app.vault.on("modify",async i=>{i instanceof zn.TFile&&(this.notesIndexer.isFileIndexable(i.path)&&this.notesIndexer.flagNoteForReindex(i),this.embedsRepository.refreshEmbedsForNote(i.path))})),this.registerEvent(this.app.vault.on("rename",async(i,a)=>{i instanceof zn.TFile&&this.notesIndexer.isFileIndexable(i.path)&&(Ke("Renaming file",i.path),this.documentsRepository.removeDocument(a),await this.documentsRepository.addDocument(i.path),n.removeFromPaths([a]),await n.addFromPaths([i.path]),this.embedsRepository.renameFile(a,i.path))})),this.refreshIndexCallback=this.notesIndexer.refreshIndex.bind(this.notesIndexer),addEventListener("blur",this.refreshIndexCallback),removeEventListener,await this.executeFirstLaunchTasks(),await this.populateIndex(),this.apiHttpServer&&r.httpApiEnabled&&this.apiHttpServer.listen(r.httpApiPort)})}async executeFirstLaunchTasks(){let r="1.21.0";this.settings.welcomeMessage=r,await this.saveData(this.settings)}async onunload(){delete globalThis.omnisearch,this.refreshIndexCallback&&removeEventListener("blur",this.refreshIndexCallback),await this.database.clearCache(),this.apiHttpServer.close()}addRibbonButton(){this.ribbonButton=this.addRibbonIcon("search","Omnisearch",r=>{new ta(this).open()})}removeRibbonButton(){this.ribbonButton&&this.ribbonButton.parentNode?.removeChild(this.ribbonButton)}getChsSegmenter(){return this.app.plugins.plugins["cm-chs-patch"]}getTextExtractor(){return this.app.plugins?.plugins?.["text-extractor"]?.api}getAIImageAnalyzer(){return this.app.plugins?.plugins?.["ai-image-analyzer"]?.api}async populateIndex(){console.time("Indexing total time"),Ca.set(2);let r=this.app.vault.getFiles().filter(a=>this.notesIndexer.isFileIndexable(a.path));console.debug(`${r.length} files total`),console.debug(`Cache is ${Qi()?"enabled":"disabled"}`);let n=this.searchEngine;Qi()&&(console.time("Loading index from cache"),Ca.set(1),await n.loadCache()&&console.timeEnd("Loading index from cache"));let i=n.getDocumentsToReindex(r.map(a=>({path:a.path,mtime:a.stat.mtime})));if(Qi()&&(i.toAdd.length&&console.debug("Total number of files to add/update: "+i.toAdd.length),i.toRemove.length&&console.debug("Total number of files to remove: "+i.toRemove.length)),i.toAdd.length>=1e3&&Qi()&&new zn.Notice(`${i.toAdd.length} files need to be indexed. Obsidian may experience stutters and freezes during the process`,1e4),Ca.set(3),n.removeFromPaths(i.toRemove.map(a=>a.path)),await n.addFromPaths(i.toAdd.map(a=>a.path)),(i.toRemove.length||i.toAdd.length)&&Qi()){Ca.set(4);let a=this.settings.useCache;a&&!this.settings.DANGER_forceSaveCache&&(this.settings.useCache=!1,await ke(this)),await this.database.writeMinisearchCache(),await this.embedsRepository.writeToCache(),a&&(this.settings.useCache=!0,await ke(this))}console.timeEnd("Indexing total time"),i.toAdd.length>=1e3&&Qi()&&new zn.Notice("Your files have been indexed."),Ca.set(0),eA()}};async function cF(e){let t=[`${e.vault.configDir}/plugins/omnisearch/searchIndex.json`,`${e.vault.configDir}/plugins/omnisearch/notesCache.json`,`${e.vault.configDir}/plugins/omnisearch/notesCache.data`,`${e.vault.configDir}/plugins/omnisearch/searchIndex.data`,`${e.vault.configDir}/plugins/omnisearch/historyCache.json`,`${e.vault.configDir}/plugins/omnisearch/pdfCache.data`];for(let r of t)if(await e.vault.adapter.exists(r))try{await e.vault.adapter.remove(r)}catch{}} -/*! Bundled license information: - -lodash-es/lodash.js: - (** - * @license - * Lodash (Custom Build) - * Build: `lodash modularize exports="es" -o ./` - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - *) - -search-query-parser/lib/search-query-parser.js: - (*! - * search-query-parser.js - * Copyright(c) 2014-2019 - * MIT Licensed - *) - -dexie/dist/dexie.js: - (*! ***************************************************************************** - Copyright (c) Microsoft Corporation. - Permission to use, copy, modify, and/or distribute this software for any - purpose with or without fee is hereby granted. - THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH - REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY - AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, - INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM - LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR - OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR - PERFORMANCE OF THIS SOFTWARE. - ***************************************************************************** *) -*/ - -/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/omnisearch/manifest.json b/.obsidian/plugins/omnisearch/manifest.json deleted file mode 100644 index 279a1185..00000000 --- a/.obsidian/plugins/omnisearch/manifest.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "id": "omnisearch", - "name": "Omnisearch", - "version": "1.27.1", - "minAppVersion": "1.7.2", - "description": "A search engine that just works", - "author": "Simon Cambier", - "authorUrl": "https://github.com/scambier/obsidian-omnisearch", - "fundingUrl": { - "Github": "https://github.com/sponsors/scambier", - "Ko-fi": "https://ko-fi.com/scambier" - }, - "isDesktopOnly": false -} diff --git a/.obsidian/plugins/omnisearch/styles.css b/.obsidian/plugins/omnisearch/styles.css deleted file mode 100644 index 8b0c6c69..00000000 --- a/.obsidian/plugins/omnisearch/styles.css +++ /dev/null @@ -1,135 +0,0 @@ -.omnisearch-modal { -} - -.omnisearch-result { - white-space: normal; - display: flex; - flex-direction: row; - /* justify-content: space-between; */ - flex-wrap: nowrap; -} - -.omnisearch-result__title-container { - display: flex; - align-items: center; - justify-content: space-between; - column-gap: 5px; - flex-wrap: wrap; -} - -.omnisearch-result__title { - white-space: pre-wrap; - align-items: center; - display: flex; - gap: 5px; -} - -.omnisearch-result__title > span { -} - -.omnisearch-result__folder-path { - font-size: 0.75rem; - align-items: center; - display: flex; - gap: 5px; - color: var(--text-muted); -} - -.omnisearch-result__extension { - font-size: 0.7rem; - color: var(--text-muted); -} - -.omnisearch-result__counter { - font-size: 0.7rem; - color: var(--text-muted); -} - -.omnisearch-result__body { - white-space: normal; - font-size: small; - word-wrap: normal; - - overflow: hidden; - display: -webkit-box; - -webkit-line-clamp: 3; - -webkit-box-orient: vertical; - - color: var(--text-muted); - margin-inline-start: 0.5em; -} - -.omnisearch-result__embed { - margin-left: 1em; -} - - -.omnisearch-result__image-container { - flex-basis: 20%; - text-align: end; -} - -.omnisearch-highlight { -} - -.omnisearch-default-highlight { - text-decoration: underline; - text-decoration-color: var(--text-highlight-bg); - text-decoration-thickness: 3px; - text-underline-offset: -1px; - text-decoration-skip-ink: none; -} - -.omnisearch-input-container { - display: flex; - align-items: center; - flex-direction: row; - gap: 5px; -} - -.omnisearch-result__icon { - display: inline-block; - vertical-align: middle; - width: 16px; - height: 16px; - margin-right: 4px; -} - -.omnisearch-result__icon svg { - width: 100%; - height: 100%; -} - -.omnisearch-result__icon--emoji { - font-size: 16px; - vertical-align: middle; - margin-right: 4px; -} - -@media only screen and (max-width: 600px) { - .omnisearch-input-container { - flex-direction: column; - } - - .omnisearch-input-container__buttons { - display: flex; - flex-direction: row; - width: 100%; - padding: 0 1em 0 1em; - gap: 1em; - } - .omnisearch-input-container__buttons > button { - flex-grow: 1; - } -} - -@media only screen and (min-width: 600px) { - .omnisearch-input-container__buttons { - margin-inline-end: 1em; - } -} - -.omnisearch-input-field { - position: relative; - flex-grow: 1; -} diff --git a/.obsidian/plugins/sync-contacts-macos/main.js b/.obsidian/plugins/sync-contacts-macos/main.js new file mode 100644 index 00000000..d4a31ec4 --- /dev/null +++ b/.obsidian/plugins/sync-contacts-macos/main.js @@ -0,0 +1,1014 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/foldline/foldline.js +var require_foldline = __commonJS({ + "node_modules/foldline/foldline.js"(exports, module2) { + var CRLF = "\r\n"; + var SP = " "; + var MAX_LINE_LENGTH = 998; + var DEFAULT_LINE_LENGTH = 78; + var MIN_LINE_LENGTH = 2; + function foldLine(input, maxLength, hardWrap) { + if (maxLength != null && maxLength < MIN_LINE_LENGTH) { + throw new Error("Maximum length must not be less than " + MIN_LINE_LENGTH); + } + if (maxLength != null && maxLength > MAX_LINE_LENGTH) { + throw new Error("Maximum length must not exceed " + MAX_LINE_LENGTH); + } + maxLength = maxLength || DEFAULT_LINE_LENGTH; + input = input.replace(/[\r\n]+/g, ""); + if (input.length <= maxLength) { + return input; + } + var output = ""; + var index = 0; + var nextIndex = 0; + var length = input.length; + var line = 0; + var trim = 0; + while (index < length) { + if (!hardWrap && ~(nextIndex = input.lastIndexOf(SP, index + maxLength))) { + if (nextIndex > index) { + output += input.slice(index, nextIndex) + CRLF + SP; + index = nextIndex; + } else { + output += input.slice(index, index + maxLength - trim) + CRLF + SP; + index = index + maxLength - trim; + hardWrap = true; + } + } else { + output += input.slice(index, index + maxLength - trim) + CRLF + SP; + index = index + maxLength - trim; + } + if (length - index < maxLength) { + output += input.slice(index); + break; + } + if (line === 0) { + trim = 1; + } + line++; + } + return output; + } + foldLine.unfold = function unfold(input) { + return input.replace(/\r\n\s/gm, ""); + }; + module2.exports = foldLine; + } +}); + +// node_modules/camelcase/index.js +var require_camelcase = __commonJS({ + "node_modules/camelcase/index.js"(exports, module2) { + "use strict"; + var preserveCamelCase = (string) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + for (let i = 0; i < string.length; i++) { + const character = string[i]; + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + "-" + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + "-" + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + return string; + }; + var camelCase = (input, options) => { + if (!(typeof input === "string" || Array.isArray(input))) { + throw new TypeError("Expected the input to be `string | string[]`"); + } + options = Object.assign({ + pascalCase: false + }, options); + const postProcess = (x) => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + if (Array.isArray(input)) { + input = input.map((x) => x.trim()).filter((x) => x.length).join("-"); + } else { + input = input.trim(); + } + if (input.length === 0) { + return ""; + } + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + const hasUpperCase = input !== input.toLowerCase(); + if (hasUpperCase) { + input = preserveCamelCase(input); + } + input = input.replace(/^[_.\- ]+/, "").toLowerCase().replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()).replace(/\d+(\w|$)/g, (m) => m.toUpperCase()); + return postProcess(input); + }; + module2.exports = camelCase; + module2.exports.default = camelCase; + } +}); + +// node_modules/vcf/lib/property.js +var require_property = __commonJS({ + "node_modules/vcf/lib/property.js"(exports, module2) { + function Property(field, value, params) { + if (!(this instanceof Property)) + return new Property(value); + if (params != null) + Object.assign(this, params); + this._field = field; + this._data = value; + Object.defineProperty(this, "_field", { enumerable: false }); + Object.defineProperty(this, "_data", { enumerable: false }); + } + Property.fromJSON = function(data) { + var field = data[0]; + var params = data[1]; + if (!/text/i.test(data[2])) + params.value = data[2]; + var value = Array.isArray(data[3]) ? data[3].join(";") : data[3]; + return new Property(field, value, params); + }; + function capitalDashCase(value) { + return value.replace(/([A-Z])/g, "-$1").toUpperCase(); + } + Property.prototype = { + constructor: Property, + /** + * Check whether the property is of a given type + * @param {String} type + * @return {Boolean} + */ + is: function(type) { + type = (type + "").toLowerCase(); + return Array.isArray(this.type) ? this.type.indexOf(type) >= 0 : this.type === type; + }, + /** + * Check whether the property is empty + * @return {Boolean} + */ + isEmpty: function() { + return this._data == null && Object.keys(this).length === 0; + }, + /** + * Clone the property + * @return {Property} + */ + clone: function() { + return new Property(this._field, this._data, this); + }, + /** + * Format the property as vcf with given version + * @param {String} version + * @return {String} + */ + toString: function(version) { + var propName = (this.group ? this.group + "." : "") + capitalDashCase(this._field); + var keys = Object.keys(this); + var params = []; + for (var i = 0; i < keys.length; i++) { + if (keys[i] === "group") + continue; + switch (propName) { + case "TEL": + case "ADR": + case "EMAIL": + if (version === "2.1") { + if (Array.isArray(this[keys[i]])) + params.push(this[keys[i]].join(";")); + else + params.push(this[keys[i]]); + } else + params.push(capitalDashCase(keys[i]) + "=" + this[keys[i]]); + break; + default: + params.push(capitalDashCase(keys[i]) + "=" + this[keys[i]]); + } + } + if (version === "2.1" || version === "3.0") + return propName + (params.length ? ";" + params.join(";").toUpperCase() : params.toString().toUpperCase()) + ":" + (Array.isArray(this._data) ? this._data.join(";") : this._data); + else + return propName + (params.length ? ";" + params.join(";") : params) + ":" + (Array.isArray(this._data) ? this._data.join(";") : this._data); + }, + /** + * Get the property's value + * @return {String} + */ + valueOf: function() { + return this._data; + }, + /** + * Format the property as jCard data + * @return {Array} + */ + toJSON: function() { + var params = Object.assign({}, this); + if (params.value === "text") { + params.value = void 0; + delete params.value; + } + var data = [this._field, params, this.value || "text"]; + switch (this._field) { + default: + data.push(this._data); + break; + case "adr": + case "n": + data.push(this._data.split(";")); + } + return data; + } + }; + module2.exports = Property; + } +}); + +// node_modules/vcf/lib/parse-lines.js +var require_parse_lines = __commonJS({ + "node_modules/vcf/lib/parse-lines.js"(exports, module2) { + var camelCase = require_camelcase(); + var Property = require_property(); + function set(object, key, value) { + if (Array.isArray(object[key])) { + object[key].push(value); + } else if (object[key] != null) { + object[key] = [object[key], value]; + } else { + object[key] = value; + } + } + function createParams(params, param) { + var parts = param.split("="); + var k = camelCase(parts[0]); + var value = parts[1]; + if (value == null || value === "") { + value = parts[0]; + k = "type"; + } + if (k === "type") { + if (value[0] === '"' && value[value.length - 1] === '"' && value.indexOf(",") !== -1) + value = value.slice(1, -1); + value.toLowerCase().split(",").forEach(function(value2) { + set(params, k, value2); + }); + return params; + } + set(params, k, value); + return params; + } + function parseLines(lines) { + var data = {}; + var line = null; + var pattern = /^([^;:]+)((?:;(?:[^;:]+))*)(?:\:([\s\S]+))?$/i; + var len = lines.length - 1; + for (var i = 1; i < len; i++) { + line = lines[i]; + var match = pattern.exec(line); + if (!match) + continue; + var name = match[1].split("."); + var property = name.pop(); + var group = name.pop(); + var value = match[3]; + var params = match[2] ? match[2].replace(/^;|;$/g, "").split(";") : []; + var propParams = params.reduce(createParams, group ? { group } : {}); + var propName = camelCase(property); + var propVal = new Property(propName, value, propParams); + set(data, propName, propVal); + } + return data; + } + module2.exports = parseLines; + } +}); + +// node_modules/vcf/lib/vcard.js +var require_vcard = __commonJS({ + "node_modules/vcf/lib/vcard.js"(exports, module2) { + function vCard() { + if (!(this instanceof vCard)) + return new vCard(); + this.version = vCard.versions[vCard.versions.length - 1]; + this.data = {}; + } + vCard.mimeType = "text/vcard"; + vCard.extension = ".vcf"; + vCard.versions = ["2.1", "3.0", "4.0"]; + vCard.EOL = "\r\n"; + vCard.foldLine = require_foldline(); + vCard.normalize = function(input) { + return (input + "").replace(/^[\s\r\n]+|[\s\r\n]+$/g, "").replace(/(\r\n)[\x09\x20]?(\r\n)|$/g, "$1").replace(/\r\n[\x20\x09]/g, ""); + }; + vCard.isSupported = function(version) { + return /^\d\.\d$/.test(version) && vCard.versions.indexOf(version) !== -1; + }; + vCard.parse = function(value) { + var objects = (value + "").split(/(?=BEGIN\:VCARD)/gi); + var cards = []; + for (var i = 0; i < objects.length; i++) { + cards.push(new vCard().parse(objects[i])); + } + return cards; + }; + vCard.parseLines = require_parse_lines(); + vCard.fromJSON = function(jcard) { + jcard = typeof jcard === "string" ? JSON.parse(jcard) : jcard; + if (jcard == null || !Array.isArray(jcard)) + return new vCard(); + if (!/vcard/i.test(jcard[0])) + throw new Error("Object not in jCard format"); + var card = new vCard(); + jcard[1].forEach(function(prop) { + card.addProperty(vCard.Property.fromJSON(prop)); + }); + return card; + }; + vCard.format = function(card, version) { + version = version || card.version || vCard.versions[vCard.versions.length - 1]; + if (!vCard.isSupported(version)) + throw new Error('Unsupported vCard version "' + version + '"'); + var vcf3 = []; + vcf3.push("BEGIN:VCARD"); + vcf3.push("VERSION:" + version); + var props = Object.keys(card.data); + var prop = ""; + for (var i = 0; i < props.length; i++) { + if (props[i] === "version") + continue; + prop = card.data[props[i]]; + if (Array.isArray(prop)) { + for (var k = 0; k < prop.length; k++) { + if (prop[k].isEmpty()) + continue; + vcf3.push(vCard.foldLine(prop[k].toString(version), 75)); + } + } else if (!prop.isEmpty()) { + vcf3.push(vCard.foldLine(prop.toString(version), 75)); + } + } + vcf3.push("END:VCARD"); + return vcf3.join(vCard.EOL); + }; + vCard.Property = require_property(); + vCard.prototype = { + constructor: vCard, + /** + * Get a vCard property + * @param {String} key + * @return {Object|Array} + */ + get: function(key) { + if (this.data[key] == null) { + return this.data[key]; + } + if (Array.isArray(this.data[key])) { + return this.data[key].map(function(prop) { + return prop.clone(); + }); + } else { + return this.data[key].clone(); + } + }, + /** + * Set a vCard property + * @param {String} key + * @param {String} value + * @param {Object} params + */ + set: function(key, value, params) { + return this.setProperty(new vCard.Property(key, value, params)); + }, + /** + * Add a vCard property + * @param {String} key + * @param {String} value + * @param {Object} params + */ + add: function(key, value, params) { + var prop = new vCard.Property(key, value, params); + this.addProperty(prop); + return this; + }, + /** + * Set a vCard property from an already + * constructed vCard.Property + * @param {vCard.Property} prop + */ + setProperty: function(prop) { + this.data[prop._field] = prop; + return this; + }, + /** + * Add a vCard property from an already + * constructed vCard.Property + * @param {vCard.Property} prop + */ + addProperty: function(prop) { + var key = prop._field; + if (Array.isArray(this.data[key])) { + this.data[key].push(prop); + } else if (this.data[key] != null) { + this.data[key] = [this.data[key], prop]; + } else { + this.data[key] = prop; + } + return this; + }, + /** + * Parse a vcf formatted vCard + * @param {String} value + * @return {vCard} + */ + parse: function(value) { + var lines = vCard.normalize(value).split(/\r\n/g); + var begin = lines[0]; + var version = lines[1]; + var end = lines[lines.length - 1]; + const regexp_version = /VERSION:\d\.\d/i; + if (!/BEGIN:VCARD/i.test(begin)) + throw new SyntaxError('Invalid vCard: Expected "BEGIN:VCARD" but found "' + begin + '"'); + if (!/END:VCARD/i.test(end)) + throw new SyntaxError('Invalid vCard: Expected "END:VCARD" but found "' + end + '"'); + if (!regexp_version.test(version)) { + if (!(version = lines.find((line) => regexp_version.test(line)))) + throw new SyntaxError('Invalid vCard: Expected "VERSION:\\d.\\d" but none found'); + } + this.version = version.substring(8, 11); + if (!vCard.isSupported(this.version)) + throw new Error('Unsupported version "' + this.version + '"'); + this.data = vCard.parseLines(lines); + return this; + }, + /** + * Format the vCard as vcf with given version + * @param {String} version + * @param {String} charset + * @return {String} + */ + toString: function(version, charset) { + version = version || this.version; + return vCard.format(this, version); + }, + /** + * Format the card as jCard + * @param {String} version='4.0' + * @return {Array} jCard + */ + toJCard: function(version) { + version = version || "4.0"; + var keys = Object.keys(this.data); + var data = [["version", {}, "text", version]]; + var prop = null; + for (var i = 0; i < keys.length; i++) { + if (keys[i] === "version") + continue; + prop = this.data[keys[i]]; + if (Array.isArray(prop)) { + for (var k = 0; k < prop.length; k++) { + data.push(prop[k].toJSON()); + } + } else { + data.push(prop.toJSON()); + } + } + return ["vcard", data]; + }, + /** + * Format the card as jCard + * @return {Array} jCard + */ + toJSON: function() { + return this.toJCard(this.version); + } + }; + module2.exports = vCard; + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => ContactsPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian2 = require("obsidian"); + +// src/vcard.ts +var vcf = require_vcard(); +var VCard = class { + constructor(card) { + var _a, _b, _c, _d, _e; + this.version = card.version; + this.fn = (_a = card.get("fn")) == null ? void 0 : _a.valueOf().replace(/\\,/g, ","); + this.nickname = (_c = (_b = card.get("nickname")) == null ? void 0 : _b.valueOf()) != null ? _c : void 0; + this.organization = this.parseOrganization(card.get("org")); + this.title = (_e = (_d = card.get("title")) == null ? void 0 : _d.valueOf()) != null ? _e : void 0; + this.telephones = this.parseTelephones(card.get("tel")); + this.addresses = this.parseAddresses(card.get("adr")); + this.emails = this.parseEmails(card.get("email")); + this.birthdate = this.parseBirthdate(card.get("bday")); + this.URLs = this.parseURLs(card.get("url")); + this.notes = this.parseNotes(card.get("note")); + this.xabuid = this.parseXAbuid(card.get("xAbuid")); + if (this.fn == void 0) { + console.debug(`Found vCard without name: + ${JSON.stringify(this, null, 2)}`); + } + } + getFilename() { + var _a; + return (_a = this.fn) != null ? _a : "NO_NAME"; + } + toMarkdown(enabledFields) { + var _a; + let markdown = `## \u{1F464} ${this.fn} + +[Open in Contacts](addressbook://${(_a = this.xabuid) == null ? void 0 : _a.replace(":", "%3A")}) + +`; + this.getVCardFields().forEach((field) => { + var _a2; + if (!enabledFields.includes(field)) + return; + markdown += (_a2 = this.fieldToMarkdown(field)) != null ? _a2 : ""; + }); + return markdown.trim(); + } + fieldToMarkdown(field) { + var _a, _b, _c, _d, _e; + if (typeof this[field] === "undefined") + return void 0; + switch (field) { + case "nickname": + return `- Nickname: ${this.nickname} +`; + case "notes": + return `- \u{1F4DD} Notes: + ${this.notes} +`; + case "birthdate": + return `- \u{1F382} Birthday: ${(_a = this.birthdate) == null ? void 0 : _a.toLocaleDateString()} +`; + case "organization": + return `- \u{1F3E2} Organization: ${this.organization} +`; + case "title": + return `- \u{1F454} Title: ${this.title} +`; + case "emails": + return (_b = this.emails) == null ? void 0 : _b.map((mail) => { + return `- \u{1F4E7} [${mail}](mailto:${mail}) +`; + }).join(""); + case "URLs": + return (_c = this.URLs) == null ? void 0 : _c.map((URL) => { + return `- \u{1F310} Website: [${URL}](${URL}) +`; + }).join(""); + case "telephones": + return (_d = this.telephones) == null ? void 0 : _d.map(([type, tel]) => { + let emotes = ``; + const types = type.split(","); + switch (types[0]) { + case "cell": + emotes += "\u{1F4F1}"; + break; + case "home": + emotes += "\u{1F3E0}"; + break; + case "work": + emotes += "\u{1F3E2}"; + break; + default: + emotes += "\u260E\uFE0F"; + } + switch (types[1]) { + case "voice": + emotes += "\u{1F4DE}"; + break; + case "fax": + emotes += "\u{1F4E0}"; + break; + default: + } + return `- ${emotes} [${tel}](tel:${tel.replace(" ", "")}) +`; + }).join(""); + case "addresses": + return (_e = this.addresses) == null ? void 0 : _e.map(([type, adr]) => { + let emotes = ``; + switch (type) { + case "home": + emotes += "\u{1F3E0}"; + break; + case "work": + emotes += "\u{1F3E2}"; + break; + default: + emotes += "\u260E\uFE0F"; + } + let [_, __, street, city, ___, postcode, country] = adr.valueOf().split(";"); + return `- ${emotes} ${type} address: + ${street} + ${postcode} ${city} + ${country} +`; + }).join(""); + default: + console.error(`Error: Unknown field or markdown convertion: ${field}`); + return void 0; + } + } + parseBirthdate(bday) { + let birthdate = void 0; + if (bday) { + birthdate = new Date(Date.parse(bday.valueOf())); + } + return birthdate; + } + parseURLs(URLs) { + let links = void 0; + if (URLs) { + links = new Array(); + if (!Array.isArray(URLs)) { + URLs = [URLs]; + } + for (let url of URLs) { + links.push(url.valueOf()); + } + } + return links; + } + parseNotes(notes) { + var _a; + let notesString = void 0; + if (notes) { + notesString = (_a = notes.valueOf()) == null ? void 0 : _a.split("\\n").map((line) => line.endsWith("\\") ? line.slice(0, line.length - 2) : line).join("\n "); + } + return notesString; + } + parseXAbuid(xabuid) { + let xabuidString = void 0; + if (xabuid) { + xabuidString = xabuid.valueOf(); + } + return xabuidString; + } + parseEmails(email) { + let emails = void 0; + if (email) { + emails = new Array(); + if (!Array.isArray(email)) { + email = [email]; + } + for (let mail of email) { + emails.push(mail.valueOf()); + } + } + return emails; + } + parseAddresses(adr) { + var _a, _b, _c, _d, _e; + let addresses = void 0; + if (adr) { + addresses = new Array(); + if (!Array.isArray(adr)) { + adr = [adr]; + } + for (let address of adr) { + let type; + if (typeof address.type == "string") + type = (_b = (_a = address.type) == null ? void 0 : _a.toLowerCase()) != null ? _b : "home"; + else if (Array.isArray(address.type)) + type = (_e = (_d = (_c = address.type) == null ? void 0 : _c[0]) == null ? void 0 : _d.toLowerCase()) != null ? _e : "home"; + addresses.push([type, address.valueOf()]); + } + } + return addresses; + } + parseTelephones(tel) { + var _a, _b, _c, _d, _e, _f; + let telephones = void 0; + if (tel) { + telephones = new Array(); + if (!Array.isArray(tel)) { + tel = [tel]; + } + for (let telephone of tel) { + let type = ((_c = (_b = (_a = telephone.type) == null ? void 0 : _a[0]) == null ? void 0 : _b.toLowerCase()) != null ? _c : "phone") + "," + ((_f = (_e = (_d = telephone.type) == null ? void 0 : _d[1]) == null ? void 0 : _e.toLowerCase()) != null ? _f : "voice"); + telephones.push([type, telephone.valueOf()]); + } + } + return telephones; + } + parseOrganization(org) { + let organization = void 0; + if (org) { + organization = org.valueOf().replace(";", ", ").replace(/\\,/g, ","); + } + return organization; + } + static getVCardFields() { + const JSON_VCARD = ["vcard", [["version", {}, "text", "4.0"], ["fn", {}, "text", "name"]]]; + const inst = new VCard(vcf.fromJSON(JSON_VCARD)); + return inst.getVCardFields(); + } + getVCardFields() { + return Object.getOwnPropertyNames(this).filter((prop) => prop !== "constructor" && typeof this[prop] !== "function" && prop !== "version" && prop !== "fn"); + } +}; + +// src/osascriptService.ts +var { spawn } = require("child_process"); +var OsaScriptService = class { + async executeScript(JXA_script) { + return new Promise((resolve, reject) => { + const osascript = spawn("osascript", ["-l", "JavaScript", "-e", JXA_script]); + let output = ""; + osascript.stdout.on("data", (data) => { + output += data.toString("utf-8"); + }); + osascript.stderr.on("data", (data) => { + const errorMsg = data.toString("utf-8"); + reject(new Error(`Error executing JXA script: +${errorMsg}`)); + }); + osascript.on("close", (code) => { + if (code === 0) { + resolve(output); + } else { + reject(new Error(`Error executing JXA script: +${output}`)); + } + }); + }); + } +}; + +// src/contactsService.ts +var vcf2 = require_vcard(); +var ContactsService = class { + constructor(groupName, enabledContactFields, osaScriptService = new OsaScriptService()) { + this.GROUP_NOT_DEFINED_ERROR = "GROUP NOT DEFINED"; + this.groupName = groupName; + this.enabledContactFields = enabledContactFields; + this.osaScriptService = osaScriptService; + } + async loadContacts() { + let vCards = await this.getVCards(); + vCards = vCards.filter((vcard) => { + return vcard.fn != void 0; + }); + const filenameToMarkdown = /* @__PURE__ */ new Map(); + for (let vcard of vCards) { + filenameToMarkdown.set(vcard.getFilename(), vcard.toMarkdown(this.enabledContactFields)); + } + return filenameToMarkdown; + } + async getNumberOfContacts() { + const JXA_SCRIPT = ` + let Contacts = Application('Contacts'); + Contacts.includeStandardAdditions = true; + + let groups = Contacts.groups.whose({ name: '${this.groupName}'}); + if (groups.length === 0 || groups === undefined || groups === null) + throw new Error('${this.GROUP_NOT_DEFINED_ERROR}'); + + groups[0].people.length; + `; + let resultPromise = this.osaScriptService.executeScript(JXA_SCRIPT).then((resultStr) => { + let resultInt = parseInt(resultStr); + if (isNaN(resultInt)) { + throw new Error(`Non-numeric result from JXA script: ${resultStr}`); + } + return resultInt; + }); + return await resultPromise; + } + async getVCards() { + const JXA_SCRIPT = ` + ObjC.import('Foundation'); + const stdout = $.NSFileHandle.fileHandleWithStandardOutput; + + let Contacts = Application('Contacts'); + Contacts.includeStandardAdditions = true; + + let groups = Contacts.groups.whose({ name: '${this.groupName}'}); + if (groups.length === 0 || groups === undefined || groups === null) + throw new Error('${this.GROUP_NOT_DEFINED_ERROR}'); + + for (let vcard of groups[0].people.vcard()) { + // Write to stdout + const nsString = $.NSString.alloc.initWithUTF8String(vcard); + const data = nsString.dataUsingEncoding($.NSUTF8StringEncoding); + stdout.writeData(data); + } + `; + const vCardRegex = /BEGIN:VCARD[\s\S]*?END:VCARD/g; + let resultPromise = this.osaScriptService.executeScript(JXA_SCRIPT).then((vCardStr) => { + let matches = vCardStr.match(vCardRegex); + let vCards = []; + for (let match of matches != null ? matches : []) { + const card = new vcf2().parse(match); + const vCardObj = new VCard(card); + vCards.push(vCardObj); + } + return vCards; + }); + return await resultPromise; + } +}; + +// src/fileService.ts +var import_obsidian = require("obsidian"); +var ContentSeperator = class { + constructor(startTag, startText, stopTag, stopText, commented = true) { + this.startTag = startTag; + this.startText = startText; + this.endTag = stopTag; + this.endText = stopText; + this.commented = commented; + this.commentStart = commented ? "" : ""; + } + buildContentString(content) { + return `${this.commentStart} ${this.startTag} ${this.startText} ${this.commentEnd} +${content} +${this.commentStart} ${this.endTag} ${this.endText} ${this.commentEnd}`; + } +}; +var FileService = class { + async createFolder(folderPath, app) { + if (await app.vault.adapter.exists((0, import_obsidian.normalizePath)(folderPath)) == false) + await app.vault.createFolder(folderPath); + } + async saveFile(filePath, content, app) { + return app.vault.create(filePath, content); + } + async updateFile(file, updatedContent, seperator, app) { + return app.vault.process(file, (oldContent) => { + let oldLines = oldContent.split("\n"); + let startIndex = oldLines.findIndex((line) => line.contains(seperator.startTag)); + let stopIndex = oldLines.findIndex((line) => line.contains(seperator.endTag)); + let newLines = Array(); + for (let i = Math.min(0, startIndex); i < oldLines.length; i++) { + if (i == startIndex) { + newLines.push(updatedContent); + i = stopIndex; + continue; + } + newLines.push(oldLines[i]); + } + return newLines.join("\n"); + }); + } +}; + +// src/main.ts +var SettingTab = class extends import_obsidian2.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + new import_obsidian2.Setting(containerEl).setName("Contacts folder").setDesc("Select the folder in which your contacts will stored").addText((text) => text.setPlaceholder("Contacts").setValue(this.plugin.settings.contactsFolder).onChange(async (value) => { + this.plugin.settings.contactsFolder = value; + await this.plugin.saveSettings(); + })); + new import_obsidian2.Setting(containerEl).setName("Contacts group").setDesc('Enter the name of the group ("Smart List") in which your contacts are stored in the MacOS Contacts app').addText((text) => text.setPlaceholder("Obsidian").setValue(this.plugin.settings.contactsGroup).onChange(async (value) => { + this.plugin.settings.contactsGroup = value; + await this.plugin.saveSettings(); + })); + new import_obsidian2.Setting(containerEl).setName("Configure the shown contact fields below").setDesc("To update the shown contact fields, re-sync your contacts"); + for (let attribute of VCard.getVCardFields()) { + new import_obsidian2.Setting(containerEl).setName(`${attribute}`).addToggle((toggle) => { + toggle.setValue(this.plugin.settings.enabledContactFields.includes(attribute)); + toggle.onChange(async (value) => { + this.plugin.settings.enabledContactFields = this.toggleEnabledField(attribute, value); + await this.plugin.saveSettings(); + }); + }); + } + } + toggleEnabledField(field, value) { + let enabledFields = this.plugin.settings.enabledContactFields.split(","); + if (value) { + enabledFields.push(field); + } else { + enabledFields = enabledFields.filter((enabledField) => enabledField != field); + } + return enabledFields.join(","); + } +}; +var DEFAULT_SETTINGS = { + contactsGroup: "Obsidian", + contactsFolder: "Contacts", + autogenerationStartTag: "START", + autogenerationStartText: "Content BELOW this line is AUTOGENERATED and will be REPLACED.", + autogenerationEndTag: "END", + autogenerationEndText: "Content ABOVE this line is AUTOGENERATED and will be REPLACED.", + enabledContactFields: "nickname,emails,title,organization,telephones,addresses,birthdate,URLs,notes" +}; +var ContactsPlugin = class extends import_obsidian2.Plugin { + async onload() { + await this.loadSettings(); + this.addCommand({ + id: "sync-contacts", + name: "Sync contacts", + callback: async () => { + if (!import_obsidian2.Platform.isMacOS) + return new import_obsidian2.Notice("Error: This plugin only works on MacOS"); + new import_obsidian2.Notice("Syncing..."); + let loadContactsLogic = new ContactsService(this.settings.contactsGroup, this.settings.enabledContactFields); + let numContactsPromise = loadContactsLogic.getNumberOfContacts().then((numContacts2) => { + new import_obsidian2.Notice(`Found ${numContacts2} Contacts in group ${this.settings.contactsGroup}`); + return numContacts2; + }); + let fileService = new FileService(); + let createFolderPromise = fileService.createFolder(this.settings.contactsFolder, this.app); + let contentSeperator = new ContentSeperator( + this.settings.autogenerationStartTag, + this.settings.autogenerationStartText, + this.settings.autogenerationEndTag, + this.settings.autogenerationEndText + ); + let [numContacts, _] = await Promise.all([numContactsPromise, createFolderPromise]); + let markdownResults = await loadContactsLogic.loadContacts(); + let successfulContacts = 0; + let promises = []; + for (let [filename, markdown] of markdownResults) { + let filePath = (0, import_obsidian2.normalizePath)(`${this.settings.contactsFolder}/${filename}.md`); + let file = this.app.vault.getAbstractFileByPath(filePath); + let newContactInfo = contentSeperator.buildContentString(markdown); + if (file instanceof import_obsidian2.TFolder) { + console.error(`Error: ${filePath} is a folder`); + new import_obsidian2.Notice(`Error: ${filePath} is a folder`); + } else if (file === null) { + promises.push( + fileService.saveFile(filePath, newContactInfo, this.app).then((_2) => successfulContacts++).catch((error) => console.error(`Error syncing ${filename} +${error}`)) + ); + } else if (file instanceof import_obsidian2.TFile) { + promises.push( + // extract the old contact info and replace it with the new data + fileService.updateFile(file, newContactInfo, new ContentSeperator(this.settings.autogenerationStartTag, this.settings.autogenerationStartText, this.settings.autogenerationEndTag, this.settings.autogenerationEndText), this.app).then((_2) => successfulContacts++).catch((error) => console.error(`Error syncing ${filename} +${error}`)) + ); + } + } + await Promise.all(promises).catch((error) => { + new import_obsidian2.Notice("Error syncing contacts!"); + console.error(error); + }).finally(() => { + new import_obsidian2.Notice(`Successfully synced ${successfulContacts} of ${numContacts} Contacts`); + console.info(`Successfully synced ${successfulContacts} of ${numContacts} Contacts`); + }); + } + }); + this.addSettingTab(new SettingTab(this.app, this)); + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + async saveSettings() { + await this.saveData(this.settings); + } +}; + +/* nosourcemap */ \ No newline at end of file diff --git a/.obsidian/plugins/sync-contacts-macos/manifest.json b/.obsidian/plugins/sync-contacts-macos/manifest.json new file mode 100644 index 00000000..e8a90b71 --- /dev/null +++ b/.obsidian/plugins/sync-contacts-macos/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "sync-contacts-macos", + "name": "Sync Contacts on macOS", + "version": "1.0.6", + "minAppVersion": "0.15.0", + "description": "Sync your contacts from macOS to your Obsidian Vault.", + "author": "Marcel Schöckel", + "authorUrl": "https://twitter.com/marcelschoeckel", + "fundingUrl": "https://www.buymeacoffee.com/motschel", + "isDesktopOnly": true +} \ No newline at end of file