You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10 lines
37 KiB

/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var re=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Fe=Object.prototype.hasOwnProperty;var Se=(m,t)=>{for(var e in t)re(m,e,{get:t[e],enumerable:!0})},xe=(m,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Te(t))!Fe.call(m,i)&&i!==e&&re(m,i,{get:()=>t[i],enumerable:!(n=Ce(t,i))||n.enumerable});return m};var Ie=m=>xe(re({},"__esModule",{value:!0}),m);var Le={};Se(Le,{default:()=>se});module.exports=Ie(Le);var be=require("obsidian");var A=require("obsidian");var J=class{constructor(){this.values=new Map}put(t,e){this.values.set(t,e)}get(t,e){var n;return(n=this.values.get(t))!=null?n:e}getFirst(t,e){for(let n=0;n<t.length;n++){let i=t[n];if(this.containsKey(i))return this.get(i,e)}return e}containsKey(t){return this.values.has(t)}getKeys(){return Array.from(this.values.keys())}removeKey(t){return this.values.delete(t)}clear(){this.values.clear()}};var oe=require("obsidian"),V=class{static getFilePathWithNewExtension(t,e){return(0,oe.normalizePath)(t.parent.path+"/"+t.basename+"."+e)}static getFilePathExcludingExtension(t){return(0,oe.normalizePath)(t.parent.path+"/"+t.basename)}};var d=class{static setActive(t){d.isActive=t,d.isActive||this.clear()}static setAutoExpire(t){d.baseMinutesToExpire=t!=null?t:0,d.updateExpiryTime()}static setLevel(t){d.level!=t&&(d.allLevels.contains(t)&&(d.level=t),d.level=d.LevelFilename,this.clear())}static updateExpiryTime(){d.baseMinutesToExpire==0||d.baseMinutesToExpire==null?d.expiryTime=null:d.expiryTime=Date.now()+d.baseMinutesToExpire*1e3*60}static putByFile(t,e){if(!d.isActive)return;let n=d.getFileCacheKey(e);this.cache.put(n,t),d.updateExpiryTime()}static getByFile(t){if(!d.isActive)return d.blankPasswordAndHint;this.clearIfExpired(),d.updateExpiryTime();let e=d.getFileCacheKey(t);return this.cache.get(e,d.blankPasswordAndHint)}static putByPath(t,e){if(!d.isActive)return;let n=d.getPathCacheKey(e);this.cache.put(n,t),d.updateExpiryTime()}static getByPath(t){if(!d.isActive)return d.blankPasswordAndHint;this.clearIfExpired(),d.updateExpiryTime();let e=d.getPathCacheKey(t);return this.cache.get(e,d.blankPasswordAndHint)}static getPathCacheKey(t){let e=t.split("/").slice(0,-1).join("/");switch(d.level){case d.LevelParentPath:return e;default:return t}}static getFileCacheKey(t){switch(d.level){case d.LevelParentPath:return t.parent.path;default:return V.getFilePathExcludingExtension(t)}}static clearIfExpired(){d.expiryTime!=null&&(Date.now()<d.expiryTime||this.clear())}static clearForFile(t){let e=d.getFileCacheKey(t);this.cache.removeKey(e)}static clearForPath(t){let e=d.getPathCacheKey(t);this.cache.removeKey(e)}static clear(){this.cache.clear()}},h=d;h.isActive=!0,h.blankPasswordAndHint={password:"",hint:""},h.cache=new J,h.baseMinutesToExpire=0,h.expiryTime=null,h.LevelFilename="filename",h.LevelParentPath="parentPath",h.allLevels=[d.LevelFilename,d.LevelParentPath],h.level=d.LevelFilename;var _=class extends A.PluginSettingTab{constructor(e,n,i,s){super(e,n);this.plugin=n,this.settings=i,this.features=s}display(){let{containerEl:e}=this;e.empty(),e.createEl("h1",{text:"Settings for Meld Encrypt"}),new A.Setting(e).setHeading().setName("Common Settings"),new A.Setting(e).setName("Confirm password?").setDesc("Confirm password when encrypting. (Recommended)").addToggle(r=>{r.setValue(this.settings.confirmPassword).onChange(async o=>{this.settings.confirmPassword=o,await this.plugin.saveSettings()})});let n=()=>{if(!this.settings.rememberPassword){i.settingEl.hide(),s.settingEl.hide();return}i.settingEl.show(),s.settingEl.show();let r=this.settings.rememberPasswordTimeout,o=`For ${r} minutes`;r==0&&(o="Until Obsidian is closed"),i.setName(`Remember Password (${o})`)};new A.Setting(e).setName("Remember password?").setDesc("Remember the last used passwords when encrypting or decrypting. Passwords are remembered until they timeout or Obsidian is closed").addToggle(r=>{r.setValue(this.settings.rememberPassword).onChange(async o=>{this.settings.rememberPassword=o,await this.plugin.saveSettings(),h.setActive(this.settings.rememberPassword),n()})});let i=new A.Setting(e).setDesc("The number of minutes to remember passwords.").addSlider(r=>{r.setLimits(0,120,5).setValue(this.settings.rememberPasswordTimeout).onChange(async o=>{this.settings.rememberPasswordTimeout=o,await this.plugin.saveSettings(),h.setAutoExpire(this.settings.rememberPasswordTimeout),n()})}),s=new A.Setting(e).setDesc("Remember passwords by using a notes file name or parent folder").addDropdown(r=>{r.addOption(h.LevelFilename,"File Name").addOption(h.LevelParentPath,"Parent Folder").setValue(this.settings.rememberPasswordLevel).onChange(async o=>{this.settings.rememberPasswordLevel=o,await this.plugin.saveSettings(),h.setLevel(this.settings.rememberPasswordLevel),n()})});n(),this.features.forEach(r=>{r.buildSettingsUi(e,async()=>await this.plugin.saveSettings())})}};var F=require("obsidian");var k=require("obsidian"),R=class extends k.Modal{constructor(e,n,i=""){super(e);this.decryptInPlace=!1;this.canDecryptInPlace=!0;this.titleEl.setText(n),this.text=i}onOpen(){var r;let{contentEl:e}=this;e.empty(),e.classList.add("meld-encrypt-decrypt-modal");let n;(r=new k.Setting(e).addTextArea(o=>{n=o,o.setValue(this.text),o.inputEl.setSelectionRange(0,0),o.inputEl.readOnly=!0,o.inputEl.rows=10}).settingEl.querySelector(".setting-item-info"))==null||r.remove();let s=new k.Setting(e);s.addButton(o=>{o.setButtonText("Copy").onClick(a=>{navigator.clipboard.writeText(n.getValue()),new k.Notice("Copied!")})}),this.canDecryptInPlace&&s.addButton(o=>{o.setWarning().setButtonText("Decrypt in-place").onClick(a=>{this.decryptInPlace=!0,this.close()})})}};var P=require("obsidian");var K=require("obsidian"),E=class{static isSettingsModalOpen(){return document.querySelector(".mod-settings")!==null}static buildPasswordSetting({container:t,name:e,desc:n="",autoFocus:i=!1,placeholder:s="",initialValue:r="",onChangeCallback:o,onEnterCallback:a}){let u=new K.Setting(t).setName(e).setDesc(n).addButton(g=>{g.setIcon("reading-glasses").onClick(p=>{let c=u.components.find((l,f,w)=>l instanceof K.TextComponent);c instanceof K.TextComponent&&(c.inputEl.type=c.inputEl.type=="password"?"text":"password")})}).addText(g=>{g.setPlaceholder(s),g.setValue(r),g.inputEl.type="password",o!=null&&g.onChange(o),a!=null&&(g.inputEl.onkeydown=p=>{p.key==="Enter"&&(p.preventDefault(),a(g.getValue()))}),i&&setTimeout(()=>g.inputEl.focus(),0)});return u}};var H=class extends P.Modal{constructor(e,n,i,s,r=null,o=null){super(e);this.defaultPassword=null;this.resultConfirmed=!1;this.resultPassword=null;this.resultShowInReadingView=null;this.defaultPassword=r,this.confirmPassword=i,this.showInReadingView=s,this.isEncrypting=n,this.defaultHint=o!=null?o:""}onOpen(){var p;let{contentEl:e}=this;e.empty(),this.invalidate();let n=(p=this.defaultPassword)!=null?p:"",i="",s=this.defaultHint,r=this.showInReadingView;new P.Setting(e).setHeading().setName(this.isEncrypting?"Encrypting":"Decrypting"),E.buildPasswordSetting({container:e,name:"Password:",placeholder:this.isEncrypting||s.length==0?"":`Hint: ${s}`,initialValue:n,autoFocus:!0,onChangeCallback:c=>{n=c,this.invalidate()},onEnterCallback:c=>{if(n=c,this.invalidate(),n.length>0)if(o.settingEl.isShown()){let l=o.components.find(f=>f instanceof P.TextComponent);l instanceof P.TextComponent&&l.inputEl.focus()}else if(a.settingEl.isShown()){let l=a.components.find(f=>f instanceof P.TextComponent);l instanceof P.TextComponent&&l.inputEl.focus()}else g()&&this.close()}});let o=E.buildPasswordSetting({container:e,name:"Confirm Password:",onChangeCallback:c=>{i=c,this.invalidate()},onEnterCallback:c=>{if(i=c,this.invalidate(),i.length>0&&g()&&a.settingEl.isShown()){let l=a.components.find(f=>f instanceof P.TextComponent);l instanceof P.TextComponent&&l.inputEl.focus()}}});this.confirmPassword||o.settingEl.hide();let a=new P.Setting(e).setName("Optional Password Hint").addText(c=>{c.inputEl.placeholder="Password Hint",c.setValue(s),c.onChange(l=>s=l),c.inputEl.on("keypress","*",(l,f)=>{l.key=="Enter"&&f instanceof HTMLInputElement&&f.value.length>0&&(l.preventDefault(),g()&&this.close())})});this.isEncrypting||a.settingEl.hide();let u=new P.Setting(e).setName("Show encrypted marker in Reading view").addToggle(c=>{c.setValue(r).onChange(l=>{r=l})});this.isEncrypting||u.settingEl.hide(),new P.Setting(e).addButton(c=>{c.setButtonText("Confirm").onClick(l=>{g()&&this.close()})});let g=()=>(this.invalidate(),o.setDesc(""),this.confirmPassword&&n!=i?(o.setDesc("Passwords don't match"),!1):(this.resultConfirmed=!0,this.resultPassword=n,this.resultHint=s,this.resultShowInReadingView=r,!0))}invalidate(){this.resultConfirmed=!1,this.resultPassword=null,this.resultHint=""}};var ae=new TextEncoder,De=new TextDecoder,Ae=1e3,Ne=ae.encode("XHWnDAT6ehMVY2zD"),W=class{async deriveKey(t){let e=ae.encode(t),n=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",hash:{name:"SHA-256"},iterations:Ae,salt:Ne},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encryptToBytes(t,e){let n=await this.deriveKey(e),i=ae.encode(t),s=crypto.getRandomValues(new Uint8Array(16)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},n,i)),o=new Uint8Array(s.byteLength+r.byteLength);return o.set(s,0),o.set(r,s.byteLength),o}convertToString(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e}async encryptToBase64(t,e){let n=await this.encryptToBytes(t,e);return btoa(this.convertToString(n))}stringToArray(t){let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));return new Uint8Array(e)}async decryptFromBytes(t,e){try{let n=t.slice(0,16),i=t.slice(16),s=await this.deriveKey(e),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},s,i);return De.decode(r)}catch(n){return null}}async decryptFromBase64(t,e){try{let n=this.stringToArray(atob(t));return await this.decryptFromBytes(n,e)}catch(n){return null}}};var B=class{constructor(t,e,n){this.vectorSize=t,this.saltSize=e,this.iterations=n}async deriveKey(t,e){let i=new TextEncoder().encode(t),s=await crypto.subtle.importKey("raw",i,"PBKDF2",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",hash:"SHA-512",salt:e,iterations:this.iterations},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encryptToBytes(t,e){let n=crypto.getRandomValues(new Uint8Array(this.saltSize)),i=await this.deriveKey(e,n),r=new TextEncoder().encode(t),o=crypto.getRandomValues(new Uint8Array(this.vectorSize)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o},i,r)),u=new Uint8Array(o.byteLength+n.byteLength+a.byteLength);return u.set(o,0),u.set(n,o.byteLength),u.set(a,o.byteLength+n.byteLength),u}convertToString(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e}async encryptToBase64(t,e){let n=await this.encryptToBytes(t,e);return btoa(this.convertToString(n))}stringToArray(t){let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));return new Uint8Array(e)}async decryptFromBytes(t,e){try{let n,i;n=0,i=n+this.vectorSize;let s=t.slice(n,i);n=i,i=n+this.saltSize;let r=t.slice(n,i);n=i,i=void 0;let o=t.slice(n),a=await this.deriveKey(e,r),u=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},a,o);return new TextDecoder().decode(u)}catch(n){return null}}async decryptFromBase64(t,e){try{let n=this.stringToArray(atob(t));return await this.decryptFromBytes(n,e)}catch(n){return null}}};var ce={name:"AES-GCM",iv:new Uint8Array([196,190,240,190,188,78,41,132,15,220,84,211]),tagLength:128},Q=class{async buildKey(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest({name:"SHA-256"},n);return await crypto.subtle.importKey("raw",i,ce,!1,["encrypt","decrypt"])}async encryptToBase64(t,e){let n=await this.buildKey(e),s=new TextEncoder().encode(t),r=new Uint8Array(await crypto.subtle.encrypt(ce,n,s));return btoa(String.fromCharCode(...r))}stringToArray(t){let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));return new Uint8Array(e)}async decryptFromBase64(t,e){try{let n=this.stringToArray(atob(t)),i=await this.buildKey(e),s=await crypto.subtle.decrypt(ce,i,n);return new TextDecoder().decode(s)}catch(n){return null}}};var C=class{static BuildDefault(){return new B(16,16,21e4)}static BuildFromFileDataOrThrow(t){let e=C.BuildFromFileDataOrNull(t);if(e!=null)return e;throw new Error(`Unable to determine ICryptoHelper for File ver ${t.version}`)}static BuildFromFileDataOrNull(t){return t.version=="1.0"?new W:t.version=="2.0"?new B(16,16,21e4):null}static BuildFromDecryptableOrThrow(t){let e=C.BuildFromDecryptableOrNull(t);if(e!=null)return e;throw new Error(`Unable to determine ICryptoHelper for Decryptable ver ${t.version}`)}static BuildFromDecryptableOrNull(t){return t.version==0?new Q:t.version==1?new W:t.version==2?new B(16,16,21e4):null}};var Z=class{};var ee="%%\u{1F510}\u03B2 ",te="\u{1F510}\u03B2 ",le="%%\u{1F510}\u03B1 ",de="\u{1F510}\u03B1 ",pe="%%\u{1F510} ",Ee=ee,Pe=te,D=[ee,te,le,de,pe],ue=" \u{1F510}%%",he=" \u{1F510}",M=[ue,he],T="\u{1F4A1}";var X=class{constructor(t){this.process(t)}process(t){var e,n;if(this.processedText=t,this.isEmpty=t.length===0,this.prefix=(e=D.find(i=>t.startsWith(i)))!=null?e:"",this.suffix=(n=M.find(i=>t.endsWith(i)))!=null?n:"",this.hasEncryptedPrefix=this.prefix.length>0,this.hasEncryptedSuffix=this.suffix.length>0,this.hasObsoleteEncryptedPrefix=this.prefix===pe,this.containsEncryptedMarkers=[...D,...M].some(i=>t.includes(i)),this.canDecrypt=this.hasEncryptedPrefix&&this.hasEncryptedSuffix,this.canEncrypt=!this.hasEncryptedPrefix&&!this.containsEncryptedMarkers,this.canDecrypt){let i=this.parseDecryptableContent(t);i!=null?this.decryptable=i:this.canDecrypt=!1}}parseDecryptableContent(t){let e=new Z;if(!this.hasEncryptedPrefix||!this.hasEncryptedSuffix)return null;this.hasObsoleteEncryptedPrefix?e.version=0:this.prefix==ee||this.prefix==te?e.version=2:(this.prefix==le||this.prefix==de)&&(e.version=1);let n=t.substring(this.prefix.length,t.length-this.suffix.length);if([...D,...M].some(i=>n.includes(i)))return null;if(n.substring(0,T.length)==T){let i=n.indexOf(T,T.length);if(i<0)return null;e.hint=n.substring(T.length,i),e.base64CipherText=n.substring(i+T.length)}else e.base64CipherText=n;return e}};var Y=class{async onload(t,e){this.plugin=t,this.pluginSettings=e,this.featureSettings=e.featureInplaceEncrypt,this.plugin.registerMarkdownPostProcessor((n,i)=>this.processEncryptedCodeBlockProcessor(n,i)),t.addCommand({id:"meld-encrypt",name:"Encrypt/Decrypt",icon:"lock",editorCheckCallback:(n,i,s)=>this.processEncryptDecryptCommand(n,i,!1)}),t.addCommand({id:"meld-encrypt-in-place",name:"Encrypt/Decrypt In-place",icon:"lock",editorCheckCallback:(n,i,s)=>this.processEncryptDecryptCommand(n,i,!0)})}onunload(){}replaceMarkersRecursive(t){if(t instanceof HTMLElement){t.childNodes.forEach(e=>this.replaceMarkersRecursive(e));return}if(t instanceof Text){let e=t.textContent;if(e==null||!e.contains("\u{1F510}"))return;let n=t.parentElement;if(n==null)return;let i=/🔐(.*?)🔐/g;n.removeChild(t);for(let s of e.matchAll(i))n.createSpan({cls:"meld-encrypt-inline-reading-marker",text:"\u{1F510}",attr:{"data-meld-encrypt-encrypted":s[0]}})}}async processEncryptedCodeBlockProcessor(t,e){this.replaceMarkersRecursive(t);let n=t.querySelectorAll(".meld-encrypt-inline-reading-marker");this.bindReadingIndicatorEventHandlers(e.sourcePath,n)}bindReadingIndicatorEventHandlers(t,e){e.forEach(n=>{let i=n;i!=null&&i.onClickEvent(async s=>{let r=s.target;if(r==null)return;let o=r.dataset.meldEncryptEncrypted;if(o==null)return;let a=new X(o);await this.handleReadingIndicatorClick(t,a.decryptable)})})}async handleReadingIndicatorClick(t,e){if(e==null){new F.Notice("\u274C Decryption failed!");return}if(await this.showDecryptedTextIfPasswordKnown(t,e))return;let n=await this.fetchPasswordFromUser(e.hint);n!=null&&(await this.showDecryptedResultForPassword(e,n)?h.putByPath({password:n,hint:e.hint},t):new F.Notice("\u274C Decryption failed!"))}async showDecryptedResultForPassword(t,e){let i=await C.BuildFromDecryptableOrThrow(t).decryptFromBase64(t.base64CipherText,e);return i===null?!1:new Promise(s=>{let r=new R(this.plugin.app,"\u{1F513}",i);r.canDecryptInPlace=!1,r.onClose=()=>{s(!0)},r.open()})}async fetchPasswordFromUser(t){return new Promise(e=>{let n=new H(this.plugin.app,!1,!1,this.featureSettings.showMarkerWhenReadingDefault,"",t);n.onClose=()=>{e(n.resultPassword)},n.open()})}async showDecryptedTextIfPasswordKnown(t,e){let n=h.getByPath(t);return n.password==null?!1:await this.showDecryptedResultForPassword(e,n.password)}buildSettingsUi(t,e){new F.Setting(t).setHeading().setName("In-place Encryption Settings"),new F.Setting(t).setName("Expand selection to whole line?").setDesc("Partial selections will get expanded to the whole line.").addToggle(n=>{n.setValue(this.featureSettings.expandToWholeLines).onChange(async i=>{this.featureSettings.expandToWholeLines=i,await e()})}),new F.Setting(t).setName("By default, show encrypted marker when reading").setDesc("When encrypting inline text, should the default be to have a visible marker in Reading view?").addToggle(n=>{n.setValue(this.featureSettings.showMarkerWhenReadingDefault).onChange(async i=>{this.featureSettings.showMarkerWhenReadingDefault=i,await e()})})}processEncryptDecryptCommand(t,e,n){if(t&&E.isSettingsModalOpen())return!0;let i=e.getCursor("from"),s=e.getCursor("to");if(this.featureSettings.expandToWholeLines){i={line:i.line,ch:0};let a=s.line,u=e.getLine(a);s={line:a,ch:u.length}}else if(!e.somethingSelected()){let o=this.getClosestPrefixCursorPos(e);if(o==null)return!1;i=o;let a=this.getClosestSuffixCursorPos(e);if(a==null)return!1;s=a}let r=e.getRange(i,s);return this.processSelection(t,e,r,i,s,n)}getClosestPrefixCursorPos(t){let e=D.reduce((i,s,r)=>r==0||s.length>i.length?s:i),n=t.posToOffset(t.getCursor("from"))+e.length;for(let i=n;i>=0;i--){let s=t.offsetToPos(i);for(let r of D){let o=i-r.length,a=t.offsetToPos(o);if(t.getRange(a,s)==r)return t.offsetToPos(o)}}return null}getClosestSuffixCursorPos(t){let e=D.reduce((r,o,a)=>a==0||o.length>r.length?o:r),n=t.posToOffset(t.getCursor("from"))-e.length+1,i=t.lastLine(),s=t.posToOffset({line:i,ch:t.getLine(i).length});for(let r=n;r<=s;r++){let o=t.offsetToPos(r);for(let a of M){let u=r+a.length,g=t.offsetToPos(u);if(t.getRange(o,g)==a)return g}}return null}processSelection(t,e,n,i,s,r,o=!0){var f;let a=new X(n);if(a.isEmpty)return t||new F.Notice("Nothing to Encrypt."),!1;if(!a.canDecrypt&&!a.canEncrypt)return t||new F.Notice("Unable to Encrypt or Decrypt that."),!1;if(a.canEncrypt&&!o)return!1;let u=this.plugin.app.workspace.getActiveFile();if(u==null)return!1;if(t)return!0;let g="",p=(f=a.decryptable)==null?void 0:f.hint;if(this.pluginSettings.rememberPassword){let w=h.getByPath(u.path);g=w.password,p=p!=null?p:w.hint}let c=a.canEncrypt&&this.pluginSettings.confirmPassword,l=new H(this.plugin.app,a.canEncrypt,c,this.featureSettings.showMarkerWhenReadingDefault,g,p);return l.onClose=async()=>{var me,we,ye;if(!l.resultConfirmed)return;let w=(me=l.resultPassword)!=null?me:"",L=(we=l.resultHint)!=null?we:"";if(a.canEncrypt){let j=new ge;j.text=n,j.hint=L,this.encryptSelection(e,j,w,i,s,(ye=l.resultShowInReadingView)!=null?ye:this.featureSettings.showMarkerWhenReadingDefault),h.putByPath({password:w,hint:L},u.path)}else a.decryptable&&await this.decryptSelection(e,a.decryptable,w,i,s,r)&&h.putByPath({password:w,hint:L},u.path)},l.open(),!0}async encryptSelection(t,e,n,i,s,r){let o=C.BuildDefault(),a=this.encodeEncryption(await o.encryptToBase64(e.text,n),e.hint,r);t.setSelection(i,s),t.replaceSelection(a)}async decryptSelection(t,e,n,i,s,r){let a=await C.BuildFromDecryptableOrThrow(e).decryptFromBase64(e.base64CipherText,n);if(a===null)return new F.Notice("\u274C Decryption failed!"),!1;if(r)t.setSelection(i,s),t.replaceSelection(a);else{let u=new R(this.plugin.app,"\u{1F513}",a);u.onClose=()=>{t.focus(),u.decryptInPlace&&(t.setSelection(i,s),t.replaceSelection(a))},u.open()}return!0}encodeEncryption(t,e,n){if(!D.some(i=>t.includes(i))&&!M.some(i=>t.includes(i))){let i=n?Pe:Ee,s=n?he:ue;return e.length>0?i.concat(T,e,T,t,s):i.concat(t,s)}return t}},ge=class{};var I=require("obsidian");var y=require("obsidian");var O=class{static get showInlineTitle(){var t;return(t=app.vault.getConfig("showInlineTitle"))!=null?t:!0}static get readableLineLength(){var t;return(t=app.vault.getConfig("readableLineLength"))!=null?t:!0}};var ne=class{constructor(t,e,n){this.version="1.0";this.version=t,this.hint=e,this.encodedData=n}},fe=class{static async encode(t,e,n){let s=await C.BuildDefault().encryptToBase64(n,t);return new ne(fe.DEFAULT_VERSION,e,s)}static async decrypt(t,e){return t.encodedData==""?"":await C.BuildFromFileDataOrThrow(t).decryptFromBase64(t.encodedData,e)}},S=fe;S.DEFAULT_VERSION="2.0";var x=class{static encode(t){return JSON.stringify(t,null,2)}static decode(t){return t===""?new ne(S.DEFAULT_VERSION,"",""):JSON.parse(t)}};var ke="encrypted",ve="mdenc",ie=ve,N=[ve,ke];var $="meld-encrypted-file-content-view",z=class extends y.TextFileView{constructor(e,n){var i;super(e);this.iconReadingView="book-open";this.iconSourceView="code";this.iconToggleEditView="edit";this.iconLockFile="lock";this.iconChangePassword="key";this.currentView=0;this.encryptionPassword="";this.hint="";this.currentEditorSourceText="";this.settings=n,this.defaultEditNoteView=(i=n.defaultView)!=null?i:"Source",this.currentEditNoteMode=this.defaultEditNoteView,this.elActionEditView=this.addAction(this.iconSourceView,"Source",()=>this.toggleReadingView()),this.elActionReadingView=this.addAction(this.iconReadingView,"Reading",()=>this.toggleReadingView()),this.elActionIconLockNote=this.addAction(this.iconLockFile,"Lock",()=>this.actionLockFile()),this.elActionChangePassword=this.addAction(this.iconChangePassword,"Change Password",()=>this.actionChangePassword()),this.elActionEditView.hide(),this.elActionReadingView.hide(),this.elActionIconLockNote.hide(),this.elActionChangePassword.hide(),this.containerEl.classList.add("meld-encrypt-encrypted-note-view"),this.contentEl.classList.add("meld-encrypt-encrypted-note-view-content")}toggleReadingView(){this.currentView==2&&(this.currentEditNoteMode=="Reading"?this.currentEditNoteMode="Source":this.currentEditNoteMode=="Source"&&(this.currentEditNoteMode="Reading"),this.refreshView(2))}actionLockFile(){this.encryptionPassword="",h.clearForFile(this.file),this.refreshView(1)}actionChangePassword(){this.refreshView(3)}onPaneMenu(e,n){n=="tab-header"&&this.currentView==2&&(e.addItem(i=>{i.setSection("action").setIcon(this.iconToggleEditView).setTitle("Toggle Editing/Reading").onClick(()=>this.toggleReadingView())}),e.addItem(i=>{i.setSection("action").setIcon(this.iconLockFile).setTitle("Lock").onClick(()=>this.actionLockFile())}),e.addItem(i=>{i.setSection("action").setIcon(this.iconChangePassword).setTitle("Change Password").onClick(()=>this.actionChangePassword())})),super.onPaneMenu(e,n)}addHeader(e,n){var i;e.createDiv({text:`\u{1F510} ${n} \u{1F510}`,cls:"encrypted-note-message"}),O.showInlineTitle&&e.createDiv({text:(i=this.file)==null?void 0:i.basename,cls:"inline-title"})}validatePassword(e){return""}validateConfirm(e,n){return e===n?"":"Password doesn't match"}addNewNoteView(e){this.addHeader(e,"This note will be encrypted");let n=this.addUserInputContainer(e);new y.Setting(n).setDesc("Please provide a password and hint to start editing this note.");let i=async(c,l,f)=>{let w=this.validatePassword(c),L=this.validateConfirm(c,l);u.setDesc(w),g.setDesc(L),w.length===0&&L.length===0&&(this.encryptionPassword=c,this.hint=f,O.showInlineTitle||(this.currentEditorSourceText=`# ${this.file.basename}
`),await this.encodeAndSave(),h.putByFile({password:c,hint:f},this.file),this.currentEditNoteMode="Source",this.refreshView(2))},s=h.getByFile(this.file),r=s.password,o="",a=s.hint,u=E.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,initialValue:r,onChangeCallback:c=>{r=c,u.setDesc(this.validatePassword(r)),g.setDesc(this.validateConfirm(r,o))},onEnterCallback:c=>{var l;r=c,r.length>0&&((l=g.controlEl.querySelector("input"))==null||l.focus())}}),g=E.buildPasswordSetting({container:n,name:"Confirm:",autoFocus:!1,onChangeCallback:c=>{o=c,u.setDesc(this.validatePassword(r)),g.setDesc(this.validateConfirm(r,o))},onEnterCallback:c=>{var f;o=c,r===o&&((f=p.controlEl.querySelector("input"))==null||f.focus())}}),p=new y.Setting(n).setName("Hint:").addText(c=>{c.setValue(a),c.onChange(l=>{a=l})});p.controlEl.on("keydown","*",c=>{c.key==="Enter"&&(c.preventDefault(),i(r,o,a))}),new y.Setting(n).addButton(c=>{c.setCta().setIcon("go-to-file").setTooltip("Edit").onClick(l=>i(r,o,a))})}addDecryptNoteView(e){this.addHeader(e,"This note is encrypted");let n=this.addUserInputContainer(e);new y.Setting(n).setDesc("Please provide a password to unlock this note.");let i=E.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,placeholder:this.formatHint(this.hint),onChangeCallback:r=>{this.encryptionPassword=r,i.setDesc(this.validatePassword(this.encryptionPassword))},onEnterCallback:async()=>await this.handleDecryptButtonClick()});new y.Setting(n).addButton(r=>{r.setCta().setIcon("checkmark").setTooltip("Unlock & Edit").onClick(o=>this.handleDecryptButtonClick())});let s=h.getByFile(this.file);this.encryptionPassword=s.password,s.password.length>0&&this.decryptWithPassword(s.password).then(r=>{r!=null&&(this.currentEditorSourceText=r,this.refreshView(2),new y.Notice("Decrypted using remembered password",2e3))})}async encodeAndSave(){try{let e=await S.encode(this.encryptionPassword,this.hint,this.currentEditorSourceText);this.data=x.encode(e),this.requestSave()}catch(e){console.error(e),new y.Notice(e,1e4)}}addEditorSourceView(e){this.elActionReadingView.show(),this.elActionIconLockNote.show(),this.elActionChangePassword.show(),this.addHeader(e,"Editing an encrypted note");let n=e.createDiv({cls:"editor-source-view"},i=>{i.spellcheck=!0,i.autocapitalize="on",i.translate=!1,i.contentEditable="plaintext-only",i.style.tabSize="4",i.innerText=this.currentEditorSourceText});n.focus(),n.on("keydown","*",(i,s)=>{i.key=="Tab"&&this.handleTabInEditor(i,n)}),n.on("input","*",async(i,s)=>{this.updateAndSaveEditorSourceText(n)})}async updateAndSaveEditorSourceText(e){this.currentEditorSourceText=e.innerText,await this.encodeAndSave()}handleTabInEditor(e,n){let i=window.getSelection();if(i==null||i.rangeCount<1)return;e.preventDefault();let s=!e.shiftKey;for(let r=0;r<i.rangeCount;r++){let o=i.getRangeAt(r),a=this.getRangeNodes(o);for(let u=0;u<a.length;u++){let g=a[u];g instanceof Text&&(s?g.insertData(0," "):g.data.startsWith(" ")&&g.replaceData(0,1,""))}}this.updateAndSaveEditorSourceText(n)}getRangeNodes(e){let n=Array();if(e.startContainer==e.endContainer)return[e.startContainer];let i=e.startContainer;for(i==e.commonAncestorContainer&&(i=e.commonAncestorContainer.firstChild);i!=null;)e.intersectsNode(i)&&n.push(i),i=i.nextSibling;return n}addEditorReadingView(e){this.elActionEditView.show(),this.elActionIconLockNote.show(),this.elActionChangePassword.show(),this.addHeader(e,"Reading an encrypted note");let n=e.createDiv({cls:"editor-reading-view"});y.MarkdownRenderer.renderMarkdown(this.currentEditorSourceText,n,this.file.path,this).catch(i=>{console.error(i)})}addUserInputContainer(e){return e.createDiv({cls:"input-container"})}addChangePasswordView(e){this.addHeader(e,"Change encrypted note password");let n=this.addUserInputContainer(e),i="",s="",r="",o=async(p,c,l)=>{let f=this.validatePassword(p),w=this.validateConfirm(p,c);a.setDesc(f),u.setDesc(w),f.length===0&&w.length===0&&(this.encryptionPassword=p,this.hint=l,this.encodeAndSave(),this.refreshView(2),h.putByFile({password:p,hint:l},this.file),new y.Notice("Password and Hint were changed"))},a=E.buildPasswordSetting({container:n,name:"New Password:",autoFocus:!0,onChangeCallback:p=>{i=p,a.setDesc(this.validatePassword(i)),u.setDesc(this.validateConfirm(i,s))},onEnterCallback:p=>{var c;i=p,i.length>0&&((c=u.controlEl.querySelector("input"))==null||c.focus())}}),u=E.buildPasswordSetting({container:n,name:"Confirm:",onChangeCallback:p=>{s=p,a.setDesc(this.validatePassword(i)),u.setDesc(this.validateConfirm(i,s))},onEnterCallback:p=>{var l;s=p,i===s&&((l=g.controlEl.querySelector("input"))==null||l.focus())}}),g=new y.Setting(n).setName("New Hint:").addText(p=>{p.onChange(c=>{r=c})});g.controlEl.on("keydown","*",p=>{p.key==="Enter"&&(p.preventDefault(),o(i,s,r))}),new y.Setting(n).addButton(p=>{p.removeCta().setIcon("cross").setTooltip("Cancel").onClick(()=>{this.refreshView(2)})}).addButton(p=>{p.setCta().setIcon("checkmark").setTooltip("Change Password").setWarning().onClick(c=>{o(i,s,r)})})}formatHint(e){return e.length>0?`Hint: ${e}`:""}refreshView(e){this.currentView=e,this.elActionEditView.hide(),this.elActionReadingView.hide(),this.elActionIconLockNote.hide(),this.elActionChangePassword.hide(),this.contentEl.empty(),O.readableLineLength?this.contentEl.classList.add("is-readable-line-width"):this.contentEl.classList.remove("is-readable-line-width");let n=this.contentEl.createDiv({cls:"content-container"});switch(this.currentView){case 4:this.addNewNoteView(n);break;case 1:this.addDecryptNoteView(n);break;case 2:this.currentEditNoteMode=="Source"?this.addEditorSourceView(n):this.addEditorReadingView(n);break;case 3:this.addChangePasswordView(n);break}}async decryptWithPassword(e){let n=x.decode(this.data);return await S.decrypt(n,e)}async handleDecryptButtonClick(){let e=await this.decryptWithPassword(this.encryptionPassword);e===null?new y.Notice("Decryption failed"):(h.putByFile({password:this.encryptionPassword,hint:this.hint},this.file),this.currentEditorSourceText=e,this.refreshView(2))}canAcceptExtension(e){return N.contains(e)}getViewType(){return $}setViewData(e,n){if(n){let i;e===""?i=4:i=1,this.encryptionPassword="";let s=x.decode(this.data);this.hint=s.hint,this.refreshView(i)}else this.leaf.detach(),new y.Notice("Multiple views of the same encrypted note isn't supported")}getViewData(){return this.data}clear(){}};var G=class{async onload(t,e){this.plugin=t,this.settings=e.featureWholeNoteEncrypt,this.plugin.addRibbonIcon("file-lock-2","New encrypted note",n=>{this.processCreateNewEncryptedNoteCommand()}),this.plugin.registerView($,n=>new z(n,this.settings)),this.plugin.registerExtensions(N,$),this.plugin.addCommand({id:"meld-encrypt-create-new-note",name:"Create new encrypted note",icon:"file-lock-2",callback:()=>this.processCreateNewEncryptedNoteCommand()}),this.plugin.addCommand({id:"meld-encrypt-toggle-reading-view",name:"Toggle Reading View",icon:"edit",callback:()=>this.processToggleReadingViewCommand()})}onunload(){this.plugin.app.workspace.detachLeavesOfType($)}processToggleReadingViewCommand(){let t=this.plugin.app.workspace.getActiveViewOfType(z);t==null||t.toggleReadingView()}processCreateNewEncryptedNoteCommand(){try{let t=(0,I.moment)().format(`[Untitled] YYYYMMDD hhmmss[.${ie}]`),e,n=this.plugin.app.workspace.getActiveFile();n!=null?e=this.plugin.app.fileManager.getNewFileParent(n.path):e=this.plugin.app.fileManager.getNewFileParent("");let i=(0,I.normalizePath)(e.path+"/"+t);this.plugin.app.vault.create(i,"").then(async s=>{await this.plugin.app.workspace.getLeaf(!0).openFile(s)}).catch(s=>{new I.Notice(s,1e4)})}catch(t){console.error(t),new I.Notice(t,1e4)}}buildSettingsUi(t,e){new I.Setting(t).setHeading().setName("Whole Note Encryption Settings"),new I.Setting(t).setName("Default view for new tabs").setDesc("The default view that a new encrypted note tab gets opened in").addDropdown(n=>{var i;n.addOption(`${"Source"}`,"Source view").addOption(`${"Reading"}`,"Reading view").setValue(`${(i=this.settings.defaultView)!=null?i:"Source"}`).onChange(async s=>{this.settings.defaultView=s,await e()})})}};var b=require("obsidian");var v=require("obsidian");var U=class extends v.Modal{constructor(e,n,i,s,r){super(e);this.resultConfirmed=!1;this.title=n,this.defaultPassword=r,this.confirmPassword=s,this.isEncrypting=i}onOpen(){var u,g,p,c;let{contentEl:e}=this;e.empty(),this.invalidate();let n=(g=(u=this.defaultPassword)==null?void 0:u.password)!=null?g:"",i="",s=(c=(p=this.defaultPassword)==null?void 0:p.hint)!=null?c:"";new v.Setting(e).setHeading().setName(this.title),E.buildPasswordSetting({container:e,name:"Password:",placeholder:this.isEncrypting?"":`Hint: ${s}`,initialValue:n,autoFocus:n=="",onChangeCallback:l=>{n=l,this.invalidate()},onEnterCallback:l=>{if(n=l,this.invalidate(),n.length>0)if(r.settingEl.isShown()){let f=r.components.find(w=>w instanceof v.TextComponent);f instanceof v.TextComponent&&f.inputEl.focus()}else if(o.settingEl.isShown()){let f=o.components.find(w=>w instanceof v.TextComponent);f instanceof v.TextComponent&&f.inputEl.focus()}else a()&&this.close()}});let r=E.buildPasswordSetting({container:e,name:"Confirm Password:",autoFocus:n!="",onChangeCallback:l=>{i=l,this.invalidate()},onEnterCallback:l=>{if(i=l,this.invalidate(),i.length>0&&a()&&o.settingEl.isShown()){let f=o.components.find(w=>w instanceof v.TextComponent);f instanceof v.TextComponent&&f.inputEl.focus()}}});this.confirmPassword||r.settingEl.hide();let o=new v.Setting(e).setName("Optional Password Hint").addText(l=>{l.inputEl.placeholder="Password Hint",l.setValue(s),l.onChange(f=>s=f),l.inputEl.on("keypress","*",(f,w)=>{f.key=="Enter"&&w instanceof HTMLInputElement&&w.value.length>0&&(f.preventDefault(),a()&&this.close())})});this.isEncrypting||o.settingEl.hide(),new v.Setting(e).addButton(l=>{l.setButtonText("Confirm").onClick(f=>{a()&&this.close()})});let a=()=>(this.invalidate(),r.setDesc(""),this.confirmPassword&&n!=i?(r.setDesc("Passwords don't match"),!1):(this.resultConfirmed=!0,this.resultPassword={password:n,hint:s},!0))}openAsync(){return new Promise((e,n)=>{this.onClose=()=>{this.resultConfirmed==!0?e(this.resultPassword):n()},this.open()})}invalidate(){this.resultConfirmed=!1,this.resultPassword={password:"",hint:""}}};var q=class{async onload(t,e){this.plugin=t,this.plugin.addCommand({id:"meld-encrypt-convert-to-or-from-encrypted-note",name:"Convert to or from an Encrypted note",icon:"file-lock",checkCallback:n=>this.processCommandConvertActiveNote(n)}),this.plugin.addRibbonIcon("file-lock","Convert to or from an Encrypted note",n=>this.processCommandConvertActiveNote(!1)),this.plugin.registerEvent(this.plugin.app.workspace.on("file-menu",(n,i)=>{i instanceof b.TFile&&(i.extension=="md"&&n.addItem(s=>{s.setTitle("Encrypt note").setIcon("file-lock").onClick(()=>this.processCommandEncryptNote(i))}),N.contains(i.extension)&&n.addItem(s=>{s.setTitle("Decrypt note").setIcon("file").onClick(()=>this.processCommandDecryptNote(i))}))}))}onunload(){}buildSettingsUi(t,e){}checkCanEncryptFile(t){return t==null?!1:t.extension=="md"}checkCanDecryptFile(t){return t==null?!1:N.contains(t.extension)}processCommandEncryptNote(t){this.getPasswordAndEncryptFile(t).catch(e=>{e&&new b.Notice(e,1e4)})}processCommandDecryptNote(t){this.getPasswordAndDecryptFile(t).catch(e=>{e&&new b.Notice(e,1e4)})}processCommandConvertActiveNote(t){let e=this.plugin.app.workspace.getActiveFile();if(t)return this.checkCanEncryptFile(e)||this.checkCanDecryptFile(e);(e==null?void 0:e.extension)=="md"&&this.getPasswordAndEncryptFile(e).catch(n=>{n&&new b.Notice(n,1e4)}),e&&N.contains(e.extension)&&this.getPasswordAndDecryptFile(e).catch(n=>{n&&new b.Notice(n,1e4)})}async getPasswordAndEncryptFile(t){if(!this.checkCanEncryptFile(t))throw new Error("Unable to encrypt file");let e=h.getByFile(t),n=new U(app,"Encrypt Note",!0,!0,e);try{let i=await n.openAsync(),s=await this.encryptFile(t,i);await this.closeUpdateRememberPasswordThenReopen(t,ie,s,i),new b.Notice("\u{1F510} Note was encrypted \u{1F510}")}catch(i){i&&new b.Notice(i,1e4)}}async getPasswordAndDecryptFile(t){if(!this.checkCanDecryptFile(t))throw new Error("Unable to decrypt file");let e=h.getByFile(t);if(e.password!=""){let r=await this.decryptFile(t,e.password);if(r!=null){await this.closeUpdateRememberPasswordThenReopen(t,"md",r,e);return}}let n=await app.vault.read(t),i=x.decode(n),s=new U(app,"Decrypt Note",!1,!1,{password:"",hint:i.hint});try{if(e=await s.openAsync(),!s.resultConfirmed)return;let r=await this.decryptFile(t,e.password);if(r==null)throw new Error("Decryption failed");await this.closeUpdateRememberPasswordThenReopen(t,"md",r,e),new b.Notice("\u{1F513} Note was decrypted \u{1F513}")}catch(r){r&&new b.Notice(r,1e4)}}async closeUpdateRememberPasswordThenReopen(t,e,n,i){let s=!1;this.plugin.app.workspace.iterateAllLeaves(r=>{r.view instanceof b.TextFileView&&r.view.file==t&&(r.detach(),s=!0)});try{let r=V.getFilePathWithNewExtension(t,e);await app.fileManager.renameFile(t,r),await app.vault.modify(t,n),h.putByFile(i,t)}finally{s&&await app.workspace.getLeaf().openFile(t)}}async encryptFile(t,e){let n=await app.vault.read(t),i=await S.encode(e.password,e.hint,n);return x.encode(i)}async decryptFile(t,e){let n=await app.vault.read(t),i=x.decode(n);return await S.decrypt(i,e)}};var se=class extends be.Plugin{constructor(){super(...arguments);this.enabledFeatures=[]}async onload(){await this.loadSettings(),this.enabledFeatures.push(new G,new q,new Y),this.addSettingTab(new _(this.app,this,this.settings,this.enabledFeatures)),this.enabledFeatures.forEach(async e=>{await e.onload(this,this.settings)})}onunload(){this.enabledFeatures.forEach(async e=>{e.onunload()})}async loadSettings(){let e={confirmPassword:!0,rememberPassword:!0,rememberPasswordTimeout:30,rememberPasswordLevel:h.LevelFilename,featureWholeNoteEncrypt:{defaultView:"Source".toString()},featureInplaceEncrypt:{expandToWholeLines:!1,showMarkerWhenReadingDefault:!0}};this.settings=Object.assign(e,await this.loadData()),h.setActive(this.settings.rememberPassword),h.setAutoExpire(this.settings.rememberPasswordTimeout==0?null:this.settings.rememberPasswordTimeout),h.setLevel(this.settings.rememberPasswordLevel)}async saveSettings(){await this.saveData(this.settings)}};