Char: `+y.c),u=newError(u),y.error=u,C(y,"onerror",u),y}functionY(y){returny.sawRoot&&!y.closedRoot&&M(y,"Unclosed root tag"),y.state!==w.BEGIN&&y.state!==w.BEGIN_WHITESPACE&&y.state!==w.TEXT&&j(y,"Unexpected end"),P(y),y.c="",y.closed=!0,C(y,"onend"),t.call(y,y.strict,y.opt),y}functionM(y,u){if(typeofy!="object"||!(yinstanceoft))thrownewError("bad call to strictFail");y.strict&&j(y,u)}functionne(y){y.strict||(y.tagName=y.tagName[y.looseCase]());varu=y.tags[y.tags.length-1]||y,R=y.tag={name:y.tagName,attributes:{}};y.opt.xmlns&&(R.ns=u.ns),y.attribList.length=0,N(y,"onopentagstart",R)}functionZ(y,u){varR=y.indexOf(":"),x=R<0?["",y]:y.split(":"),S=x[0],I=x[1];returnu&&y==="xmlns"&&(S="xmlns",I=""),{prefix:S,local:I}}functionpe(y){if(y.strict||(y.attribName=y.attribName[y.looseCase]()),y.attribList.indexOf(y.attribName)!==-1||y.tag.attributes.hasOwnProperty(y.attribName)){y.attribName=y.attribValue="";return}if(y.opt.xmlns){varu=Z(y.attribName,!0),R=u.prefix,x=u.local;if(R==="xmlns")if(x==="xml"&&y.attribValue!==g)M(y,"xml: prefix must be bound to "+g+`
Actual: `+y.attribValue);elseif(x==="xmlns"&&y.attribValue!==b)M(y,"xmlns: prefix must be bound to "+b+`
Actual: `+y.attribValue);else{varS=y.tag,I=y.tags[y.tags.length-1]||y;S.ns===I.ns&&(S.ns=Object.create(I.ns)),S.ns[x]=y.attribValue}y.attribList.push([y.attribName,y.attribValue])}elsey.tag.attributes[y.attribName]=y.attribValue,N(y,"onattribute",{name:y.attribName,value:y.attribValue});y.attribName=y.attribValue=""}functionU(y,u){if(y.opt.xmlns){varR=y.tag,x=Z(y.tagName);R.prefix=x.prefix,R.local=x.local,R.uri=R.ns[x.prefix]||"",R.prefix&&!R.uri&&(M(y,"Unbound namespace prefix: "+JSON.stringify(y.tagName)),R.uri=x.prefix);varS=y.tags[y.tags.length-1]||y;R.ns&&S.ns!==R.ns&&Object.keys(R.ns).forEach(function(ss){N(y,"onopennamespace",{prefix:ss,uri:R.ns[ss]})});for(varI=0,F=y.attribList.length;I<F;I++){var$=y.attribList[I],W=$[0],te=$[1],ee=Z(W,!0),re=ee.prefix,gn=ee.local,Xr=re===""?"":R.ns[re]||"",zt={name:W,value:te,prefix:re,local:gn,uri:Xr};re&&re!=="xmlns"&&!Xr&&(M(y,"Unbound namespace prefix: "+JSON.stringify(re)),zt.uri=re),y.tag.attributes[W]=zt,N(y,"onattribute",zt)}y.attribList.length=0}y.tag.isSelfClosing=!!u,y.sawRoot=!0,y.tags.push(y.tag),N(y,"onopentag",y.tag),u||(!y.noscript&&y.tagName.toLowerCase()==="script"?y.state=w.SCRIPT:y.state=w.TEXT,y.tag=null,y.tagName=""),y.attribName=y.attribValue="",y.attribList.length=0}functionRe(y){if(!y.tagName){M(y,"Weird empty close tag."),y.textNode+="</>",y.state=w.TEXT;return}if(y.script){if(y.tagName!=="script"){y.script+="</"+y.tagName+">",y.tagName="",y.state=w.SCRIPT;return}N(y,"onscript",y.script),y.script=""}varu=y.tags.length,R=y.tagName;y.strict||(R=R[y.looseCase]());for(varx=R;u--;){varS=y.tags[u];if(S.name!==x)M(y,"Unexpected close tag");elsebreak}if(u<0){M(y,"Unmatched closing tag: "+y.tagName),y.textNode+="</"+y.tagName+">",y.state=w.TEXT;return}y.tagName=R;for(varI=y.tags.length;I-->u;){varF=y.tag=y.tags.pop();y.tagName=y.tag.name,N(y,"onclosetag",y.tagName);var$={};for(varWinF.ns)$[W]=F.ns[W];varte=y.tags[y.tags.length-1]||y;y.opt.xmlns&&F.ns!==te.ns&&Object.keys(F.ns).forEach(function(ee){varre=F.ns[ee];N(y,"onclosenamespace",{prefix:ee,uri:re})})}u===0&&(y.closedRoot=!0),y.tagName=y.attribValue=y.attribName="",y.attribList.length=0,y.state=w.TEXT}functionG(y){varu=y.entity,R=u.toLowerCase(),x,S="";returny.ENTITIES[u]?y.ENTITIES[u]:y.ENTITIES[R]?y.ENTITIES[R]:(u=R,u.charAt(0)==="#"&&(u.charAt(1)==="x"?(u=u.slice(2),x=parseInt(u,16),S=x.toString(16)):(u=u.slice(1),x=parseInt(u,10),S=x.toString(10))),u=u.replace(/^0+/,""),isNaN(x)||S.toLowerCase()!==u?(M(y,"Invalid character entity"),"&"+y.entity+";"):String.fromCodePoint(x))}functionQ(y,u){u==="<"?(y.state=w.OPEN_WAKA,y.startTagPosition=y.position):T(u)||(M(y,"Non-whitespace before first tag."),y.textNode=u,y.state=w.TEXT)}functionct(y,u){varR="";returnu<y.length&&(R=y.charAt(u)),R}functionYt(y){varu=this;if(this.error)throwthis.error;if(u.closed)returnj(u,"Cannot write after close. Assign an onready handler.");if(y===null)returnY(u);typeofy=="object"&&(y=y.toString());for(varR=0,x="";x=ct(y,R++),u.c=x,!!x;)switch(u.trackPosition&&(u.position++,x===`
`?(u.line++,u.column=0):u.column++);u.textNode+=y.substring(S,R-1)}x==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=w.OPEN_WAKA,u.startTagPosition=u.position):(!T(x)&&(!u.sawRoot||u.closedRoot)&&M(u,"Text data outside of root node."),x==="&"?u.state=w.TEXT_ENTITY:u.textNode+=x);continue;casew.SCRIPT:x==="<"?u.state=w.SCRIPT_ENDING:u.script+=x;continue;casew.SCRIPT_ENDING:x==="/"?u.state=w.CLOSE_TAG:(u.script+="<"+x,u.state=w.SCRIPT);continue;casew.OPEN_WAKA:if(x==="!")u.state=w.SGML_DECL,u.sgmlDecl="";elseif(!T(x))if(_(d,x))u.state=w.OPEN_TAG,u.tagName=x;elseif(x==="/")u.state=w.CLOSE_TAG,u.tagName="";elseif(x==="?")u.state=w.PROC_INST,u.procInstName=u.procInstBody="";else{if(M(u,"Unencoded <"),u.startTagPosition+1<u.position){varI=u.position-u.startTagPosition;x=newArray(I).join(" ")+x}u.textNode+="<"+x,u.state=w.TEXT}continue;casew.SGML_DECL:(u.sgmlDecl+x).toUpperCase()===p?(N(u,"onopencdata"),u.state=w.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+x==="--"?(u.state=w.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+x).toUpperCase()===m?(u.state=w.DOCTYPE,(u.doctype||u.sawRoot)&&M(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):x===">"?(N(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=w.TEXT):(A(x)&&(u.state=w.SGML_DECL_QUOTED),u.sgmlDecl+=x);continue;casew.SGML_DECL_QUOTED:x===u.q&&(u.state=w.SGML_DECL,u.q=""),u.sgmlDecl+=x;continue;casew.DOCTYPE:x===">"?(u.state=w.TEXT,N(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=x,x==="["?u.state=w.DOCTYPE_DTD:A(x)&&(u.state=w.DOCTYPE_QUOTED,u.q=x));continue;casew.DOCTYPE_QUOTED:u.doctype+=x,x===u.q&&(u.q="",u.state=w.DOCTYPE);continue;casew.DOCTYPE_DTD:u.doctype+=x,x==="]"?u.state=w.DOCTYPE:A(x)&&(u.state=w.DOCTYPE_DTD_QUOTED,u.q=x);continue;casew.DOCTYPE_DTD_QUOTED:u.doctype+=x,x===u.q&&(u.state=w.DOCTYPE_DTD,u.q="");continue;casew.COMMENT:x==="-"?u.state=w.COMMENT_ENDING:u.comment+=x;continue;casew.COMMENT_ENDING:x==="-"?(u.state=w.COMMENT_ENDED,u.comment=L(u.opt,u.comment),u.comment&&N(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+x,u.state=w.COMMENT);continue;casew.COMMENT_ENDED:x!==">"?(M(u,"Malformed comment"),u.comment+="--"+x,u.state=w.COMMENT):u.state=w.TEXT;continue;casew.CDATA:x==="]"?u.state=w.CDATA_ENDING:u.cdata+=x;continue;casew.CDATA_ENDING:x==="]"?u.state=w.CDATA_ENDING_2:(u.cdata+="]"+x,u.state=w.CDATA);continue;casew.CDATA_ENDING_2:x===">"?(u.cdata&&N(u,"oncdata",u.cdata),N(u,"onclosecdata"),u.cdata="",u.state=w.TEXT):x==="]"?u.cdata+="]":(u.cdata+="]]"+x,u.state=w.CDATA);continue;casew.PROC_INST:x==="?"?u.state=w.PROC_INST_ENDING:T(x)?u.state=w.PROC_INST_BODY:u.procInstName+=x;continue;casew.PROC_INST_BODY:if(!u.procInstBody&&T(x))continue;x==="?"?u.state=w.PROC_INST_ENDING:u.procInstBody+=x;continue;casew.PROC_INST_ENDING:x===">"?(N(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=w.TEXT):(u.procInstBody+="?"+x,u.state=w.PROC_INST_BODY);continue;casew.OPEN_TAG:_(f,x)?u.tagName+=x:(ne(u),x===">"?U(u):x==="/"?u.state=w.OPEN_TAG_SLASH:(T(x)||M(u,"Invalid character in tag name"),u.state=w.ATTRIB));continue;casew.OPEN_TAG_SLASH:x===">"?(U(u,!0),Re(u)):(M(u,"Forward-slash in opening tag not followed by >"),u.state=w.ATTRIB);continue;casew.ATTRIB:if(T(x))continue;x===">"?U(u):x==="/"?u.state=w.OPEN_TAG_SLASH:_(d,x)?(u.attribName=x,u.attribValue="",u.state=w.ATTRIB_NAME):M(u,"Invalid attribute name");continue;casew.ATTRIB_NAME:x==="="?u.state=w.ATTRIB_VALUE:x===">"?(M(u,"Attribute without value"),u.attribValue=u.attribName,pe(u),U(u)):T(x)?u.state=w.ATTRIB_NAME_SAW_WHITE:_(f,x)?u.attribName+=x:M(u,"Invalid attribute name");continue;casew.ATTRIB_NAME_SAW_WHITE:if(x==="=")u.state=w.ATTRIB_VALUE;else{if(T(x))continue;M(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",N(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",x===">"?U(u):_(d,x)?(u.attribName=x,u.state=w.ATTRIB_NAME):(M(u,"Invalid attribute name"),u.state=w.ATTRIB)}continue;casew.ATTRIB_VALUE:if(T(x))continue;A(x)?(u.q=x,u
`}};Un.protobufType="ciofecaforensics.MergableDataProto";var jn=class extends vt{constructor(t,i){super(t);this.rowLocations={};this.columnLocations={};this.table=i.mergableDataObject;let r=this.table.mergeableDataObjectData;this.keys=r.mergeableDataObjectKeyItem,this.types=r.mergeableDataObjectTypeItem,this.uuids=r.mergeableDataObjectUuidItem.map(this.uuidToString),this.objects=r.mergeableDataObjectEntry}async parse(){let t=this.objects.find(r=>r.customMap&&this.types[r.customMap.type]=="com.apple.notes.ICTable");if(!t)return null;let i=null;for(let r of t.customMap.mapEntry){let o=this.objects[r.value.objectIndex];switch(this.keys[r.key]){case"crRows":[this.rowLocations,this.rowCount]=this.findLocations(o);break;case"crColumns":[this.columnLocations,this.columnCount]=this.findLocations(o);break;case"cellColumns":i=o;break}}return i?await this.computeCells(i):null}findLocations(t){let i=[],r={};for(let o of t.orderedSet.ordering.array.attachment)i.push(this.uuidToString(o.uuid));for(let o of t.orderedSet.ordering.contents.element){let a=this.getTargetUuid(o.key),s=this.getTargetUuid(o.value);r[s]=i.indexOf(a)}return[r,i.length]}async computeCells(t){let i=Array(this.rowCount).fill(0).map(()=>Array(this.columnCount));for(let r of t.dictionary.element){let o=this.columnLocations[this.getTargetUuid(r.key)],a=this.objects[r.value.objectIndex];for(let s of a.dictionary.element){let l=this.rowLocations[this.getTargetUuid(s.key)],c=this.objects[s.value.objectIndex];if(!(l in i)||!c)continue;let p=new Zt(this.importer,c);i[l][o]=await p.format(!0)}}return i}async format(){let t=await this.parse();if(!t)return"";let i=`
WHERE zidentifier = ${o.toUpperCase()}`,s=await this.importer.resolveNote(a.Z_PK);return s?this.app.fileManager.generateMarkdownLink(s,r,void 0,i):"(unknownfilelink)"}convertColor(t){let i="#";for(let r of Object.values(t))i+=Math.floor(r*255).toString(16);return i}convertAlign(t){switch(t){default:return"left";case 1:return"center";case 2:return"right";case 3:return"justify"}}};Zt.protobufType="ciofecaforensics.Document";function Bd(n){return n.attachmentInfo?!n.attachmentInfo.typeUti.includes("com.apple.notes.inlinetextattachment"):!1}function us(n,e){var t,i;if(!e||n.$type!=e.$type)return!1;for(let r of n.$type.fieldsArray)if(r.name!="length"){if((t=n[r.name])!=null&&t.$type&&((i=e[r.name])!=null&&i.$type)){if(!us(n[r.name],e[r.name]))return!1}else if(n[r.name]!=e[r.name])return!1}return!0}var fs={nested:{ciofecaforensics:{nested:{Color:{fields:{red:{type:"float",id:1},green:{type:"float",id:2},blue:{type:"float",id:3},alpha:{type:"float",id:4}}},AttachmentInfo:{fields:{attachmentIdentifier:{type:"string",id:1},typeUti:{type:"string",id:2}}},Font:{fields:{fontName:{type:"string",id:1},pointSize:{type:"float",id:2},fontHints:{type:"int32",id:3}}},ParagraphStyle:{fields:{styleType:{type:"int32",id:1,options:{default:-1}},alignment:{type:"int32",id:2},indentAmount:{type:"int32",id:4},checklist:{type:"Checklist",id:5},blockquote:{type:"int32",id:8}}},Checklist:{fields:{uuid:{type:"bytes",id:1},done:{type:"int32",id:2}}},DictionaryElement:{fields:{key:{type:"ObjectID",id:1},value:{type:"ObjectID",id:2}}},Dictionary:{fields:{element:{rule:"repeated",type:"DictionaryElement",id:1,options:{packed:!1}}}},ObjectID:{fields:{unsignedIntegerValue:{type:"uint64",id:2},stringValue:{type:"string",id:4},objectIndex:{type:"int32",id:6}}},RegisterLatest:{fields:{contents:{type:"ObjectID",id:2}}},MapEntry:{fields:{key:{type:"int32",id:1},value:{type:"ObjectID",id:2}}},AttributeRun:{fields:{length:{type:"int32",id:1},paragraphStyle:{type:"ParagraphStyle",id:2},font:{type:"Font",id:3},fontWeight:{type:"int32",id:5},underlined:{type:"int32",id:6},strikethrough:{type:"int32",id:7},superscript:{type:"int32",id:8},link:{type:"string",id:9},color:{type:"Color",id:10},attachmentInfo:{type:"AttachmentInfo",id:12}}},NoteStoreProto:{fields:{document:{type:"Document",id:2}}},Document:{fields:{version:{type:"int32",id:2},note:{type:"Note",id:3}}},Note:{fields:{noteText:{type:"string",id:2},attributeRun:{rule:"repeated",type:"AttributeRun",id:5,options:{packed:!1}}}},MergableDataProto:{fields:{mergableDataObject:{type:"MergableDataObject",id:2}}},MergableDataObject:{fields:{version:{type:"int32",id:2},mergeableDataObjectData:{type:"MergeableDataObjectData",id:3}}},MergeableDataObjectData:{fields:{mergeableDataObjectEntry:{rule:"repeated",type:"MergeableDataObjectEntry",id:3,options:{packed:!1}},mergeableDataObjectKeyItem:{rule:"repeated",type:"string",id:4},mergeableDataObjectTypeItem:{rule:"repeated",type:"string",id:5},mergeableDataObjectUuidItem:{rule:"repeated",type:"bytes",id:6}}},MergeableDataObjectEntry:{fields:{registerLatest:{type:"RegisterLatest",id:1},list:{type:"List",id:5},dictionary:{type:"Dictionary",id:6},unknownMessage:{type:"UnknownMergeableDataObjectEntryMessage",id:9},note:{type:"Note",id:10},customMap:{type:"MergeableDataObjectMap",id:13},orderedSet:{type:"OrderedSet",id:16}}},UnknownMergeableDataObjectEntryMessage:{fields:{unknownEntry:{type:"UnknownMergeableDataObjectEntryMessageEntry",id:1}}},UnknownMergeableDataObjectEntryMessageEntry:{fields:{unknownInt1:{type:"int32",id:1},unknownInt2:{type:"int64",id:2}}},MergeableDataObjectMap:{fields:{type:{type:"int32",id:1},mapEntry:{rule:"repeated",type:"MapEntry",id:3,options:{packed:!1}}}},OrderedSet:{fields:{ordering:{type:"OrderedSetOrdering",id:1},elements:{type:"Dictionary",id:2}}},OrderedSetOrdering:{fields:{array:{type:"OrderedSetOrderingArray",id:1},contents:{type:"Dictionary",id:2}}},OrderedSetOrderingArray:{fields:{contents:{type:"Note",id:1},attachment:{rule:"repeated",type:"OrderedSetOrderingArrayAttachment",id:2,options:{packed:!1}}}},OrderedSetOrderingArrayAttachme
`}functionii(n,e,t="..."){returnn.length<e?n:n.substring(0,e)+t}varCe=require("obsidian");varjl=300,ue=class{constructor(e,t){this.files=[];this.outputLocation="";this.notAvailable=!1;this.outputFolder=null;this.app=e,this.vault=e.vault,this.modal=t,this.init()}registerAuthCallback(e){this.modal.plugin.registerAuthCallback(e)}addFileChooserSetting(e,t,i=!1){letr=newCe.Setting(this.modal.contentEl).setName("Files to import").setDesc("Pick the files that you want to import.").addButton(a=>a.setButtonText(i?"Choose files":"Choose file").onClick(async()=>{if(Ce.Platform.isDesktopApp){lets=["openFile","dontAddToRecent"];i&&s.push("multiSelections");letl=window.electron.remote.dialog.showOpenDialogSync({title:"Pick files to import",properties:s,filters:[{name:e,extensions:t}]});l&&l.length>0&&(this.files=l.map(c=>newBe(c)),o())}else{lets=createEl("input");s.type="file",s.accept=t.map(l=>"."+l.toLowerCase()).join(","),s.addEventListener("change",()=>{if(!s.files)return;letl=Array.from(s.files);l.length>0&&(this.files=l.map(c=>newVi(c)).filter(c=>t.contains(c.extension)),o())}),s.click()}}));i&&Ce.Platform.isDesktopApp&&r.addButton(a=>a.setButtonText("Choose folders").onClick(async()=>{if(Ce.Platform.isDesktopApp){lets=window.electron.remote.dialog.showOpenDialogSync({title:"Pick folders to import",properties:["openDirectory","multiSelections","dontAddToRecent"]});if(s&&s.length>0){r.setDesc("Reading folders...");letl=s.map(c=>newen(c));this.files=awaitIo(l,c=>t.contains(c.extension)),o()}}}));leto=()=>{leta=document.createDocumentFragment(),s=this.files.length,l=this.files.map(c=>c.name).join(", ");l.length>jl&&(l=l.substring(0,jl)+"..."),a.createEl("span",{text:`These ${s} files will be imported: `}),a.createEl("br"),a.createEl("span",{cls:"u-pop",text:l}),r.setDesc(a)}}addOutputLocationSetting(e){this.outputLocation=e,newCe.Setting(this.modal.contentEl).setName("Output folder").setDesc("Choose a folder in the vault to put the imported files. Leave empty to output to vault root.").addText(t=>t.setValue(e).onChange(i=>{this.outputLocation=i,this.outputFolder=null}))}asyncgetOutputFolder(){if(this.outputFolder)returnthis.outputFolder;let{vault:e}=this.app,t=this.outputLocation;t===""&&(t="/");leti=e.getAbstractFileByPath(t);return(i===null||!(iinstanceofCe.TFolder))&&(awaite.createFolder(t),i=e.getAbstractFileByPath(t)),iinstanceofCe.TFolder?(this.outputFolder=i,i):null}asyncgetAvailablePathForAttachment(e,t){leti=awaitthis.getOutputFolder(),r=i?{parent:i}:null,{basename:o,extension:a}=oe(e),s=awaitthis.vault.getAvailablePathForAttachments(o,a,r),l=oe(s),c=l.extension?"."+l.extension:"."+a,p=1,m=s;for(;t.includes(m)||this.vault.getAbstractFileByPath(m);)m=q.join(l.parent,`${l.name}${p}${c}`),p++;returnm}asyncpause(e,t,i){letr=newPromise(o=>setTimeout(o,e*1e3));if(i){leto=i.statusMessage;i.status(`\u23F8\uFE0F Pausing import for ${e} seconds (${t})`),awaitr,i.status(o)}elseawaitr}sanitizeFilePath(e){returne.replace(/[:|?<>*\\]/g,"")}asynccreateFolders(e){lett=e.split("/").map(o=>o.replace(/^\.+/,"")).join("/"),i=(0,Ce.normalizePath)(t),r=this.vault.getAbstractFileByPathInsensitive(i);if(r&&rinstanceofCe.TFolder)returnr;if(awaitthis.vault.createFolder(i),r=this.vault.getAbstractFileByPathInsensitive(i),!(rinstanceofCe.TFolder))thrownewError(`Failed to create folder at "${e}"`);returnr}asyncsaveAsMarkdownFile(e,t,i){letr=ze(t);returnawaitthis.app.fileManager.createNewMarkdownFile(e,r,i)}};varKp=Jr(Up());varCa=require("obsidian");varjp=n=>{lett=vr.execSync(`${n} --version`).toString().toString().match(/(\d+)\.(\d+).(\d+)/);return(t==null?void0:t[1])>3||(t==null?void0:t[2])>32},Hp=n=>{lete=[];if(!n)returne;lett=[],i=0,r=-1,o={};for(;i<n.length;){leta="";if(n[i]==="'")for(i++;i<n.length;)if(n[i]!=="'"){lets=n.indexOf("'",i);a+=n.substring(i,s),i=s}elseif(n[i+1]==="'")a+=n[i],i+=2;else{i++;break}elseif(n[i]==="N")a=null,i+=4;else{lets=Math.min(...[n.indexOf(",",i),n.indexOf(`
`,{isArray:Vg}=Array,{parse:Gp}=JSON,{defineProperty:Kg}=Object,Xg=()=>{},Jg=(n,e,t,i,r,o)=>{leta=[],{stdout:s,stderr:l}=vr.spawn(i,r,o).on("close",p=>{if(c||p!==0){p!==0&&hi(e,"busy DB or query too slow");return}letm=a.join("").trim();if(t==="query")n(m);else{letg=Gp(m||"[]");n(t==="get"&&Vg(g)?g.shift():g)}});s.on("data",p=>{a.push(p)});letc=!1;l.on("data",p=>{c=!0,hi(e,"".trim.call(p))})},Qg=(n,e,t)=>{leti=jp(n),r=i?Zg:Gg,{stdin:o,stdout:a,stderr:s}=vr.spawn(n,e);i?o.write(`.mode json
`)})))}},Oa=(n,e,t,i,r)=>(...o)=>newPromise((a,s)=>{letl=Sa(s,o);l.length&&(n==="get"&&/^SELECT\s+/i.test(l)&&!/\s+LIMIT\s+\d+$/i.test(l)&&(l+=" LIMIT 1"),t(a,s,n,e,i.concat(l),r))}),Zp="";functionIa(n,e={}){n===":memory:"&&(n=Zp||(Zp=q.join(nn.tmpdir(),randomUUID())));lett=e.timeout||0,i=e.bin||"sqlite3",r=[n,"-bail"],o={timeout:t};e.readonly&&r.push("-readonly"),t&&r.push("-cmd",".timeout "+t);leta=r.concat("-json"),s=e.exec||(e.persistent?Qg(i,r,t):Jg);return{transaction(){letl=[];returnKg((...c)=>{l.push(c)},"commit",{value(){returnnewPromise((c,p)=>{letm=["BEGIN TRANSACTION"];for(letgofl){letb=Sa(p,g);if(!b.length)return;m.push(b)}m.push("COMMIT"),s(c,p,"query",i,r.concat(m.join(";")),o)})}})},query:Oa("query",i,s,r,o),get:Oa("get",i,s,a,o),all:Oa("all",i,s,a,o),close:e.persistent?()=>s(null,null,"close"):Xg,raw:zp}}varFa="Library/Group Containers/group.com.apple.notes",Vp="NoteStore.sqlite",e0=978307200,Tr=classextendsue{constructor(){super(...arguments);this.owners={};this.resolvedAccounts={};this.resolvedFiles={};this.resolvedFolders={};this.multiAccount=!1;this.noteCount=0;this.parsedNotes=0;this.omitFirstLine=!0;this.importTrashed=!1;this.includeHandwriting=!1;this.trashFolders=[]}init(){if(!lt.Platform.isMacOS||!lt.Platform.isDesktop){this.modal.contentEl.createEl("p",{text:"Due to platform limitations, Apple Notes cannot be exported from this device. Open your vault on a Mac to export from Apple Notes."}),this.notAvailable=!0;return}this.addOutputLocationSetting("Apple Notes"),newlt.Setting(this.modal.contentEl).setName("Import recently deleted notes").setDesc('Import notes in the "Recently Deleted" folder. Unlike in Apple Notes, they will not be automatically removed after a set amount of time.').addToggle(t=>t.setValue(!1).onChange(asynci=>this.importTrashed=i)),newlt.Setting(this.modal.contentEl).setName("Omit first line").setDesc("Don't include the first line in the text, since Apple Notes uses it as the title. It will still be used as the note name.").addToggle(t=>t.setValue(!0).onChange(asynci=>this.omitFirstLine=i)),newlt.Setting(this.modal.contentEl).setName("Include handwriting text").setDesc("When Apple Notes has detected handwriting in drawings, include it as text before the drawing.").addToggle(t=>t.setValue(!1).onChange(asynci=>this.includeHandwriting=i))}asyncgetNotesDatabase(){lett=q.join(nn.homedir(),Fa),i=window.electron.remote.dialog.showOpenDialogSync({defaultPath:t,properties:["openDirectory"],message:'Select the "group.com.apple.notes" folder to allow Obsidian to read Apple Notes data.'});if(!(i!=null&&i.includes(t)))returnnewlt.Notice("Data import failed. Ensure you have selected the correct Apple Notes data folder."),null;letr=q.join(t,Vp),o=q.join(nn.tmpdir(),Vp);returnawait$e.copyFile(r,o),await$e.copyFile(r+"-shm",o+"-shm"),await$e.copyFile(r+"-wal",o+"-wal"),newIa(o,{readonly:!0,persistent:!0})}asyncimport(t){if(this.ctx=t,this.protobufRoot=Kp.Root.fromJSON(fs),this.rootFolder=awaitthis.getOutputFolder(),!this.rootFolder){newlt.Notice("Please select a location to export to.");return}if(this.database=awaitthis.getNotesDatabase(),!this.database)return;this.keys=Object.fromEntries((awaitthis.database.all`SELECT z_ent, z_name FROM z_primarykey`).map(a=>[a.Z_NAME,a.Z_ENT]));leti=awaitthis.database.all`
`,r=q.join("Media",s.ZIDENTIFIER,s.ZGENERATION1||"",s.ZFILENAME),[o,a]=Fo(s.ZFILENAME);break}try{letc=awaitthis.getAttachmentSource(this.resolvedAccounts[this.owners[s.ZNOTE]],r),p=awaitthis.getAvailablePathForAttachment(`${o}.${a}`,[]);l=awaitthis.vault.createBinary(p,c,{ctime:this.decodeTime(s.ZCREATIONDATE),mtime:this.decodeTime(s.ZMODIFICATIONDATE)})}catch(c){returnthis.ctx.reportFailed(r),console.error(c),null}returnthis.resolvedFiles[t]=l,this.ctx.reportAttachmentSuccess(this.resolvedFiles[t].path),l}decodeData(t,i){letr=Bl.gunzipSync(Buffer.from(t,"hex")),o=this.protobufRoot.lookupType(i.protobufType).decode(r);returnnewi(this,o)}decodeTime(t){return!t||t<1?newDate().getTime():Math.floor((t+e0)*1e3)}asyncgetAttachmentSource(t,i){try{returnawait$e.readFile(q.join(t.path,i))}catch(r){returnawait$e.readFile(q.join(nn.homedir(),Fa,i))}}};varOn=require("obsidian");vargi=class{constructor(e,t){this.type="file";this.entry=t,this.fullpath=e.fullpath+"/"+t.filename;let{parent:i,name:r,basename:o,extension:a}=oe(t.filename);this.parent=i,this.name=r,this.basename=o,this.extension=a}asyncreadText(){returnthis.entry.getData(newqi)}asyncread(){return(awaitthis.entry.getData(newJn)).arrayBuffer()}getfilepath(){returnthis.entry.filename}getsize(){returnthis.entry.uncompressedSize}getctime(){returnthis.entry.creationDate}getmtime(){returnthis.entry.lastModDate}asyncreadZip(e){returne(newQt(newRt(newBlob([awaitthis.read()]))))}};asyncfunctionyt(n,e){awaitn.readZip(asynct=>{letr=(awaitt.getEntries()).filter(o=>!o.directory&&!!o.getData).map(o=>newgi(n,o));returne(t,r)})}var_r=classextendsue{constructor(){super(...arguments);this.attachmentMap={}}init(){this.addFileChooserSetting("Bear2bk",["bear2bk"]),this.addOutputLocationSetting("Bear")}asyncimport(t){let{files:i}=this;if(i.length===0){newOn.Notice("Please pick at least one file to import.");return}letr=awaitthis.getOutputFolder();if(!r){newOn.Notice("Please select a location to export to.");return}leto=r,a=newRegExp("\\[[^\\]]*\\]\\((assets/[^\\)]+)\\)","gm"),s=awaitthis.createFolders(`${r.path}/archive`),l=awaitthis.createFolders(`${r.path}/trash`);for(letcofi){if(t.isCancelled())return;t.status("Processing "+c.name),awaityt(c,async(p,m)=>{letg=awaitthis.collectMetadata(t,m);for(letbofm){if(t.isCancelled())return;let{fullpath:v,filepath:d,parent:f,name:h,extension:E}=b;if(!(h==="info.json"||h==="tags.json")){t.status("Processing "+h);try{if(E==="md"||E==="markdown"){letT=oe(f).basename;t.status("Importing note "+T);letA=awaitb.readText();A=this.removeMarkdownHeader(T,A);letO=[...A.matchAll(a)];if(O.length>0)for(letCofO){let[N,P]=C,L=q.join(f,decodeURI(P)),j=awaitthis.getAttachmentStoragePath(L);j=encodeURI(j);letY=N.replace(P,j);A=A.replace(N,Y)}let_=(0,On.normalizePath)(T),k=g[f],w=o;k!=null&&k.archived?w=s:k!=null&&k.trashed&&(w=l);letD=awaitthis.saveAsMarkdownFile(w,_,A);k!=null&&k.ctime&&(k!=null&&k.mtime)&&awaitthis.modifFileTimestamps(k,D),t.reportNoteSuccess(T)}elseif(d.match(/\/assets\//g)){t.status("Importing asset "+b.name);letT=awaitthis.getAttachmentStoragePath(b.filepath),A=awaitb.read();awaitthis.vault.createBinary(T,A),t.reportAttachmentSuccess(b.fullpath)}elset.reportSkipped(v,"unknown type of file")}catch(T){t.reportFailed(v,T)}}}})}}asyncmodifFileTimestamps(t,i){letr={ctime:t.ctime,mtime:t.mtime};awaitthis.vault.append(i,"",r)}asynccollectMetadata(t,i){letr={};for(letoofi){if(t.isCancelled())returnr;if(o.name!=="info.json")continue;leta=awaito.readText(),l=JSON.parse(a)["net.shinyfrog.bear"],c=Date.parse(l.creationDate),p=Date.parse(l.modificationDate);r[o.parent]={ctime:isNaN(c)?void0:c,mtime:isNaN(p)?void0:p,archived:l.archived===1,trashed:l.trashed===1}}returnr}asyncgetAttachmentStoragePath(t){leti=(0,On.normalizePath)(t);if(this.attachmentMap[i])returnthis.attachmentMap[i];letr=Object.values(this.attachmentMap),o=awaitthis.getAvailablePathForAttachment(i,r);returno=o.replace(/:/g,""),this.attachmentMap[i]=o,o}removeMarkdownHeader(t,i){if(!i.startsW
`,zf=Yf+By+$y+Yf+Uy;var nb=td.Platform.isDesktopApp?ed():null,Pr={enexSources:[],currentTemplate:"",outputDir:"./mdNotes",isMetadataNeeded:!1,isNotebookNameNeeded:!1,isZettelkastenNeeded:!1,useZettelIdAsFilename:!1,plainTextNotesOnly:!1,skipWebClips:!1,useHashTags:!0,nestedTags:{separatorInEN:"_",replaceSeparatorWith:"/",replaceSpaceWith:"-"},obsidianTaskTag:"",urlEncodeFileNamesAndLinks:!1,sanitizeResourceNameSpaces:!1,replacementChar:"_",pathSeparator:"/",resourcesDir:"_resources",turndownOptions:{headingStyle:"atx"}},ib="@@@",B={...Pr};function rb(n){return n==null?n:JSON.parse(JSON.stringify(n))}function nd(n,...e){for(let t of e)for(let i of Object.keys(t)){let r=t[i],o=n[i];!Array.isArray(r)&&typeof r=="object"&&!Array.isArray(o)&&typeof o=="object"?n[i]=nd({},o,r):n[i]=rb(r)}return n}var ob=n=>{B=nd({},Pr,n);let e=B.templateFile?K.readFileSync(B.templateFile,"utf-8"):zf;e=B.currentTemplate?B.currentTemplate:e,B.skipCreationTime=!Bf(e),B.skipLocation=!Uf(e),B.skipSourceUrl=!Hf(e),B.skipTags=!qf(e),B.skipUpdateTime=!Wf(e),B.isNotebookNameNeeded=jf(e),B.currentTemplate=e,console.log(`Currentconfigis:${JSON.stringify(B,null,4)}`),console.log(`Pathseparator:${q.sep}`)},ab=async(n,e,t)=>{if(!(e instanceof Be))throw new Error("Evernote import currently only works on desktop");let i=ke.getInstance();t.status("Processing "+e.name),console.log(`Gettingstreamfrom${e}`);let r=e.createReadStream(),o={},a=i.getCurrentNotebookName();return new Promise((s,l)=>{let c=g=>(t.reportFailed(i.getCurrentNotebookFullpath(),g),l(g)),p=nb(r),m=null;p.on("tag:note-attributes",g=>{m=g}),p.on("tag:note",g=>{if(t.isCancelled()){r.close();return}if(n.skipWebClips&&ef(g))t.reportSkipped(g.title);else{t.status("Importing note "+g.title),m&&(g["note-attributes"]=m);try{If(g,a),t.reportNoteSuccess(a+"/"+g.title)}catch(v){return t.reportFailed(g.title||e,v),s()}}m=null;let b=i.getCurrentNotePath();if(b)for(let v of Object.keys(o)){let d=`<YARLE-EN-V10-TASK>${v}</YARLE-EN-V10-TASK>`,f=K.readFileSync(b,"utf8"),h=new Map([...o[v]].sort()),E=f.replace(d,[...h.values()].join(`
`));K.writeFileSync(b,E)}}),p.on("tag:task",g=>{let b=Jp(g);o[b.taskgroupnotelevelid]||(o[b.taskgroupnotelevelid]=new Map),o[b.taskgroupnotelevelid].set(b.sortweight,Mf(b,a))}),p.on("end",s),p.on("error",c),r.on("error",c)})};async function id(n,e){ob(n);let t=[],i=n.outputDir;for(let r of n.enexSources){if(e.isCancelled())return;let o,a=ke.getInstance();r.basename.includes(ib)?(n.outputDir=Vu(r,n),o=Gu(r),Xu(o,n),a.setCurrentNotebookName(o.basename),a.setCurrentNotebookFullpath(o.fullpath)):(Ku(r,n),a.setCurrentNotebookName(r.basename),a.setCurrentNotebookFullpath(r.fullpath)),await ab(n,r,e),t.push(Wa()),n.outputDir=i}e.isCancelled()||await $f(n,t)}var Mr=class extends ue{init(){this.addFileChooserSetting("Evernote",["enex"],!0),this.addOutputLocationSetting("Evernote")}async import(e){let{files:t}=this;if(t.length===0){new Ti.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Ti.Notice("Please select a location to export to.");return}let{app:r}=this,o=r.vault.adapter;if(!(o instanceof Ti.FileSystemAdapter))return;let a={...Pr,enexSources:t,outputDir:q.join(o.getBasePath(),i.path)};await id(a,e)}};var Se=require("obsidian");var $r=class extends ue{init(){this.addFileChooserSetting("HTML",["htm","html"],!0),this.addAttachmentSizeLimit(0),this.addMinimumImageSize(65),this.addOutputLocationSetting("HTML import")}addAttachmentSizeLimit(e){this.attachmentSizeLimit=e*10**6,new Se.Setting(this.modal.contentEl).setName("Attachment size limit (MB)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>{i.type="number",i.step="0.1"}).setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(Number.isNaN(r)||r<0){t.setValue((this.attachmentSizeLimit/10**6).toString());return}this.attachmentSizeLimit=r*10**6}))}addMinimumImageSize(e){this.minimumImageSize=e,new Se.Setting(this.modal.contentEl).setName("Minimum image size (px)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>i.type="number").setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(!Number.isInteger(r)||r<0){t.setValue(this.minimumImageSize.toString());return}this.minimumImageSize=r}))}async import(e){let{files:t}=this;if(t.length===0){new Se.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Se.Notice("Please select a location to export to.");return}let r=new Map;e.reportProgress(0,t.length);for(let l=0;l<t.length;l++){if(e.isCancelled())return;let c=t[l],p=await this.processFile(e,i,c);p&&r.set(c instanceof Be?ni.pathToFileURL(c.filepath).href:c.name,{file:c,tFile:p}),e.reportProgress(l+1,t.length)}let{metadataCache:o}=this.app,a,s=new Promise(l=>{a=l});o.onCleanCache(async()=>{for(let[l,{file:c,tFile:p}]of r){if(e.isCancelled())break;try{let m=await this.app.vault.cachedRead(p),g=o.computeMetadataAsync?await o.computeMetadataAsync(Lo(m)):o.getFileCache(p);if(!g)continue;let b=[];if(g.links)for(let{link:v,position:d,displayText:f}of g.links){let{path:h,subpath:E}=(0,Se.parseLinktext)(v),T;if(ni){let O=new URL(encodeURI(h),l);O.hash="",O.search="",T=decodeURIComponent(O.href)}else T=oe(h.replace(/#/gu,"%23")).name;let A=r.get(T);if(A){let O=this.app.fileManager.generateMarkdownLink(A.tFile,p.path,E,f);b.push({from:d.start.offset,to:d.end.offset,text:O})}}b.sort((v,d)=>d.from-v.from);for(let v of b)m=m.substring(0,v.from)+v.text+m.substring(v.to);await this.vault.modify(p,m)}catch(m){e.reportFailed(c.fullpath,m)}}a()}),await s}async processFile(e,t,i){e.status("Processing "+i.name);try{let r=await i.readText(),o=dt(r);sb(o);let a=i instanceof Be?ni.pathToFileURL(i.filepath):void 0,s=new Map,l=new Map;for(let m of o.findAll("img, audio, video")){if(e.isCancelled())return;let g=m.getAttribute("src");if(g)try{let b=new URL(g.startsWith("//")?`https:${g}`:g,a),v=b.href,d=s.get(v);s.has(v)||(e.status("Downloading attachment for "+i.name),d=await this.downloadAttachment(t,m,b),s.set(v,d),d?(l.set(d.path,d),e.reportAttachmentSuccess(d.name)):e.reportSkipped(g)),d&&(m.setAttribute("src",d.path.replace(/
`),n}functionrs(n){n.replaceWith(...Array.from(n.childNodes))}asyncfunctionxd(n,e){varp;lett=awaite.readText(),i=dt(t),r=i.find("div[class=page-body]");if(r===null)thrownewError("page body was not found");leto=ud(n,r);bd(n,o,!0);leta={},s=i.find("table[class=properties] > tbody");if(s){letm=ud(n,s);bd(n,m,!1),Bb(s);for(letgofArray.from(s.rows)){letb=xb(g);b&&(b.title=="Tags"&&(b.title="tags",typeofb.content=="string"?b.content=b.content.replace(/ /g,"-"):b.contentinstanceofArray&&(b.content=b.content.map(v=>v.replace(/ /g,"-")))),a[b.title]=b.content)}}Rb(r,["strong","em","mark","del"]),kb(r),vb(r),Lb(r),_b(r),Fb(r),Ed(r),gd(r,"div.indented"),gd(r,"details"),Pb(r),yd(r,"ul"),yd(r,"ol"),Mb(r),$b(r),Ib(r),Nb(r);letl=(0,Bn.htmlToMarkdown)(r.innerHTML);n.singleLineBreaks&&(l=l.replace(/\n\n(?!>)/g,`
`+l),Xi(a)+l}varpd={checkbox:["checkbox"],date:["created_time","last_edited_time","date"],list:["file","multi_select","relation"],number:["number","auto_increment_id"],text:["email","person","phone_number","text","url","status","select","formula","rollup","last_edited_by","created_by"]};functionxb(n){vara,s,l,c,p,m;lete=(a=n.className.match(/property-row-(.*)/))==null?void0:a[1];if(!e)thrownewError("property type not found for: "+n);lett=(0,Bn.htmlToMarkdown)((s=n.cells[0].textContent)!=null?s:""),i=n.cells[1],r=Object.keys(pd).find(g=>pd[g].includes(e));if(!r)thrownewError("type not found for: "+i);leto="";switch(r){case"checkbox":o=i.innerHTML.includes("checkbox-on");break;case"number":if(o=Number(i.textContent),isNaN(o))return;break;case"date":Ed(i);letg=i.getElementsByTagName("time");if(g.length===0)o="";elseif(g.length===1)o=is((0,Bn.moment)((l=g.item(0))==null?void0:l.textContent));else{letd=[];for(letf=0;f<g.length;f++)d.push(is((0,Bn.moment)((c=g.item(f))==null?void0:c.textContent)));o=d.join(" - ")}if(o.length===0)return;break;case"list":letb=i.children,v=[];for(letd=0;d<b.length;d++){letf=(p=b.item(d))==null?void0:p.textContent;f&&v.push(f)}if(o=v,o.length===0)return;break;case"text":if(o=(m=i.textContent)!=null?m:"",o.length===0)return;break}return{title:t,content:o}}functionud(n,e){vari,r;lett=[];for(letoofe.findAll("a")){leta=ld(decodeURI((i=o.getAttribute("href"))!=null?i:"")),s=xt(a),l=Object.keys(n.pathsToAttachmentInfo).find(c=>c.includes(a));s&&a.endsWith(".html")?t.push({type:"relation",a:o,id:s}):l?t.push({type:"attachment",a:o,path:l}):s&&a.startsWith("#")&&((r=o.parentElement)!=null&&r.classList.contains("table_of_contents-item"))&&t.push({type:"toc-item",a:o,id:s})}returnt}functionwb(n){lete=/\[\[[^\]]*(\\\\)\|[^\]]*\]\]/,t=n.match(newRegExp(e,"g"));returnt==null||t.forEach(i=>{n=n.replace(i,i.replace(/\\\\\|/g,"\\|"))}),n}functionvb(n){Sb(n,"style"),wd(n,"span.notion-text-equation-token");lete=n.ownerDocument,t=n.findAll("figure.equation");for(letroft){leto=r.find("annotation");if(!o)continue;leta=e.createElement("div");a.className="annotation",a.appendText(`$$${fd(o.textContent)}$$`),r.replaceWith(a)}leti=n.findAll("span.notion-text-equation-token");for(letrofi){leto=r.find("annotation");o&&r.replaceWith(`$${fd(o.textContent,!0)}$`)}}functionfd(n,e=!1){vari;lett=newRegExp(/^(?:\s|\\\\|\\\s)*(.*?)[\s\\]*$/,"s");return(i=n==null?void0:n.replace(t,"$1").replace(/[\r\n]+/g,e?" ":`
`)}functionLb(n){vare;for(lettofn.findAll("link"))t.innerText=(e=t.textContent)!=null?e:""}functionEd(n){vare,t;for(letiofn.findAll("time"))i.textContent=(t=(e=i.textContent)==null?void0:e.replace(/@/g,""))!=null?t:""}varhd={"1.875em":"h1","1.5em":"h2","1.25em":"h3"};functionPb(n){vart;lete=n.findAll("summary");for(letiofe){letr=i.getAttribute("style");if(r){for(letoofObject.keys(hd))if(r.includes(o)){i.replaceWith(createEl(hd[o],{text:(t=i.textContent)!=null?t:""}));break}}}}functiongd(n,e){lett=n.findAll(e);for(letioft)rs(i)}functionMb(n){for(leteofn.findAll(".language-Mermaid"))e.removeClass("language-Mermaid"),e.addClass("language-mermaid")}functionyd(n,e){for(lettofn.findAll(e)){leti=[],r=[],o=t;for(;o.tagName===e.toUpperCase();){i.push(o);for(lets=0;s<o.children.length;s++)r.push(o.children[s]);if(!o.nextElementSibling||o.getAttribute("class")!==o.nextElementSibling.getAttribute("class"))break;o=o.nextElementSibling}leta=n.createEl(e);for(letsofr)a.appendChild(s);i[0].replaceWith(a),i.slice(1).forEach(s=>s.remove())}}function$b(n){for(leteofn.findAll(".checkbox.checkbox-on"))e.replaceWith("[x] ");for(leteofn.findAll(".checkbox.checkbox-off"))e.replaceWith("[ ] ")}functionBb(n){vart;lete=n.findAll("a");if(e.length===0)returnn;for(letiofe){letr=createSpan();r.setText((t=i.getAttribute("href"))!=null?t:""),i.replaceWith(r)}}functionbd(n,e,t){vari,r,o;for(letaofe){lets=createSpan(),l="";switch(a.type){case"relation":letc=n.idsToFileInfo[a.id];if(c){letg=a.a.closest("table");l=`[[${c.fullLinkPathNeeded?`${n.getPathForFile(c)}${c.title}${g?"\\":""}|${c.title}`:c.title}]]`}else{console.warn("missing relation data for id: "+a.id);let{basename:g}=oe(decodeURI((i=a.a.getAttribute("href"))!=null?i:""));l=`[[${sd(g)}]]`}break;case"attachment":letp=n.pathsToAttachmentInfo[a.path];if(!p){console.warn("missing attachment data for: "+a.path);continue}l=`${t?"!":""}[[${p.fullLinkPathNeeded?p.targetParentFolder+p.nameWithExtension+"|"+p.nameWithExtension:p.nameWithExtension}]]`;break;case"toc-item":l=(r=a.a.textContent)!=null?r:"";letm=(o=l.endsWith("]"))!=null?o:!1;l=`[[#${l+(m?" ":"")}]]`}s.setText(l),a.a.replaceWith(s)}}varUr=class{constructor(e,t){this.idsToFileInfo={};this.pathsToAttachmentInfo={};this.attachmentPath=e,this.singleLineBreaks=t}getPathForFile(e){let{idsToFileInfo:t}=this,i=e.path.split("/");returne.parentIds.map(r=>{varo,a,s;return(s=(o=t[r])==null?void0:o.title)!=null?s:(a=i.find(l=>l.contains(r)))==null?void0:a.replace(` ${r}`,"")}).filter(r=>r).map(r=>r.replace(/[\. ]+$/,"")).join("/")+"/"}};asyncfunction_d(n,e){vari,r;let{filepath:t}=e;if(e.extension==="html"){leto=awaite.readText(),a=dt(o),l=a.find("body").children,c;for(letv=0;v<l.length&&(c=xt((i=l[v].getAttr("id"))!=null?i:""),!c);v++);if(!c)thrownewError("no id found for: "+t);letp=Td(a,"property-row-created_time"),m=Td(a,"property-row-last_edited_time"),g=((r=a.find("title"))==null?void0:r.textContent)||"Untitled",b=Ub(ze(g.replace(/\n/g," ").replace(/[:\/]/g,"-").replace(/#/g,"").trim()));n.idsToFileInfo[c]={path:t,parentIds:ns(t),ctime:p,mtime:m,title:b,fullLinkPathNeeded:!1}}elsen.pathsToAttachmentInfo[t]={path:t,parentIds:ns(t),nameWithExtension:ze(decodeURIComponent(e.name)),targetParentFolder:"",fullLinkPathNeeded:!1}}functionUb(n){if(n.length<200)returnn;lete=n.split(" "),t=[],i=0,r=0,o=!1;for(;i<200;){if(!e[r]){o=!0;break}t.push(e[r]),i+=e[r].length+1,r++}leta=t.join(" ");returno||(a+="..."),a}functionjb(n){lete=n.startsWith("@")?n.substr(1).trim():n.trim(),t=newDate(e);returnisNaN(t.getTime())?null:t}functionTd(n,e){lett=n.querySelector(`tr.${e}`);if(t){leti=t.querySelector("time");returni&&i.textContent?jb(i.textContent):null}returnnull}varjr=classextendsue{init(){this.parentsInSubfolders=!0,this.addFileChooserSetting("Exported Notion",["zip"]),this.addOutputLocationSetting("Notion"),newwt.Setting(this.modal.contentEl).setName("Save parent pages in subfolders").setDesc("Places the parent database pages in the same folder as the nested content."
Returnedstate:${t.state}`);await this.updateAccessToken(t.code),await this.setSwitchUser(),await this.showSectionPickerUI()}catch(i){console.error("An error occurred while we were trying to sign you in. Error details: ",i),this.modal.contentEl.createEl("div",{text:"An error occurred while trying to sign you in."}).createEl("details",{text:i}).createEl("summary",{text:"Click here to show error details"})}}async setSwitchUser(){let t=await this.fetchResource("https://graph.microsoft.com/v1.0/me","json");this.switchUserSetting.setDesc(`Signedinas${t.displayName}(${t.mail}).Ifthat's not the correct account, sign in again.`),this.switchUserSetting.settingEl.show(),this.microsoftAccountSetting.settingEl.hide()}async updateAccessToken(t){let i=new URLSearchParams({client_id:Ad,scope:"offline_access "+kd.join(" "),redirect_uri:qr});if(t)i.set("code",t),i.set("grant_type","authorization_code");else{let o=this.retrieveRefreshToken();if(!o)throw new Error("Missing token required for authentication. Please try logging in again.");i.set("refresh_token",o),i.set("grant_type","refresh_token")}let r=await(0,xe.requestUrl)({method:"POST",url:"https://login.microsoftonline.com/common/oauth2/v2.0/token",contentType:"application/x-www-form-urlencoded",body:i.toString()}).json;if(!r.access_token)throw new Error(`Unexpected data was returned instead of an access token. Error details: ${r}`);r.refresh_token&&this.storeRefreshToken(r.refresh_token),this.graphData.accessToken=r.access_token}storeRefreshToken(t){this.refreshToken=t,this.rememberMe&&localStorage.setItem(as,t)}retrieveRefreshToken(){return this.refreshToken?this.refreshToken:localStorage.getItem(as)}clearStoredRefreshToken(){localStorage.removeItem(as)}async showSectionPickerUI(){var o,a;this.loadingArea.show(),this.selectedIds=[];let t="https://graph.microsoft.com/v1.0/me/onenote/notebooks",i=new URLSearchParams({$expand:"sections($select=id,displayName),sectionGroups($expand=sections,sectionGroups)",$select:"id,displayName,lastModifiedDateTime",$orderby:"lastModifiedDateTime DESC"}),r=`${t}?${i.toString()}`;try{this.notebooks=(await this.fetchResource(r,"json-wrapped")).value,this.contentArea.empty(),this.contentArea.createEl("h4",{text:"Choose data to import"});for(let s of this.notebooks){if(((o=s.sectionGroups)==null?void 0:o.length)!==0)for(let c of s.sectionGroups)await this.fetchNestedSectionGroups(c);let l=this.contentArea.createDiv();new xe.Setting(l).setName(s.displayName).setDesc(`Last edited on: ${xe.moment.utc(s.lastModifiedDateTime).format("Do MMMM YYYY")}. Contains ${(a=s.sections)==null?void 0:a.length} sections.`).addButton(c=>c.setCta().setButtonText("Select all").onClick(()=>{l.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach(p=>p.click())})),this.renderHierarchy(s,l)}}catch(s){this.showContentAreaErrorMessage()}this.loadingArea.hide(),this.contentArea.show()}async fetchNestedSectionGroups(t){if(t.sectionGroups=(await this.fetchResource(t.sectionGroupsUrl+"?$expand=sectionGroups($expand=sections),sections","json-wrapped")).value,t.sectionGroups)for(let i=0;i<t.sectionGroups.length;i++)await this.fetchNestedSectionGroups(t.sectionGroups[i])}renderHierarchy(t,i){if(t.sectionGroups)for(let r of t.sectionGroups){let o=i.createDiv({attr:{style:"padding-inline-start: 1em; padding-top: 8px"}});o.createEl("strong",{text:r.displayName}),this.renderHierarchy(r,o)}if(t.sections){let r=i.createEl("ul",{attr:{style:"padding-inline-start: 1em;"}});for(let o of t.sections){let s=r.createEl("li",{cls:"task-list-item"}).createEl("label"),l=s.createEl("input");l.type="checkbox",s.appendChild(document.createTextNode(o.displayName)),s.createEl("br"),l.addEventListener("change",()=>{if(l.checked)this.selectedIds.push(o.id);else{let c=this.selectedIds.findIndex(p=>p===o.id);c!==-1&&this.selectedIds.splice(c,1)}})}}}showContentAreaErrorMessage(){this.contentArea.empty(),this.contentArea.createEl("p",{text:"Microsoft OneNote has limited how fast notes can be imported. Please try again in 1 hour to continue importing."}),this.contentArea.show(),this.loadingArea.
`))}}}asyncextractAndProcessBlockReferences(t,i,r,o){leta=o.match(a1);if(!a)returno;lets=[];for(letpofa)try{letm=i.get(p);if(!m){s.push(p);continue}letg=m.blockString.replace(/\[\[|\]\]/g,""),b=`[[${r}/${m.pageName}#^${p}|${g}]]`;awaitthis.modifySourceBlockString(t,m,r,p),s.push(b)}catch(m){s.push(p)}letl=0;returno.replace(/\(\(\b.*?\b\)\)/g,()=>s[l++])}asyncdownloadFirebaseFile(t,i){let{progress:r,vault:o}=this,a="";try{lets,l;if(r1.test(t)?(s=t.match(/https:\/\/firebasestorage(.*?)\?alt(.*?)\}/),l=t.match(/{{.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):Rd.test(t)?(s=t.match(Rd),l=t.match(/!\[.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):(s=t.match(o1),l=t.match(/https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)),s&&l){letc="https://firebasestorage"+s[1],p=decodeURIComponent(c.split("/").last()||"");if(p){letd=p.split("/");d.length>1&&(d.splice(-1,1),this.createFolders(`${i}/${d.join("/")}`))}else{letd=Math.floor(Date.now()/1e3),f=c.slice(-5).match(/(.*?)\.(.+)/);if(!f)returnr.reportSkipped(s[1],"Unexpected file extension"),t;p=`${d}.${f[2]}`}letm=`${i}/${p}`;if(o.getAbstractFileByPath(m))returnr.reportSkipped(s[1],"File already exists"),t;a=s[0].slice(0,-1);letv=await(awaitfetch(a,{})).arrayBuffer();returnawaito.createBinary(m,v),r.reportAttachmentSuccess(a),t.replace(l[0],`![[${m}]]`)}}catch(s){console.error(s),r.reportFailed(a,s)}returnt}};varqt=require("obsidian");varOd=/!\[\]\(assets\/([^)]*)\)/g,Gr=classextendsue{init(){qt.Platform.isMacOS||this.modal.contentEl.createEl("p",{text:"Due to platform limitations, only textpack and zip files can be imported from this device. Open your vault on a Mac to import textbundle files."});lete=qt.Platform.isMacOS?["textbundle","textpack","zip"]:["textpack","zip"];this.addFileChooserSetting("Textbundle",e,!0),this.addOutputLocationSetting("Textbundle")}asyncimport(e){let{files:t}=this;if(t.length===0){newqt.Notice("Please pick at least one file to import.");return}leti=awaitthis.getOutputFolder();if(!i){newqt.Notice("Please select a location to export to.");return}this.attachmentsFolderPath=awaitthis.createFolders(`${i.path}/assets`);for(letroft)if(r.extension==="textpack")awaityt(r,async(o,a)=>{awaitthis.process(e,r.name,a)});elseif(r.extension==="zip")awaityt(r,async(o,a)=>{lets=this.groupFilesByTextbundle(r.name,a);for(letlofs)awaitthis.process(e,r.name,l)});else{leta=awaitnewen(`${r.toString()}/`).list();awaitthis.process(e,r.name,a)}}groupFilesByTextbundle(e,t){leti={},r=e+"/",o=".textbundle";for(letaoft){if(!a.fullpath.startsWith(r)){console.log("Skipping",a.fullpath);continue}lets=a.fullpath.slice(r.length);if(s.startsWith("._")||s.startsWith("__MACOSX")){console.log("Skipping",a.fullpath);continue}letl=s.indexOf(o);if(l===-1){console.log("Skipping",a.fullpath);continue}letc=s.slice(0,l)+".textbundle";if(s.slice(l+o.length+1).startsWith("._")){console.log("Skipping",a.fullpath);continue}cini?i[c].push(a):i[c]=[a]}returnObject.values(i)}asyncprocess(e,t,i){letr=i.find(o=>o.name==="info.json");if(r){leto=awaitr.readText(),a=JSON.parse(o);if(a.hasOwnProperty("type")&&a.type!=="net.daringfireball.markdown"){e.reportSkipped(t,"The textbundle does not contain markdown");return}}for(letoofi)if(!o.name.startsWith("._"))try{if(o.type==="file"&&(o.extension==="md"||o.extension==="markdown")){leta="parent"ino?o.parent:t;a=a.replace(/.textbundle$/,"");lets=awaito.readText();s.match(Od)&&(s=s.replace(Od,`![[${this.attachmentsFolderPath.path}/$1]]`));letl=(0,qt.normalizePath)(a),c=awaitthis.getOutputFolder();awaitthis.saveAsMarkdownFile(c,l,s),e.reportNoteSuccess(a)}elseif(o.type==="file"&&o.fullpath.contains("assets/"))awaitthis.importAsset(e,o);elseif(o.type==="folder"){let{basename:a}=oe(o.toString());if(a!=="assets")continue;letl=awaitnewen(`${o.toString()}/`).list();for(letcofl)awaitthis.importAsset(e,c)}elseo.name!=="info.json"&&e.reportSkipped(o.name,"the file is not a media or markdown file.")}catch(a){e.reportFailed(o.name,a)}}asyncimportAsset(e,t){if(t.type==="folder"