293 lines
654 KiB
JavaScript
293 lines
654 KiB
JavaScript
/*
|
|||
|
|
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
|
||
|
|
if you want to view the source, please visit the github repository of this plugin
|
||
|
|
*/
|
||
|
|
|
||
|
|
"use strict";var Bg=Object.create;var Zi=Object.defineProperty;var qg=Object.getOwnPropertyDescriptor;var jg=Object.getOwnPropertyNames;var Ug=Object.getPrototypeOf,Hg=Object.prototype.hasOwnProperty;var te=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),ot=(r,t)=>{for(var e in t)Zi(r,e,{get:t[e],enumerable:!0})},Oc=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jg(t))!Hg.call(r,i)&&i!==e&&Zi(r,i,{get:()=>t[i],enumerable:!(n=qg(t,i))||n.enumerable});return r};var Yn=(r,t,e)=>(e=r!=null?Bg(Ug(r)):{},Oc(t||!r||!r.__esModule?Zi(e,"default",{value:r,enumerable:!0}):e,r)),Wg=r=>Oc(Zi({},"__esModule",{value:!0}),r);var Bs=te((pT,fp)=>{"use strict";fp.exports=Bb;function Bb(r,t){for(var e=new Array(arguments.length-1),n=0,i=2,a=!0;i<arguments.length;)e[n++]=arguments[i++];return new Promise(function(l,s){e[n]=function(u){if(a)if(a=!1,u)s(u);else{for(var p=new Array(arguments.length-1),f=0;f<p.length;)p[f++]=arguments[f];l.apply(null,p)}};try{r.apply(t||null,e)}catch(c){a&&(a=!1,s(c))}})}});var bp=te(gp=>{"use strict";var wa=gp;wa.length=function(t){var e=t.length;if(!e)return 0;for(var n=0;--e%4>1&&t.charAt(e)==="=";)++n;return Math.ceil(t.length*3)/4-n};var An=new Array(64),hp=new Array(123);for(kt=0;kt<64;)hp[An[kt]=kt<26?kt+65:kt<52?kt+71:kt<62?kt-4:kt-59|43]=kt++;var kt;wa.encode=function(t,e,n){for(var i=null,a=[],o=0,l=0,s;e<n;){var c=t[e++];switch(l){case 0:a[o++]=An[c>>2],s=(c&3)<<4,l=1;break;case 1:a[o++]=An[s|c>>4],s=(c&15)<<2,l=2;break;case 2:a[o++]=An[s|c>>6],a[o++]=An[c&63],l=0;break}o>8191&&((i||(i=[])).push(String.fromCharCode.apply(String,a)),o=0)}return l&&(a[o++]=An[s],a[o++]=61,l===1&&(a[o++]=61)),i?(o&&i.push(String.fromCharCode.apply(String,a.slice(0,o))),i.join("")):String.fromCharCode.apply(String,a.slice(0,o))};var mp="invalid encoding";wa.decode=function(t,e,n){for(var i=n,a=0,o,l=0;l<t.length;){var s=t.charCodeAt(l++);if(s===61&&a>1)break;if((s=hp[s])===void 0)throw Error(mp);switch(a){case 0:o=s,a=1;break;case 1:e[n++]=o<<2|(s&48)>>4,o=s,a=2;break;case 2:e[n++]=(o&15)<<4|(s&60)>>2,o=s,a=3;break;case 3:e[n++]=(o&3)<<6|s,a=0;break}}if(a===1)throw Error(mp);return n-i};wa.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}});var xp=te((fT,yp)=>{"use strict";yp.exports=va;function va(){this._listeners={}}va.prototype.on=function(t,e,n){return(this._listeners[t]||(this._listeners[t]=[])).push({fn:e,ctx:n||this}),this};va.prototype.off=function(t,e){if(t===void 0)this._listeners={};else if(e===void 0)this._listeners[t]=[];else for(var n=this._listeners[t],i=0;i<n.length;)n[i].fn===e?n.splice(i,1):++i;return this};va.prototype.emit=function(t){var e=this._listeners[t];if(e){for(var n=[],i=1;i<arguments.length;)n.push(arguments[i++]);for(i=0;i<e.length;)e[i].fn.apply(e[i++].ctx,n)}return this}});var Cp=te((mT,Ap)=>{"use strict";Ap.exports=wp(wp);function wp(r){return typeof Float32Array!="undefined"?function(){var t=new Float32Array([-0]),e=new Uint8Array(t.buffer),n=e[3]===128;function i(s,c,u){t[0]=s,c[u]=e[0],c[u+1]=e[1],c[u+2]=e[2],c[u+3]=e[3]}function a(s,c,u){t[0]=s,c[u]=e[3],c[u+1]=e[2],c[u+2]=e[1],c[u+3]=e[0]}r.writeFloatLE=n?i:a,r.writeFloatBE=n?a:i;function o(s,c){return e[0]=s[c],e[1]=s[c+1],e[2]=s[c+2],e[3]=s[c+3],t[0]}function l(s,c){return e[3]=s[c],e[2]=s[c+1],e[1]=s[c+2],e[0]=s[c+3],t[0]}r.readFloatLE=n?o:l,r.readFloatBE=n?l:o}():function(){function t(n,i,a,o){var l=i<0?1:0;if(l&&(i=-i),i===0)n(1/i>0?0:2147483648,a,o);else if(isNaN(i))n(2143289344,a,o);else if(i>34028234663852886e22)n((l<<31|2139095040)>>>0,a,o);else if(i<11754943508222875e-54)n((l<<31|Math.round(i/1401298464324817e-60))>>>0,a,o);else{var s=Math.floor(Math.log(i)/Math.LN2),c=Math.round(i*Math.pow(2,-s)*8388608)&8388607;n((l<<31|s+127<<23|c)>>>0,a,o)}}r.writeFloatLE=t.bind(null,vp),r.writeFloatBE=t.bind(null,Ep);function e(n,i,a){var o=n(i,a),l=(o>>31)*2+1,s=o>>>23&255,c=o&8388607;return s===255?c?NaN:l*(1/0):s===0?l*1401298464324817e-60*c:l*Math.pow(2,s-150)*(c+8388608)}r.readFloatLE=e.bind(null,_p),r.readFloatBE=e.bind(null,Tp)}(),typeof Float64A
|
||
|
|
`+e.join(`
|
||
|
|
`)+`
|
||
|
|
}`}return n.toString=i,n}el.verbose=!1});var sd=te((NT,od)=>{"use strict";od.exports=gi;var Yb=Bs(),Zb=qs(),tl=Zb("fs");function gi(r,t,e){return typeof t=="function"?(e=t,t={}):t||(t={}),e?!t.xhr&&tl&&tl.readFile?tl.readFile(r,function(i,a){return i&&typeof XMLHttpRequest!="undefined"?gi.xhr(r,t,e):i?e(i):e(null,t.binary?a:a.toString("utf8"))}):gi.xhr(r,t,e):Yb(gi,this,r,t)}gi.xhr=function(t,e,n){var i=new XMLHttpRequest;i.onreadystatechange=function(){if(i.readyState===4){if(i.status!==0&&i.status!==200)return n(Error("status "+i.status));if(e.binary){var o=i.response;if(!o){o=[];for(var l=0;l<i.responseText.length;++l)o.push(i.responseText.charCodeAt(l)&255)}return n(null,typeof Uint8Array!="undefined"?new Uint8Array(o):o)}return n(null,i.responseText)}},e.binary&&("overrideMimeType"in i&&i.overrideMimeType("text/plain; charset=x-user-defined"),i.responseType="arraybuffer"),i.open("GET",t),i.send()}});var ud=te(cd=>{"use strict";var nl=cd,ld=nl.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},rl=nl.normalize=function(t){t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var e=t.split("/"),n=ld(t),i="";n&&(i=e.shift()+"/");for(var a=0;a<e.length;)e[a]===".."?a>0&&e[a-1]!==".."?e.splice(--a,2):n?e.splice(a,1):++a:e[a]==="."?e.splice(a,1):++a;return i+e.join("/")};nl.resolve=function(t,e,n){return n||(e=rl(e)),ld(e)?e:(n||(t=rl(t)),(t=t.replace(/(?:\/|^)[^/]+$/,"")).length?rl(t+"/"+e):e)}});var Kr=te(pd=>{"use strict";var bi=pd,Kb=je(),Xb=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function yi(r,t){var e=0,n={};for(t|=0;e<r.length;)n[Xb[e+t]]=r[e++];return n}bi.basic=yi([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);bi.defaults=yi([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",Kb.emptyArray,null]);bi.long=yi([0,0,0,1,1],7);bi.mapKey=yi([0,0,0,5,5,0,0,0,1,1,0,2],2);bi.packed=yi([1,5,0,0,0,5,5,0,0,0,1,1,0])});var vr=te((DT,md)=>{"use strict";md.exports=xt;var Ca=Xr();((xt.prototype=Object.create(Ca.prototype)).constructor=xt).className="Field";var dd=St(),fd=Kr(),Re=je(),il,Jb=/^required|optional|repeated$/;xt.fromJSON=function(t,e){return new xt(t,e.id,e.type,e.rule,e.extend,e.options,e.comment)};function xt(r,t,e,n,i,a,o){if(Re.isObject(n)?(o=i,a=n,n=i=void 0):Re.isObject(i)&&(o=a,a=i,i=void 0),Ca.call(this,r,a),!Re.isInteger(t)||t<0)throw TypeError("id must be a non-negative integer");if(!Re.isString(e))throw TypeError("type must be a string");if(n!==void 0&&!Jb.test(n=n.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(i!==void 0&&!Re.isString(i))throw TypeError("extend must be a string");n==="proto3_optional"&&(n="optional"),this.rule=n&&n!=="optional"?n:void 0,this.type=e,this.id=t,this.extend=i||void 0,this.required=n==="required",this.optional=!this.required,this.repeated=n==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=Re.Long?fd.long[e]!==void 0:!1,this.bytes=e==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=o}Object.defineProperty(xt.prototype,"packed",{get:function(){return this._packed===null&&(this._packed=this.getOption("packed")!==!1),this._packed}});xt.prototype.setOption=function(t,e,n){return t==="packed"&&(this._packed=null),Ca.prototype.setOption.call(this,t,e,n)};xt.prototype.toJSON=function(t){var e=t?!!t.keepComments:!1;return Re.toObject(["rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",e?this.comment:void 0])};xt.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=fd.defaults[this.type])===void 0?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof il?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&this.options.default!=null&&(this.typeDefault=this.o
|
||
|
|
`,t:" "};function Kd(r){return r.replace(Iy,function(t,e){switch(e){case"\\":case"":return e;default:return Fy[e]||""}})}Xd.unescape=Kd;function Xd(r,t){r=r.toString();var e=0,n=r.length,i=1,a=0,o={},l=[],s=null;function c(k){return Error("illegal "+k+" (line "+i+")")}function u(){var k=s==="'"?Py:Ny;k.lastIndex=e-1;var O=k.exec(r);if(!O)throw c("string");return e=k.lastIndex,h(s),s=null,Kd(O[1])}function p(k){return r.charAt(k)}function f(k,O,w){var C={type:r.charAt(k++),lineEmpty:!1,leading:w},y;t?y=2:y=3;var S=k-y,D;do if(--S<0||(D=r.charAt(S))===`
|
||
|
|
`){C.lineEmpty=!0;break}while(D===" "||D===" ");for(var R=r.substring(k,O).split(Ry),M=0;M<R.length;++M)R[M]=R[M].replace(t?Dy:Sy,"").trim();C.text=R.join(`
|
||
|
|
`).trim(),o[i]=C,a=i}function d(k){var O=g(k),w=r.substring(k,O),C=/^\s*\/\//.test(w);return C}function g(k){for(var O=k;O<n&&p(O)!==`
|
||
|
|
`;)O++;return O}function m(){if(l.length>0)return l.shift();if(s)return u();var k,O,w,C,y,S=e===0;do{if(e===n)return null;for(k=!1;Oy.test(w=p(e));)if(w===`
|
||
|
|
`&&(S=!0,++i),++e===n)return null;if(p(e)==="/"){if(++e===n)throw c("comment");if(p(e)==="/")if(t){if(C=e,y=!1,d(e-1)){y=!0;do if(e=g(e),e===n||(e++,!S))break;while(d(e))}else e=Math.min(n,g(e)+1);y&&(f(C,e,S),S=!0),i++,k=!0}else{for(y=p(C=e+1)==="/";p(++e)!==`
|
||
|
|
`;)if(e===n)return null;++e,y&&(f(C,e-1,S),S=!0),++i,k=!0}else if((w=p(e))==="*"){C=e+1,y=t||p(C)==="*";do{if(w===`
|
||
|
|
`&&++i,++e===n)throw c("comment");O=w,w=p(e)}while(O!=="*"||w!=="/");++e,y&&(f(C,e-2,S),S=!0),k=!0}else return"/"}}while(k);var D=e;kl.lastIndex=0;var R=kl.test(p(D++));if(!R)for(;D<n&&!kl.test(p(D));)++D;var M=r.substring(e,e=D);return(M==='"'||M==="'")&&(s=M),M}function h(k){l.push(k)}function b(){if(!l.length){var k=m();if(k===null)return null;h(k)}return l[0]}function T(k,O){var w=b(),C=w===k;if(C)return m(),!0;if(!O)throw c("token '"+w+"', '"+k+"' expected");return!1}function P(k){var O=null,w;return k===void 0?(w=o[i-1],delete o[i-1],w&&(t||w.type==="*"||w.lineEmpty)&&(O=w.leading?w.text:null)):(a<k&&b(),w=o[k],delete o[k],w&&!w.lineEmpty&&(t||w.type==="/")&&(O=w.leading?null:w.text)),O}return Object.defineProperty({next:m,peek:b,push:h,skip:T,cmnt:P},"line",{get:function(){return i}})}});var af=te((KT,nf)=>{"use strict";nf.exports=Qt;Qt.filename=null;Qt.defaults={keepCase:!1};var Ly=Nl(),Qd=Ba(),ef=La(),tf=vr(),My=Sa(),rf=Cn(),$y=St(),By=Ra(),qy=Da(),Pl=Kr(),Sl=je(),jy=/^[1-9][0-9]*$/,Uy=/^-?[1-9][0-9]*$/,Hy=/^0[x][0-9a-fA-F]+$/,Wy=/^-?0[x][0-9a-fA-F]+$/,Vy=/^0[0-7]+$/,zy=/^-?0[0-7]+$/,Gy=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,jt=/^[a-zA-Z_][a-zA-Z_0-9]*$/,Ut=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,Yy=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function Qt(r,t,e){t instanceof Qd||(e=t,t=new Qd),e||(e=Qt.defaults);var n=e.preferTrailingComment||!1,i=Ly(r,e.alternateCommentMode||!1),a=i.next,o=i.push,l=i.peek,s=i.skip,c=i.cmnt,u=!0,p,f,d,g,m=!1,h=t,b=e.keepCase?function(A){return A}:Sl.camelCase;function T(A,L,j){var z=Qt.filename;return j||(Qt.filename=null),Error("illegal "+(L||"token")+" '"+A+"' ("+(z?z+", ":"")+"line "+i.line+")")}function P(){var A=[],L;do{if((L=a())!=='"'&&L!=="'")throw T(L);A.push(a()),s(L),L=l()}while(L==='"'||L==="'");return A.join("")}function k(A){var L=a();switch(L){case"'":case'"':return o(L),P();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return w(L,!0)}catch(j){if(A&&Ut.test(L))return L;throw T(L,"value")}}function O(A,L){var j,z;do L&&((j=l())==='"'||j==="'")?A.push(P()):A.push([z=C(a()),s("to",!0)?C(a()):z]);while(s(",",!0));s(";")}function w(A,L){var j=1;switch(A.charAt(0)==="-"&&(j=-1,A=A.substring(1)),A){case"inf":case"INF":case"Inf":return j*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(jy.test(A))return j*parseInt(A,10);if(Hy.test(A))return j*parseInt(A,16);if(Vy.test(A))return j*parseInt(A,8);if(Gy.test(A))return j*parseFloat(A);throw T(A,"number",L)}function C(A,L){switch(A){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!L&&A.charAt(0)==="-")throw T(A,"id");if(Uy.test(A))return parseInt(A,10);if(Wy.test(A))return parseInt(A,16);if(zy.test(A))return parseInt(A,8);throw T(A,"id")}function y(){if(p!==void 0)throw T("package");if(p=a(),!Ut.test(p))throw T(p,"name");h=h.define(p),s(";")}function S(){var A=l(),L;switch(A){case"weak":L=d||(d=[]),a();break;case"public":a();default:L=f||(f=[]);break}A=P(),s(";"),L.push(A)}function D(){if(s("="),g=P(),m=g==="proto3",!m&&g!=="proto2")throw T(g,"syntax");s(";")}function R(A,L){switch(L){case"option":return Z(A,L),s(";"),!0;case"message":return I(A,L),!0;case"enum":return X(A,L),!0;case"service":return xe(A,L),!0;case"extend":return x(A,L),!0}return!1}function M(A,L,j){var z=i.line;if(A&&(typeof A.comment!="string"&&(A.comment=c()),A.filename=Qt.filename),s("{",!0)){for(var V;(V=a())!=="}";)L(V);s(";",!0)}else j&&j(),s(";"),A&&(typeof A.comment!="string"||n)&&(A.comment=c(z)||A.comment)}function I(A,L){if(!jt.test(L=a()))throw T(L,"type name");var j=new ef(L);M(j,function(V){if(!R(j,V))switch(V){case"map":H(j,V);break;case"required":case"repeated":q(j,V);break;case"optional":m?q(j,"proto3_optional"):q(j,"optional");break;case"oneof":W(j,V);break;case"extensions":O(j.extensions||(j.extensions=[]));break;case"reserved":O(j.reserved||(j.reserved=[]),!0);break;default:if(!m||!Ut.test(V))throw T(V);o(V),q(j,"optional");break}}),A.add(j)}function q(A,L,j){var z=a();if(z==="group"){U(A,L);return}for(;z.endsWith(".")||l().startsWith(".");)z+=a()
|
||
|
|
|
||
|
|
`+n.fence+a+`
|
||
|
|
`+e.firstChild.textContent+`
|
||
|
|
`+n.fence+`
|
||
|
|
|
||
|
|
`}})}function Rf(r){r.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(t){return"~~"+t+"~~"}})}var Cx=Array.prototype.indexOf,kx=Array.prototype.every,kr={},Nx={left:":---",right:"---:",center:":---:"},$l=null,Of=null,Sf=new WeakMap;function Px(r){return r?(r.getAttribute("align")||r.style.textAlign||"").toLowerCase():""}function If(r){return r?Nx[r]:"---"}function Ff(r,t){for(var e={left:0,right:0,center:0,"":0},n="",i=0;i<r.rows.length;++i){var a=r.rows[i];if(t<a.childNodes.length){var o=Px(a.childNodes[t]);++e[o],e[o]>e[n]&&(n=o)}}return n}kr.tableCell={filter:["th","td"],replacement:function(r,t){return ql(Bf(t))?r:Lf(r,t)}};kr.tableRow={filter:"tr",replacement:function(r,t){let e=Bf(t);if(ql(e))return r;var n="";if(Sx(t)){let o=qf(e);for(var i=0;i<o;i++){let l=i<t.childNodes.length?t.childNodes[i]:null;var a=If(Ff(e,i));n+=Lf(a,l,i)}}return`
|
||
|
|
`+r+(n?`
|
||
|
|
`+n:"")}};kr.table={filter:function(r,t){return r.nodeName==="TABLE"},replacement:function(r,t){if($f(t,Of)){let l=t.outerHTML,s=Ox(t);return s===null||!s.classList.contains("joplin-table-wrapper")?`
|
||
|
|
|
||
|
|
<div class="joplin-table-wrapper">${l}</div>
|
||
|
|
|
||
|
|
`:l}else{if(ql(t))return r;r=r.replace(/\n+/g,`
|
||
|
|
`);var e=r.trim().split(`
|
||
|
|
`);e.length>=2&&(e=e[1]);var n=/\| :?---/.test(e),i=qf(t),a="";if(i&&!n){a="|"+" |".repeat(i)+`
|
||
|
|
|`;for(var o=0;o<i;++o)a+=" "+If(Ff(t,o))+" |"}let l=t.caption&&t.caption.textContent||"",s=l?`${l}
|
||
|
|
|
||
|
|
`:"",c=`${a}${r}`.trimStart();return`
|
||
|
|
|
||
|
|
${s}${c}
|
||
|
|
|
||
|
|
`}}};kr.tableCaption={filter:["caption"],replacement:()=>""};kr.tableColgroup={filter:["colgroup","col"],replacement:()=>""};kr.tableSection={filter:["thead","tbody","tfoot"],replacement:function(r){return r}};function Sx(r){var t=r.parentNode;return t.nodeName==="THEAD"||t.firstChild===r&&(t.nodeName==="TABLE"||Dx(t))&&kx.call(r.childNodes,function(e){return e.nodeName==="TH"})}function Dx(r){var t=r.previousSibling;return r.nodeName==="TBODY"&&(!t||t.nodeName==="THEAD"&&/^\s*$/i.test(t.textContent))}function Lf(r,t=null,e=null){e===null&&(e=Cx.call(t.parentNode.childNodes,t));var n=" ";e===0&&(n="| ");let i=r.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");for(i=i.replace(/\|+/g,"\\|");i.length<3;)i+=" ";return t&&(i=Ix(i,t," ")),n+i+" |"}function Mf(r){if(!r.childNodes)return!1;for(let t=0;t<r.childNodes.length;t++){let e=r.childNodes[t];if(e.nodeName==="TABLE"||Mf(e))return!0}return!1}var Bl=(r,t)=>{if(!r.childNodes)return!1;for(let e=0;e<r.childNodes.length;e++){let n=r.childNodes[e];if(t==="code"&&$l&&$l(n)||t.includes(n.nodeName)||Bl(n,t))return!0}return!1},$f=(r,t)=>{let e=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];return t.preserveNestedTables&&e.push("TABLE"),Bl(r,"code")||Bl(r,e)};function ql(r){let t=Sf.get(r);if(t!==void 0)return t;let e=Rx(r);return Sf.set(r,e),e}function Rx(r){return!!(!r||!r.rows||r.rows.length===1&&r.rows[0].childNodes.length<=1||Mf(r))}function Ox(r){let t=r.parentNode;for(;t.nodeName!=="DIV";)if(t=t.parentNode,!t)return null;return t}function Bf(r){let t=r.parentNode;for(;t.nodeName!=="TABLE";)if(t=t.parentNode,!t)return null;return t}function Ix(r,t,e){let n=t.getAttribute("colspan")||1;for(let i=1;i<n;i++)r+=" | "+e.repeat(3);return r}function qf(r){let t=0;for(let e=0;e<r.rows.length;e++){let i=r.rows[e].childNodes.length;i>t&&(t=i)}return t}function jf(r){$l=r.isCodeBlock,Of=r.options,r.keep(function(e){return!!(e.nodeName==="TABLE"&&$f(e,r.options))});for(var t in kr)r.addRule(t,kr[t])}function Uf(r){r.addRule("taskListItems",{filter:function(t){return t.type==="checkbox"&&t.parentNode.nodeName==="LI"},replacement:function(t,e){return(e.checked?"[x]":"[ ]")+" "}})}function Fx(r){r.use([Df,Rf,jf,Uf])}en.gfm=Fx;en.highlightedCodeBlock=Df;en.strikethrough=Rf;en.tables=jf;en.taskListItems=Uf});var Th=te(ao=>{(function(r){r.parser=function(E,x){return new e(E,x)},r.SAXParser=e,r.SAXStream=c,r.createStream=s,r.MAX_BUFFER_LENGTH=64*1024;var t=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];r.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function e(E,x){if(!(this instanceof e))return new e(E,x);var F=this;i(F),F.q=F.c="",F.bufferCheckPosition=r.MAX_BUFFER_LENGTH,F.opt=x||{},F.opt.lowercase=F.opt.lowercase||F.opt.lowercasetags,F.looseCase=F.opt.lowercase?"toLowerCase":"toUpperCase",F.tags=[],F.closed=F.closedRoot=F.sawRoot=!1,F.tag=F.error=null,F.strict=!!E,F.noscript=!!(E||F.opt.noscript),F.state=y.BEGIN,F.strictEntities=F.opt.strictEntities,F.ENTITIES=F.strictEntities?Object.create(r.XML_ENTITIES):Object.create(r.ENTITIES),F.attribList=[],F.opt.xmlns&&(F.ns=Object.create(g)),F.opt.unquotedAttributeValues===void 0&&(F.opt.unquotedAttributeValues=!E),F.trackPosition=F.opt.position!==!1,F.trackPosition&&(F.position=F.line=F.column=0),D(F,"onready")}Object.create||(Object.create=function(E){function x(){}x.prototype=E;var F=new x;return F}),Object.keys||(Object.keys=function(E){var x=[];for(var F in E)E.hasOwnProperty(F)&&x.push(F);return x});function n(E){for(var x=Math.max(r.MAX_BUFFER_LENGTH,10),F=0,A=0,L=t.length;A<L;A++){var j=E[t[A]].length;if(j>x)switch(t[A]){case"textNode":M(E);break;case"cdata":R(E,"oncdata",E.cdata),E.cdata="";break;case"script":R(E,"onscript",E.script),E.script="";break;default:q(E,"Max buffer length exceeded: "+t[A])}F=Math.max(F,j)}var z=r.MAX_BUFFER_LENGTH-F;E.bufferCheckPositi
|
||
|
|
`||E==="\r"||E===" "}function k(E){return E==='"'||E==="'"}function O(E){return E===">"||P(E)}function w(E,x){return E.test(x)}function C(E,x){return!w(E,x)}var y=0;r.STATE={BEGIN:y++,BEGIN_WHITESPACE:y++,TEXT:y++,TEXT_ENTITY:y++,OPEN_WAKA:y++,SGML_DECL:y++,SGML_DECL_QUOTED:y++,DOCTYPE:y++,DOCTYPE_QUOTED:y++,DOCTYPE_DTD:y++,DOCTYPE_DTD_QUOTED:y++,COMMENT_STARTING:y++,COMMENT:y++,COMMENT_ENDING:y++,COMMENT_ENDED:y++,CDATA:y++,CDATA_ENDING:y++,CDATA_ENDING_2:y++,PROC_INST:y++,PROC_INST_BODY:y++,PROC_INST_ENDING:y++,OPEN_TAG:y++,OPEN_TAG_SLASH:y++,ATTRIB:y++,ATTRIB_NAME:y++,ATTRIB_NAME_SAW_WHITE:y++,ATTRIB_VALUE:y++,ATTRIB_VALUE_QUOTED:y++,ATTRIB_VALUE_CLOSED:y++,ATTRIB_VALUE_UNQUOTED:y++,ATTRIB_VALUE_ENTITY_Q:y++,ATTRIB_VALUE_ENTITY_U:y++,CLOSE_TAG:y++,CLOSE_TAG_SAW_WHITE:y++,SCRIPT:y++,SCRIPT_ENDING:y++},r.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},r.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(r.ENTITIES).forEach(function(E){var x=r.ENTITIES[E],F=typeof x=="number"?String.fromCharCode(x):x;r.ENTITIES[E]=F});for(var S in r.STATE)r.STATE[r.STATE[S]]=S;y=r.STATE;function D(E,x,F){E[x]&&E[x](F)}function R(E,x,F){E.textNode&&M(E),D(E,x,F)}function M(E){E.textNode=I(E.opt,E.textNode),E.textNode&&D(E,"ontext",E.textNode),E.textNode=""}function I(E,x){return E.trim&&(x=x.trim()),E.normalize&&(x=x.replace(/\s+/g," ")),x}function q(E,x){return M(E),E.trackPosition&&(x+=`
|
||
|
|
Line: `+E.line+`
|
||
|
|
Column: `+E.column+`
|
||
|
|
Char: `+E.c),x=new Error(x),E.error=x,D(E,"onerror",x),E}function U(E){return E.sawRoot&&!E.closedRoot&&H(E,"Unclosed root tag"),E.state!==y.BEGIN&&E.state!==y.BEGIN_WHITESPACE&&E.state!==y.TEXT&&q(E,"Unexpected end"),M(E),E.c="",E.closed=!0,D(E,"onend"),e.call(E,E.strict,E.opt),E}function H(E,x){if(typeof E!="object"||!(E instanceof e))throw new Error("bad call to strictFail");E.strict&&q(E,x)}function W(E){E.strict||(E.tagName=E.tagName[E.looseCase]());var x=E.tags[E.tags.length-1]||E,F=E.tag={name:E.tagName,attributes:{}};E.opt.xmlns&&(F.ns=x.ns),E.attribList.length=0,R(E,"onopentagstart",F)}function X(E,x){var F=E.indexOf(":"),A=F<0?["",E]:E.split(":"),L=A[0],j=A[1];return x&&E==="xmlns"&&(L="xmlns",j=""),{prefix:L,local:j}}function se(E){if(E.strict||(E.attribName=E.attribName[E.looseCase]()),E.attribList.indexOf(E.attribName)!==-1||E.tag.attributes.hasOwnProperty(E.attribName)){E.attribName=E.attribValue="";return}if(E.opt.xmlns){var x=X(E.attribName,!0),F=x.prefix,A=x.local;if(F==="xmlns")if(A==="xml"&&E.attribValue!==f)H(E,"xml: prefix must be bound to "+f+`
|
||
|
|
Actual: `+E.attribValue);else if(A==="xmlns"&&E.attribValue!==d)H(E,"xmlns: prefix must be bound to "+d+`
|
||
|
|
Actual: `+E.attribValue);else{var L=E.tag,j=E.tags[E.tags.length-1]||E;L.ns===j.ns&&(L.ns=Object.create(j.ns)),L.ns[A]=E.attribValue}E.attribList.push([E.attribName,E.attribValue])}else E.tag.attributes[E.attribName]=E.attribValue,R(E,"onattribute",{name:E.attribName,value:E.attribValue});E.attribName=E.attribValue=""}function Z(E,x){if(E.opt.xmlns){var F=E.tag,A=X(E.tagName);F.prefix=A.prefix,F.local=A.local,F.uri=F.ns[A.prefix]||"",F.prefix&&!F.uri&&(H(E,"Unbound namespace prefix: "+JSON.stringify(E.tagName)),F.uri=A.prefix);var L=E.tags[E.tags.length-1]||E;F.ns&&L.ns!==F.ns&&Object.keys(F.ns).forEach(function(Ne){R(E,"onopennamespace",{prefix:Ne,uri:F.ns[Ne]})});for(var j=0,z=E.attribList.length;j<z;j++){var V=E.attribList[j],G=V[0],de=V[1],fe=X(G,!0),we=fe.prefix,ft=fe.local,Vt=we===""?"":F.ns[we]||"",ve={name:G,value:de,prefix:we,local:ft,uri:Vt};we&&we!=="xmlns"&&!Vt&&(H(E,"Unbound namespace prefix: "+JSON.stringify(we)),ve.uri=we),E.tag.attributes[G]=ve,R(E,"onattribute",ve)}E.attribList.length=0}E.tag.isSelfClosing=!!x,E.sawRoot=!0,E.tags.push(E.tag),R(E,"onopentag",E.tag),x||(!E.noscript&&E.tagName.toLowerCase()==="script"?E.state=y.SCRIPT:E.state=y.TEXT,E.tag=null,E.tagName=""),E.attribName=E.attribValue="",E.attribList.length=0}function pe(E){if(!E.tagName){H(E,"Weird empty close tag."),E.textNode+="</>",E.state=y.TEXT;return}if(E.script){if(E.tagName!=="script"){E.script+="</"+E.tagName+">",E.tagName="",E.state=y.SCRIPT;return}R(E,"onscript",E.script),E.script=""}var x=E.tags.length,F=E.tagName;E.strict||(F=F[E.looseCase]());for(var A=F;x--;){var L=E.tags[x];if(L.name!==A)H(E,"Unexpected close tag");else break}if(x<0){H(E,"Unmatched closing tag: "+E.tagName),E.textNode+="</"+E.tagName+">",E.state=y.TEXT;return}E.tagName=F;for(var j=E.tags.length;j-- >x;){var z=E.tag=E.tags.pop();E.tagName=E.tag.name,R(E,"onclosetag",E.tagName);var V={};for(var G in z.ns)V[G]=z.ns[G];var de=E.tags[E.tags.length-1]||E;E.opt.xmlns&&z.ns!==de.ns&&Object.keys(z.ns).forEach(function(fe){var we=z.ns[fe];R(E,"onclosenamespace",{prefix:fe,uri:we})})}x===0&&(E.closedRoot=!0),E.tagName=E.attribValue=E.attribName="",E.attribList.length=0,E.state=y.TEXT}function ie(E){var x=E.entity,F=x.toLowerCase(),A,L="";return E.ENTITIES[x]?E.ENTITIES[x]:E.ENTITIES[F]?E.ENTITIES[F]:(x=F,x.charAt(0)==="#"&&(x.charAt(1)==="x"?(x=x.slice(2),A=parseInt(x,16),L=A.toString(16)):(x=x.slice(1),A=parseInt(x,10),L=A.toString(10))),x=x.replace(/^0+/,""),isNaN(A)||L.toLowerCase()!==x||A<0||A>1114111?(H(E,"Invalid character entity"),"&"+E.entity+";"):String.fromCodePoint(A))}function ce(E,x){x==="<"?(E.state=y.OPEN_WAKA,E.startTagPosition=E.position):P(x)||(H(E,"Non-whitespace before first tag."),E.textNode=x,E.state=y.TEXT)}function ye(E,x){var F="";return x<E.length&&(F=E.charAt(x)),F}function xe(E){var x=this;if(this.error)throw this.error;if(x.closed)return q(x,"Cannot write after close. Assign an onready handler.");if(E===null)return U(x);typeof E=="object"&&(E=E.toString());for(var F=0,A="";A=ye(E,F++),x.c=A,!!A;)switch(x.trackPosition&&(x.position++,A===`
|
||
|
|
`?(x.line++,x.column=0):x.column++),x.state){case y.BEGIN:if(x.state=y.BEGIN_WHITESPACE,A==="\uFEFF")continue;ce(x,A);continue;case y.BEGIN_WHITESPACE:ce(x,A);continue;case y.TEXT:if(x.sawRoot&&!x.closedRoot){for(var j=F-1;A&&A!=="<"&&A!=="&";)A=ye(E,F++),A&&x.trackPosition&&(x.position++,A===`
|
||
|
|
`?(x.line++,x.column=0):x.column++);x.textNode+=E.substring(j,F-1)}A==="<"&&!(x.sawRoot&&x.closedRoot&&!x.strict)?(x.state=y.OPEN_WAKA,x.startTagPosition=x.position):(!P(A)&&(!x.sawRoot||x.closedRoot)&&H(x,"Text data outside of root node."),A==="&"?x.state=y.TEXT_ENTITY:x.textNode+=A);continue;case y.SCRIPT:A==="<"?x.state=y.SCRIPT_ENDING:x.script+=A;continue;case y.SCRIPT_ENDING:A==="/"?x.state=y.CLOSE_TAG:(x.script+="<"+A,x.state=y.SCRIPT);continue;case y.OPEN_WAKA:if(A==="!")x.state=y.SGML_DECL,x.sgmlDecl="";else if(!P(A))if(w(m,A))x.state=y.OPEN_TAG,x.tagName=A;else if(A==="/")x.state=y.CLOSE_TAG,x.tagName="";else if(A==="?")x.state=y.PROC_INST,x.procInstName=x.procInstBody="";else{if(H(x,"Unencoded <"),x.startTagPosition+1<x.position){var L=x.position-x.startTagPosition;A=new Array(L).join(" ")+A}x.textNode+="<"+A,x.state=y.TEXT}continue;case y.SGML_DECL:if(x.sgmlDecl+A==="--"){x.state=y.COMMENT,x.comment="",x.sgmlDecl="";continue}x.doctype&&x.doctype!==!0&&x.sgmlDecl?(x.state=y.DOCTYPE_DTD,x.doctype+="<!"+x.sgmlDecl+A,x.sgmlDecl=""):(x.sgmlDecl+A).toUpperCase()===u?(R(x,"onopencdata"),x.state=y.CDATA,x.sgmlDecl="",x.cdata=""):(x.sgmlDecl+A).toUpperCase()===p?(x.state=y.DOCTYPE,(x.doctype||x.sawRoot)&&H(x,"Inappropriately located doctype declaration"),x.doctype="",x.sgmlDecl=""):A===">"?(R(x,"onsgmldeclaration",x.sgmlDecl),x.sgmlDecl="",x.state=y.TEXT):(k(A)&&(x.state=y.SGML_DECL_QUOTED),x.sgmlDecl+=A);continue;case y.SGML_DECL_QUOTED:A===x.q&&(x.state=y.SGML_DECL,x.q=""),x.sgmlDecl+=A;continue;case y.DOCTYPE:A===">"?(x.state=y.TEXT,R(x,"ondoctype",x.doctype),x.doctype=!0):(x.doctype+=A,A==="["?x.state=y.DOCTYPE_DTD:k(A)&&(x.state=y.DOCTYPE_QUOTED,x.q=A));continue;case y.DOCTYPE_QUOTED:x.doctype+=A,A===x.q&&(x.q="",x.state=y.DOCTYPE);continue;case y.DOCTYPE_DTD:A==="]"?(x.doctype+=A,x.state=y.DOCTYPE):A==="<"?(x.state=y.OPEN_WAKA,x.startTagPosition=x.position):k(A)?(x.doctype+=A,x.state=y.DOCTYPE_DTD_QUOTED,x.q=A):x.doctype+=A;continue;case y.DOCTYPE_DTD_QUOTED:x.doctype+=A,A===x.q&&(x.state=y.DOCTYPE_DTD,x.q="");continue;case y.COMMENT:A==="-"?x.state=y.COMMENT_ENDING:x.comment+=A;continue;case y.COMMENT_ENDING:A==="-"?(x.state=y.COMMENT_ENDED,x.comment=I(x.opt,x.comment),x.comment&&R(x,"oncomment",x.comment),x.comment=""):(x.comment+="-"+A,x.state=y.COMMENT);continue;case y.COMMENT_ENDED:A!==">"?(H(x,"Malformed comment"),x.comment+="--"+A,x.state=y.COMMENT):x.doctype&&x.doctype!==!0?x.state=y.DOCTYPE_DTD:x.state=y.TEXT;continue;case y.CDATA:for(var j=F-1;A&&A!=="]";)A=ye(E,F++),A&&x.trackPosition&&(x.position++,A===`
|
||
|
|
`?(x.line++,x.column=0):x.column++);x.cdata+=E.substring(j,F-1),A==="]"&&(x.state=y.CDATA_ENDING);continue;case y.CDATA_ENDING:A==="]"?x.state=y.CDATA_ENDING_2:(x.cdata+="]"+A,x.state=y.CDATA);continue;case y.CDATA_ENDING_2:A===">"?(x.cdata&&R(x,"oncdata",x.cdata),R(x,"onclosecdata"),x.cdata="",x.state=y.TEXT):A==="]"?x.cdata+="]":(x.cdata+="]]"+A,x.state=y.CDATA);continue;case y.PROC_INST:A==="?"?x.state=y.PROC_INST_ENDING:P(A)?x.state=y.PROC_INST_BODY:x.procInstName+=A;continue;case y.PROC_INST_BODY:if(!x.procInstBody&&P(A))continue;A==="?"?x.state=y.PROC_INST_ENDING:x.procInstBody+=A;continue;case y.PROC_INST_ENDING:A===">"?(R(x,"onprocessinginstruction",{name:x.procInstName,body:x.procInstBody}),x.procInstName=x.procInstBody="",x.state=y.TEXT):(x.procInstBody+="?"+A,x.state=y.PROC_INST_BODY);continue;case y.OPEN_TAG:w(h,A)?x.tagName+=A:(W(x),A===">"?Z(x):A==="/"?x.state=y.OPEN_TAG_SLASH:(P(A)||H(x,"Invalid character in tag name"),x.state=y.ATTRIB));continue;case y.OPEN_TAG_SLASH:A===">"?(Z(x,!0),pe(x)):(H(x,"Forward-slash in opening tag not followed by >"),x.state=y.ATTRIB);continue;case y.ATTRIB:if(P(A))continue;A===">"?Z(x):A==="/"?x.state=y.OPEN_TAG_SLASH:w(m,A)?(x.attribName=A,x.attribValue="",x.state=y.ATTRIB_NAME):H(x,"Invalid attribute name");continue;case y.ATTRIB_NAME:A==="="?x.state=y.ATTRIB_VALUE:A===">"?(H(x,"Attribute without value"),x.attribValue=x.attribName,se(x),Z(x)):P(A)?x.state=y.ATTRIB_NAME_SAW_WHITE:w(h,A)?x.attribName+=A:H(x,"Invalid attribute name");continue;case y.ATTRIB_NAME_SAW_WHITE:if(A==="=")x.state=y.ATTRIB_VALUE;else{if(P(A))continue;H(x,"Attribute without value"),x.tag.attributes[x.attribName]="",x.attribValue="",R(x,"onattribute",{name:x.attribName,value:""}),x.attribName="",A===">"?Z(x):w(m,A)?(x.attribName=A,x.state=y.ATTRIB_NAME):(H(x,"Invalid attribute name"),x.state=y.ATTRIB)}continue;case y.ATTRIB_VALUE:if(P(A))continue;k(A)?(x.q=A,x.state=y.ATTRIB_VALUE_QUOTED):(x.opt.unquotedAttributeValues||q(x,"Unquoted attribute value"),x.state=y.ATTRIB_VALUE_UNQUOTED,x.attribValue=A);continue;case y.ATTRIB_VALUE_QUOTED:if(A!==x.q){A==="&"?x.state=y.ATTRIB_VALUE_ENTITY_Q:x.attribValue+=A;continue}se(x),x.q="",x.state=y.ATTRIB_VALUE_CLOSED;continue;case y.ATTRIB_VALUE_CLOSED:P(A)?x.state=y.ATTRIB:A===">"?Z(x):A==="/"?x.state=y.OPEN_TAG_SLASH:w(m,A)?(H(x,"No whitespace between attributes"),x.attribName=A,x.attribValue="",x.state=y.ATTRIB_NAME):H(x,"Invalid attribute name");continue;case y.ATTRIB_VALUE_UNQUOTED:if(!O(A)){A==="&"?x.state=y.ATTRIB_VALUE_ENTITY_U:x.attribValue+=A;continue}se(x),A===">"?Z(x):x.state=y.ATTRIB;continue;case y.CLOSE_TAG:if(x.tagName)A===">"?pe(x):w(h,A)?x.tagName+=A:x.script?(x.script+="</"+x.tagName,x.tagName="",x.state=y.SCRIPT):(P(A)||H(x,"Invalid tagname in closing tag"),x.state=y.CLOSE_TAG_SAW_WHITE);else{if(P(A))continue;C(m,A)?x.script?(x.script+="</"+A,x.state=y.SCRIPT):H(x,"Invalid tagname in closing tag."):x.tagName=A}continue;case y.CLOSE_TAG_SAW_WHITE:if(P(A))continue;A===">"?pe(x):H(x,"Invalid characters in closing tag");continue;case y.TEXT_ENTITY:case y.ATTRIB_VALUE_ENTITY_Q:case y.ATTRIB_VALUE_ENTITY_U:var z,V;switch(x.state){case y.TEXT_ENTITY:z=y.TEXT,V="textNode";break;case y.ATTRIB_VALUE_ENTITY_Q:z=y.ATTRIB_VALUE_QUOTED,V="attribValue";break;case y.ATTRIB_VALUE_ENTITY_U:z=y.ATTRIB_VALUE_UNQUOTED,V="attribValue";break}if(A===";"){var G=ie(x);x.opt.unparsedEntities&&!Object.values(r.XML_ENTITIES).includes(G)?(x.entity="",x.state=z,x.write(G)):(x[V]+=G,x.entity="",x.state=z)}else w(x.entity.length?T:b,A)?x.entity+=A:(H(x,"Invalid character in entity name"),x[V]+="&"+x.entity+A,x.entity="",x.state=z);continue;default:throw new Error(x,"Unknown state: "+x.state)}return x.position>=x.bufferCheckPosition&&n(x),x}String.fromCodePoint||function(){var E=String.fromCharCode,x=Math.floor,F=function(){var A=16384,L=[],j,z,V=-1,G=arguments.length;if(!G)return"";for(var de="";++V<G;){var fe=Number(arguments[V]);if(!isFinite(fe)||fe<0||fe>1114111||x(fe)!==fe)throw RangeError("Invalid code point: "+fe);fe<=65535?L.push(fe):(fe-=65536,j=(fe>>10)+55296,z=fe%1024+5
|
||
|
|
`:"";function l(s,c,u){let p="",f,d=c,g=u?o+u:"",m=u+e,h="";return s=s||"",s.constructor===Array?(s.forEach(b=>{p+=l(b,d,u)}),p):(!d&&s.$name&&(d=s.$name),d&&(p=`${g}<${d}`,s.$attrs&&typeof s.$attrs=="object"&&(f=Object.keys(s.$attrs),f.forEach(b=>{p+=` ${b}=${JSON.stringify(String(s.$attrs[b]))}`}))),s==null||s===""||(typeof s=="object"?(f=Object.keys(s),f.forEach(b=>{let T=s[b];switch(b){case"$name":case"$attrs":break;case"$text":case"$markup":h+=l(T,null,m);break;case"$script":h+=l(T,"script",m);break;case"$cdata":h+=`${g}<![CDATA[${T}]]>`;break;default:h+=l(T,b,m)}})):h+=g+i(s)),d?h?p+=`>${h}${o}${u}</${d}>`:n?p+="/>":p+=`></${d}>`:p+=h,p)}return l(t,a,"")};Sh.exports=Ri});var mo=te(Ii=>{"use strict";Object.defineProperty(Ii,"__esModule",{value:!0});Ii.assertNever=h2;Ii.pick=g2;Ii.isObject=b2;function h2(r){throw new Error(`Unexpected value should never occur: ${r}`)}function g2(r,t){let e=t.map(n=>[n,r==null?void 0:r[n]]);return Object.fromEntries(e)}function b2(r){return typeof r=="object"&&r!==null}});var cc=te(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.LogLevel=void 0;Hn.makeConsoleLogger=x2;Hn.logLevelSeverity=w2;var y2=mo(),Un;(function(r){r.DEBUG="debug",r.INFO="info",r.WARN="warn",r.ERROR="error"})(Un||(Hn.LogLevel=Un={}));function x2(r){return(t,e,n)=>{console[t](`${r} ${t}:`,e,n)}}function w2(r){switch(r){case Un.DEBUG:return 20;case Un.INFO:return 40;case Un.WARN:return 60;case Un.ERROR:return 80;default:return(0,y2.assertNever)(r)}}});var pc=te(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.APIResponseError=rt.UnknownHTTPResponseError=rt.RequestTimeoutError=rt.ClientErrorCode=rt.APIErrorCode=void 0;rt.isNotionClientError=rg;rt.isHTTPResponseError=E2;rt.buildRequestError=_2;var tg=mo(),Ce;(function(r){r.Unauthorized="unauthorized",r.RestrictedResource="restricted_resource",r.ObjectNotFound="object_not_found",r.RateLimited="rate_limited",r.InvalidJSON="invalid_json",r.InvalidRequestURL="invalid_request_url",r.InvalidRequest="invalid_request",r.ValidationError="validation_error",r.ConflictError="conflict_error",r.InternalServerError="internal_server_error",r.ServiceUnavailable="service_unavailable"})(Ce||(rt.APIErrorCode=Ce={}));var ln;(function(r){r.RequestTimeout="notionhq_client_request_timeout",r.ResponseError="notionhq_client_response_error"})(ln||(rt.ClientErrorCode=ln={}));var Fi=class extends Error{};function rg(r){return(0,tg.isObject)(r)&&r instanceof Fi}function yo(r,t){return rg(r)&&r.code in t}var uc=class r extends Fi{constructor(t="Request to Notion API has timed out"){super(t),this.code=ln.RequestTimeout,this.name="RequestTimeoutError"}static isRequestTimeoutError(t){return yo(t,{[ln.RequestTimeout]:!0})}static rejectAfterTimeout(t,e){return new Promise((n,i)=>{let a=setTimeout(()=>{i(new r)},e);t.then(n).catch(i).then(()=>clearTimeout(a))})}};rt.RequestTimeoutError=uc;var ho=class extends Fi{constructor(t){super(t.message),this.name="HTTPResponseError";let{code:e,status:n,headers:i,rawBodyText:a,additional_data:o,request_id:l}=t;this.code=e,this.status=n,this.headers=i,this.body=a,this.additional_data=o,this.request_id=l}},v2={[ln.ResponseError]:!0,[Ce.Unauthorized]:!0,[Ce.RestrictedResource]:!0,[Ce.ObjectNotFound]:!0,[Ce.RateLimited]:!0,[Ce.InvalidJSON]:!0,[Ce.InvalidRequestURL]:!0,[Ce.InvalidRequest]:!0,[Ce.ValidationError]:!0,[Ce.ConflictError]:!0,[Ce.InternalServerError]:!0,[Ce.ServiceUnavailable]:!0};function E2(r){return!!yo(r,v2)}var go=class extends ho{constructor(t){var e;super({...t,code:ln.ResponseError,message:(e=t.message)!==null&&e!==void 0?e:`Request to Notion API failed with status: ${t.status}`,additional_data:void 0,request_id:void 0}),this.name="UnknownHTTPResponseError"}static isUnknownHTTPResponseError(t){return yo(t,{[ln.ResponseError]:!0})}};rt.UnknownHTTPResponseError=go;var ng={[Ce.Unauthorized]:!0,[Ce.RestrictedResource]:!0,[Ce.ObjectNotFound]:!0,[Ce.RateLimited]:!0,[Ce.InvalidJSON]:!0,[Ce.InvalidRequestURL]:!0,[Ce.InvalidRequest]:!0,[Ce.ValidationError]:!0,[Ce.ConflictError]:!0,[Ce.InternalServerError]:!0,[Ce.Ser
|
||
|
|
`).replace(/[\r\u0085\u2028]/g,`
|
||
|
|
`)}function h(w){this.options=w||{locator:{}}}function b(){this.cdata=!1}function T(w,C){C.lineNumber=w.lineNumber,C.columnNumber=w.columnNumber}function P(w){if(w)return`
|
||
|
|
@`+(w.systemId||"")+"#[line:"+w.lineNumber+",col:"+w.columnNumber+"]"}function k(w,C,y){return typeof w=="string"?w.substr(C,y):w.length>=C+y||C?new java.lang.String(w,C,y)+"":w}function O(w,C){w.currentElement?w.currentElement.appendChild(C):w.doc.appendChild(C)}h.prototype.parseFromString=function(w,C){var y=this.options,S=new g,D=y.domBuilder||new b,R=y.errorHandler,M=y.locator,I=y.xmlns||{},q=/\/x?html?$/.test(C),U=q?c.HTML_ENTITIES:c.XML_ENTITIES;M&&D.setDocumentLocator(M),S.errorHandler=function(W,X,se){if(!W){if(X instanceof b)return X;W=X}var Z={},pe=W instanceof Function;function ie(ce){var ye=W[ce];!ye&&pe&&(ye=W.length==2?function(xe){W(ce,xe)}:W),Z[ce]=ye&&function(xe){ye("[xmldom "+ce+"] "+xe+P(se))}||function(){}}return se=se||{},ie("warning"),ie("error"),ie("fatalError"),Z}(R,D,M),S.domBuilder=y.domBuilder||D,q&&(I[""]=f.HTML),I.xml=I.xml||f.XML;var H=y.normalizeLineEndings||m;return w&&typeof w=="string"?S.parse(H(w),I,U):S.errorHandler.error("invalid doc source"),D.doc},b.prototype={startDocument:function(){this.doc=new p().createDocument(null,null,null),this.locator&&(this.doc.documentURI=this.locator.systemId)},startElement:function(w,C,y,S){var D=this.doc,R=D.createElementNS(w,y||C),M=S.length;O(this,R),this.currentElement=R,this.locator&&T(this.locator,R);for(var I=0;I<M;I++){w=S.getURI(I);var q=S.getValue(I),U=(y=S.getQName(I),D.createAttributeNS(w,y));this.locator&&T(S.getLocator(I),U),U.value=U.nodeValue=q,R.setAttributeNode(U)}},endElement:function(w,C,y){var S=this.currentElement;S.tagName,this.currentElement=S.parentNode},startPrefixMapping:function(w,C){},endPrefixMapping:function(w){},processingInstruction:function(w,C){var y=this.doc.createProcessingInstruction(w,C);this.locator&&T(this.locator,y),O(this,y)},ignorableWhitespace:function(w,C,y){},characters:function(w,C,y){if(w=k.apply(this,arguments)){if(this.cdata)var S=this.doc.createCDATASection(w);else S=this.doc.createTextNode(w);this.currentElement?this.currentElement.appendChild(S):/^\s*$/.test(w)&&this.doc.appendChild(S),this.locator&&T(this.locator,S)}},skippedEntity:function(w){},endDocument:function(){this.doc.normalize()},setDocumentLocator:function(w){(this.locator=w)&&(w.lineNumber=0)},comment:function(w,C,y){w=k.apply(this,arguments);var S=this.doc.createComment(w);this.locator&&T(this.locator,S),O(this,S)},startCDATA:function(){this.cdata=!0},endCDATA:function(){this.cdata=!1},startDTD:function(w,C,y){var S=this.doc.implementation;if(S&&S.createDocumentType){var D=S.createDocumentType(w,C,y);this.locator&&T(this.locator,D),O(this,D),this.doc.doctype=D}},warning:function(w){console.warn("[xmldom warning] "+w,P(this.locator))},error:function(w){console.error("[xmldom error] "+w,P(this.locator))},fatalError:function(w){throw new d(w,this.locator)}},"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(w){b.prototype[w]=function(){return null}}),a.DOMParser=h},4722:(i,a,o)=>{var l=o(4582),s=l.find,c=l.NAMESPACE;function u(v){return v!==""}function p(v,_){return v.hasOwnProperty(_)||(v[_]=!0),v}function f(v){if(!v)return[];var _=function(N){return N?N.split(/[\t\n\f\r ]+/).filter(u):[]}(v);return Object.keys(_.reduce(p,{}))}function d(v,_){for(var N in v)Object.prototype.hasOwnProperty.call(v,N)&&(_[N]=v[N])}function g(v,_){var N=v.prototype;if(!(N instanceof _)){let Y=function(){};var $=Y;Y.prototype=_.prototype,d(N,Y=new Y),v.prototype=N=Y}N.constructor!=v&&(typeof v!="function"&&console.error("unknown Class:"+v),N.constructor=v)}var m={},h=m.ELEMENT_NODE=1,b=m.ATTRIBUTE_NODE=2,T=m.TEXT_NODE=3,P=m.CDATA_SECTION_NODE=4,k=m.ENTITY_REFERENCE_NODE=5,O=m.ENTITY_NODE=6,w=m.PROCESSING_INSTRUCTION_NODE=7,C=m.COMMENT_NODE=8,y=m.DOCUMENT_NODE=9,S=m.DOCUMENT_TYPE_NODE=10,D=m.DOCUMENT_FRAGMENT_NODE=11,R=m.NOTATION_NODE=12,M={},I={},q=(M.INDEX_SIZE_ERR=(I[1]="Index size error",1),M.DOMSTRING_SIZE_ERR=(I[2]="DOMString size error",2),M.HIERARCHY_REQUEST_ERR=(I[3]="Hierarchy request error",3)),U=(M.WRONG_DOCUMENT_ERR
|
||
|
|
`,nexist:"\u2204",nexists:"\u2204",Nfr:"\u{1D511}",nfr:"\u{1D52B}",ngE:"\u2267\u0338",nge:"\u2271",ngeq:"\u2271",ngeqq:"\u2267\u0338",ngeqslant:"\u2A7E\u0338",nges:"\u2A7E\u0338",nGg:"\u22D9\u0338",ngsim:"\u2275",nGt:"\u226B\u20D2",ngt:"\u226F",ngtr:"\u226F",nGtv:"\u226B\u0338",nhArr:"\u21CE",nharr:"\u21AE",nhpar:"\u2AF2",ni:"\u220B",nis:"\u22FC",nisd:"\u22FA",niv:"\u220B",NJcy:"\u040A",njcy:"\u045A",nlArr:"\u21CD",nlarr:"\u219A",nldr:"\u2025",nlE:"\u2266\u0338",nle:"\u2270",nLeftarrow:"\u21CD",nleftarrow:"\u219A",nLeftrightarrow:"\u21CE",nleftrightarrow:"\u21AE",nleq:"\u2270",nleqq:"\u2266\u0338",nleqslant:"\u2A7D\u0338",nles:"\u2A7D\u0338",nless:"\u226E",nLl:"\u22D8\u0338",nlsim:"\u2274",nLt:"\u226A\u20D2",nlt:"\u226E",nltri:"\u22EA",nltrie:"\u22EC",nLtv:"\u226A\u0338",nmid:"\u2224",NoBreak:"\u2060",NonBreakingSpace:"\xA0",Nopf:"\u2115",nopf:"\u{1D55F}",Not:"\u2AEC",not:"\xAC",NotCongruent:"\u2262",NotCupCap:"\u226D",NotDoubleVerticalBar:"\u2226",NotElement:"\u2209",NotEqual:"\u2260",NotEqualTilde:"\u2242\u0338",NotExists:"\u2204",NotGreater:"\u226F",NotGreaterEqual:"\u2271",NotGreaterFullEqual:"\u2267\u0338",NotGreaterGreater:"\u226B\u0338",NotGreaterLess:"\u2279",NotGreaterSlantEqual:"\u2A7E\u0338",NotGreaterTilde:"\u2275",NotHumpDownHump:"\u224E\u0338",NotHumpEqual:"\u224F\u0338",notin:"\u2209",notindot:"\u22F5\u0338",notinE:"\u22F9\u0338",notinva:"\u2209",notinvb:"\u22F7",notinvc:"\u22F6",NotLeftTriangle:"\u22EA",NotLeftTriangleBar:"\u29CF\u0338",NotLeftTriangleEqual:"\u22EC",NotLess:"\u226E",NotLessEqual:"\u2270",NotLessGreater:"\u2278",NotLessLess:"\u226A\u0338",NotLessSlantEqual:"\u2A7D\u0338",NotLessTilde:"\u2274",NotNestedGreaterGreater:"\u2AA2\u0338",NotNestedLessLess:"\u2AA1\u0338",notni:"\u220C",notniva:"\u220C",notnivb:"\u22FE",notnivc:"\u22FD",NotPrecedes:"\u2280",NotPrecedesEqual:"\u2AAF\u0338",NotPrecedesSlantEqual:"\u22E0",NotReverseElement:"\u220C",NotRightTriangle:"\u22EB",NotRightTriangleBar:"\u29D0\u0338",NotRightTriangleEqual:"\u22ED",NotSquareSubset:"\u228F\u0338",NotSquareSubsetEqual:"\u22E2",NotSquareSuperset:"\u2290\u0338",NotSquareSupersetEqual:"\u22E3",NotSubset:"\u2282\u20D2",NotSubsetEqual:"\u2288",NotSucceeds:"\u2281",NotSucceedsEqual:"\u2AB0\u0338",NotSucceedsSlantEqual:"\u22E1",NotSucceedsTilde:"\u227F\u0338",NotSuperset:"\u2283\u20D2",NotSupersetEqual:"\u2289",NotTilde:"\u2241",NotTildeEqual:"\u2244",NotTildeFullEqual:"\u2247",NotTildeTilde:"\u2249",NotVerticalBar:"\u2224",npar:"\u2226",nparallel:"\u2226",nparsl:"\u2AFD\u20E5",npart:"\u2202\u0338",npolint:"\u2A14",npr:"\u2280",nprcue:"\u22E0",npre:"\u2AAF\u0338",nprec:"\u2280",npreceq:"\u2AAF\u0338",nrArr:"\u21CF",nrarr:"\u219B",nrarrc:"\u2933\u0338",nrarrw:"\u219D\u0338",nRightarrow:"\u21CF",nrightarrow:"\u219B",nrtri:"\u22EB",nrtrie:"\u22ED",nsc:"\u2281",nsccue:"\u22E1",nsce:"\u2AB0\u0338",Nscr:"\u{1D4A9}",nscr:"\u{1D4C3}",nshortmid:"\u2224",nshortparallel:"\u2226",nsim:"\u2241",nsime:"\u2244",nsimeq:"\u2244",nsmid:"\u2224",nspar:"\u2226",nsqsube:"\u22E2",nsqsupe:"\u22E3",nsub:"\u2284",nsubE:"\u2AC5\u0338",nsube:"\u2288",nsubset:"\u2282\u20D2",nsubseteq:"\u2288",nsubseteqq:"\u2AC5\u0338",nsucc:"\u2281",nsucceq:"\u2AB0\u0338",nsup:"\u2285",nsupE:"\u2AC6\u0338",nsupe:"\u2289",nsupset:"\u2283\u20D2",nsupseteq:"\u2289",nsupseteqq:"\u2AC6\u0338",ntgl:"\u2279",Ntilde:"\xD1",ntilde:"\xF1",ntlg:"\u2278",ntriangleleft:"\u22EA",ntrianglelefteq:"\u22EC",ntriangleright:"\u22EB",ntrianglerighteq:"\u22ED",Nu:"\u039D",nu:"\u03BD",num:"#",numero:"\u2116",numsp:"\u2007",nvap:"\u224D\u20D2",nVDash:"\u22AF",nVdash:"\u22AE",nvDash:"\u22AD",nvdash:"\u22AC",nvge:"\u2265\u20D2",nvgt:">\u20D2",nvHarr:"\u2904",nvinfin:"\u29DE",nvlArr:"\u2902",nvle:"\u2264\u20D2",nvlt:"<\u20D2",nvltrie:"\u22B4\u20D2",nvrArr:"\u2903",nvrtrie:"\u22B5\u20D2",nvsim:"\u223C\u20D2",nwarhk:"\u2923",nwArr:"\u21D6",nwarr:"\u2196",nwarrow:"\u2196",nwnear:"\u2927",Oacute:"\xD3",oacute:"\xF3",oast:"\u229B",ocir:"\u229A",Ocirc:"\xD4",ocirc:"\xF4",Ocy:"\u041E",ocy:"\u043E",odash:"\u229D",Odblac:"\u0150",odblac:"\u0151",odiv:"\u2A38",odot:"\u2299",odsold:"\u29BC",OElig:"\u0152",oelig:"\u01
|
||
|
|
${d.join("")}
|
||
|
|
\\end{${g}}`;return g===this._genericCommand?this.separators.wrap(m):m}get _command(){return this.separators.areParentheses()?"pmatrix":this.separators.areSquareBrackets()?"bmatrix":this.separators.areBrackets()?"Bmatrix":this.separators.areDivides()?"vmatrix":this.separators.areParallels()?"Vmatrix":this.separators.areNotEqual()?this._genericCommand:"bmatrix"}}class p{constructor(d,g){this.open=d,this.close=g}wrap(d){return new s.GenericWrapper(this.open,this.close).wrap(d)}areParentheses(){return this._compare("(",")")}areSquareBrackets(){return this._compare("[","]")}areBrackets(){return this._compare("{","}")}areDivides(){return this._compare("|","|")}areParallels(){return this._compare("||","||")}areNotEqual(){return this.open!==this.close}_compare(d,g){return this.open===d&&this.close===g}}},6440:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MFrac=void 0;let l=o(8917),s=o(4279);a.MFrac=class{constructor(c){this._mathmlElement=c}convert(){let{children:c,name:u}=this._mathmlElement,p=c.length;if(p!==2)throw new l.InvalidNumberOfChildrenError(u,2,p);let f=(0,s.mathMLElementToLaTeXConverter)(c[0]).convert(),d=(0,s.mathMLElementToLaTeXConverter)(c[1]).convert();return this._isBevelled()?`${this._wrapIfMoreThanOneChar(f)}/${this._wrapIfMoreThanOneChar(d)}`:`\\frac{${f}}{${d}}`}_wrapIfMoreThanOneChar(c){return new s.ParenthesisWrapper().wrapIfMoreThanOneChar(c)}_isBevelled(){return!!this._mathmlElement.attributes.bevelled}}},7037:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MI=void 0;let l=o(4279),s=o(5406),c=o(6122);a.MI=class{constructor(p){this.utf8Converter=new c.HashUTF8ToLtXConverter,this._mathmlElement=p}convert(){let p=(0,l.normalizeWhiteSpaces)(this._mathmlElement.value);if(p===" ")return u.apply(p);let f=p.trim(),d=u.apply(f),g=this.utf8Converter.convert(d);return g!==d?g:this.wrapInMathVariant(d,this.getMathVariant(this._mathmlElement.attributes))}getMathVariant(p){if(p&&p.mathvariant)return p.mathvariant}wrapInMathVariant(p,f){switch(f){case"bold":return`\\mathbf{${p}}`;case"italic":return`\\mathit{${p}}`;case"bold-italic":return`\\mathbf{\\mathit{${p}}}`;case"double-struck":return`\\mathbb{${p}}`;case"bold-fraktur":return`\\mathbf{\\mathfrak{${p}}}`;case"script":return`\\mathcal{${p}}`;case"bold-script":return`\\mathbf{\\mathcal{${p}}}`;case"fraktur":return`\\mathfrak{${p}}`;case"sans-serif":return`\\mathsf{${p}}`;case"bold-sans-serif":return`\\mathbf{\\mathsf{${p}}}`;case"sans-serif-italic":return`\\mathsf{\\mathit{${p}}}`;case"sans-serif-bold-italic":return`\\mathbf{\\mathsf{\\mathit{${p}}}}`;case"monospace":return`\\mathtt{${p}}`;default:return p}}};class u{constructor(f){this._value=f}static apply(f){return new u(f)._apply()}_apply(){return this._findByCharacter()||this._findByGlyph()||this._findByNumber()||new c.HashUTF8ToLtXConverter().convert(this._value)}_findByCharacter(){return s.allMathSymbolsByChar[this._value]}_findByGlyph(){return s.allMathSymbolsByGlyph[this._value]}_findByNumber(){return s.mathNumberByGlyph[this._value]}}},8303:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MMultiscripts=void 0;let l=o(4279),s=o(8917);a.MMultiscripts=class{constructor(c){this._mathmlElement=c}convert(){let{name:c,children:u}=this._mathmlElement,p=u.length;if(p<3)throw new s.InvalidNumberOfChildrenError(c,3,p,"at least");let f=(0,l.mathMLElementToLaTeXConverter)(u[0]).convert();return this._prescriptLatex()+this._wrapInParenthesisIfThereIsSpace(f)+this._postscriptLatex()}_prescriptLatex(){let{children:c}=this._mathmlElement,u,p;if(this._isPrescripts(c[1]))u=c[2],p=c[3];else{if(!this._isPrescripts(c[3]))return"";u=c[4],p=c[5]}return`\\_{${(0,l.mathMLElementToLaTeXConverter)(u).convert()}}^{${(0,l.mathMLElementToLaTeXConverter)(p).convert()}}`}_postscriptLatex(){let{children:c}=this._mathmlElement;if(this._isPrescripts(c[1]))return"";let u=c[1],p=c[2];return`_{${(0,l.mathMLElementToLaTeXConverter)(u).convert()}}^{${(0,l.mathMLElementToLaTeXConverter)(p).convert()}}`}_wrapInParenthesisIfThereIsSpace(c){return c.match(/\s+/g)?new l
|
||
|
|
`);return this._hasFlag("innerTable")?this._wrap(s):s}_wrap(s){return`\\begin{matrix}${s}\\end{matrix}`}_addFlagRecursiveIfName(s,c,u){s.forEach(p=>{p.name===c&&(p.attributes[u]=u),this._addFlagRecursiveIfName(p.children,c,u)})}_hasFlag(s){return!!this._mathmlElement.attributes[s]}}},3951:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MText=void 0;let l=o(7037);a.MText=class{constructor(c){this._mathmlElement=c}convert(){let{attributes:c,value:u}=this._mathmlElement;return[...u].map(p=>/^[a-zA-Z0-9]$/.test(p)||p===" "?{value:p,isAlphanumeric:!0}:{value:p,isAlphanumeric:!1}).reduce((p,f)=>{if(f.isAlphanumeric){let d=p[p.length-1];if(d&&d.isAlphanumeric)return d.value+=f.value,p}return[...p,f]},[]).map(p=>p.isAlphanumeric?new s(c.mathvariant).apply(p.value):new l.MI({name:"mi",attributes:{},children:[],value:p.value}).convert()).join("")}};class s{constructor(u){this._mathvariant=u||"normal"}apply(u){return this._commands.reduce((p,f,d)=>d===0?`${f}{${u}}`:`${f}{${p}}`,"")}get _commands(){switch(this._mathvariant){case"bold":return["\\textbf"];case"italic":return["\\textit"];case"bold-italic":return["\\textit","\\textbf"];case"double-struck":return["\\mathbb"];case"monospace":return["\\mathtt"];case"bold-fraktur":case"fraktur":return["\\mathfrak"];default:return["\\text"]}}}},1586:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MTr=void 0;let l=o(4279);a.MTr=class{constructor(s){this._mathmlElement=s}convert(){return this._mathmlElement.children.map(s=>(0,l.mathMLElementToLaTeXConverter)(s)).map(s=>s.convert()).join(" & ")}}},1222:(i,a,o)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.MUnderover=void 0;let l=o(4279),s=o(8917);a.MUnderover=class{constructor(c){this._mathmlElement=c}convert(){let{name:c,children:u}=this._mathmlElement,p=u.length;if(p!==3)throw new s.InvalidNumberOfChildrenError(c,3,p);return`${(0,l.mathMLElementToLaTeXConverter)(u[0]).convert()}_{${(0,l.mathMLElementToLaTeXConverter)(u[1]).convert()}}^{${(0,l.mathMLElementToLaTeXConverter)(u[2]).convert()}}`}}},9165:(i,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.Void=void 0,a.Void=class{constructor(o){this._mathmlElement=o}convert(){return""}}},5443:function(i,a,o){"use strict";var l=this&&this.__createBinding||(Object.create?function(d,g,m,h){h===void 0&&(h=m);var b=Object.getOwnPropertyDescriptor(g,m);b&&!("get"in b?!g.__esModule:b.writable||b.configurable)||(b={enumerable:!0,get:function(){return g[m]}}),Object.defineProperty(d,h,b)}:function(d,g,m,h){h===void 0&&(h=m),d[h]=g[m]}),s=this&&this.__setModuleDefault||(Object.create?function(d,g){Object.defineProperty(d,"default",{enumerable:!0,value:g})}:function(d,g){d.default=g}),c=this&&this.__importStar||function(d){if(d&&d.__esModule)return d;var g={};if(d!=null)for(var m in d)m!=="default"&&Object.prototype.hasOwnProperty.call(d,m)&&l(g,d,m);return s(g,d),g};Object.defineProperty(a,"__esModule",{value:!0}),a.MathMLElementToLatexConverterAdapter=void 0;let u=c(o(6959)),p=o(2697);a.MathMLElementToLatexConverterAdapter=class{constructor(d){this._mathMLElement=d!=null?d:new p.VoidMathMLElement}toLatexConverter(){let{name:d}=this._mathMLElement;return new(f[d]||u.GenericSpacingWrapper)(this._mathMLElement)}};let f={math:u.Math,mi:u.MI,mo:u.MO,mn:u.MN,msqrt:u.MSqrt,mfenced:u.MFenced,mfrac:u.MFrac,mroot:u.MRoot,maction:u.MAction,menclose:u.MEnclose,merror:u.MError,mphantom:u.MPhantom,msup:u.MSup,msub:u.MSub,msubsup:u.MSubsup,mmultiscripts:u.MMultiscripts,mtext:u.MText,munderover:u.MUnderover,mtable:u.MTable,mtr:u.MTr,mover:u.GenericUnderOver,munder:u.GenericUnderOver,mrow:u.MRow,mspace:u.MSpace,mpadded:u.GenericSpacingWrapper,void:u.Void}},5243:(i,a)=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0}),a.ErrorHandler=void 0,a.ErrorHandler=class{constructor(){this._errors=[],this.errorLocator={}}fixError(o,l){return this._isMissingAttributeValueError(l)?(this._errors.push(l),this._fixMissingAttribute(l,o)):o}isThereAnyErrors(){return this._errors.length>0}cleanErrors(){this._errors=[]}_fixMissingAttribut
|
||
|
|
SELECT z_pk, zmedia, ztypeuti FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${a}`,l=await this.importer.resolveAttachment(o.Z_PK,"com.apple.notes.gallery");if(l||(l=await this.importer.resolveAttachment(o.ZMEDIA,o.ZTYPEUTI)),l)n.push(this.importer.app.fileManager.generateMarkdownLink(l,e));else return"**Cannot decode scan**"}return`
|
||
|
|
${n.join(`
|
||
|
|
`)}
|
||
|
|
`}};Zn.protobufType="ciofecaforensics.MergableDataProto";var Kn=class extends lr{constructor(e,n){super(e);this.rowLocations={};this.columnLocations={};this.table=n.mergableDataObject;let i=this.table.mergeableDataObjectData;this.keys=i.mergeableDataObjectKeyItem,this.types=i.mergeableDataObjectTypeItem,this.uuids=i.mergeableDataObjectUuidItem.map(this.uuidToString),this.objects=i.mergeableDataObjectEntry}async parse(){let e=this.objects.find(i=>i.customMap&&this.types[i.customMap.type]=="com.apple.notes.ICTable");if(!e)return null;let n=null;for(let i of e.customMap.mapEntry){let a=this.objects[i.value.objectIndex];switch(this.keys[i.key]){case"crRows":[this.rowLocations,this.rowCount]=this.findLocations(a);break;case"crColumns":[this.columnLocations,this.columnCount]=this.findLocations(a);break;case"cellColumns":n=a;break}}return n?await this.computeCells(n):null}findLocations(e){let n=[],i={};for(let a of e.orderedSet.ordering.array.attachment)n.push(this.uuidToString(a.uuid));for(let a of e.orderedSet.ordering.contents.element){let o=this.getTargetUuid(a.key),l=this.getTargetUuid(a.value);i[l]=n.indexOf(o)}return[i,n.length]}async computeCells(e){let n=Array(this.rowCount).fill(0).map(()=>Array(this.columnCount));for(let i of e.dictionary.element){let a=this.columnLocations[this.getTargetUuid(i.key)],o=this.objects[i.value.objectIndex];for(let l of o.dictionary.element){let s=this.rowLocations[this.getTargetUuid(l.key)],c=this.objects[l.value.objectIndex];if(!(s in n)||!c)continue;let u=new Br(this.importer,c);n[s][a]=await u.format(!0)}}return n}async format(){let e=await this.parse();if(!e)return"";let n=`
|
||
|
|
`;for(let i=0;i<e.length;i++)n+=`| ${e[i].join(" | ")} |
|
||
|
|
`,i==0&&(n+=`|${" -- |".repeat(e[0].length)}
|
||
|
|
`);return n+`
|
||
|
|
`}getTargetUuid(e){let i=this.objects[e.objectIndex].customMap.mapEntry[0].value.unsignedIntegerValue;return this.uuids[i]}uuidToString(e){return Buffer.from(e).toString("hex")}};Kn.protobufType="ciofecaforensics.MergableDataProto";var Vg=/(^\s+|(?:\s+)?\n(?:\s+)?|\s+$)/,is=/applenotes:note\/([-0-9a-f]+)(?:\?ownerIdentifier=.*)?/,zg=".AppleColorEmojiUI",Fc=[100,101,102,103],Br=class extends lr{constructor(e,n){super(e);this.listNumber=0;this.listIndent=0;this.multiRun=0;this.note=n.note}parseTokens(){let e=0,n=0,i=0,a=[];for(;e<this.note.attributeRun.length;){let o,l="",s=!0;do o=this.note.attributeRun[e],i=i+o.length,l+=this.note.noteText.substring(n,i),n=i,s=e==this.note.attributeRun.length-1?!1:Lc(o,this.note.attributeRun[e+1]),e++;while(s);for(let c of l.split(Vg))c&&a.push({attr:o,fragment:c})}return a}async format(e=!1,n=""){var l;let i=this.parseTokens(),a=!e&&this.importer.omitFirstLine&&this.note.noteText.contains(`
|
||
|
|
`),o="";for(let s=0;s<i.length;s++){let{attr:c,fragment:u}=i[s];if(a)if(u.contains(`
|
||
|
|
`)||c.attachmentInfo)a=!1;else continue;c.fragment=u,c.atLineStart=s==0?!0:(l=i[s-1])==null?void 0:l.fragment.contains(`
|
||
|
|
`),o+=this.formatMultiRun(c),!/\S/.test(c.fragment)||this.multiRun==1?o+=c.fragment:c.attachmentInfo?o+=await this.formatAttachment(c,n):c.superscript||c.underlined||c.color||c.font||this.multiRun==2?o+=await this.formatHtmlAttr(c):o+=await this.formatAttr(c)}return this.multiRun!=0&&(o+=this.formatMultiRun({})),e&&o.replace(`
|
||
|
|
`,"<br>").replace("|","|"),o.trim()}formatMultiRun(e){var a,o,l,s,c,u;let n=(a=e.paragraphStyle)==null?void 0:a.styleType,i="";switch(this.multiRun){case 3:(((o=e.paragraphStyle)==null?void 0:o.indentAmount)==0&&!Fc.includes(n)||Gg(e))&&(this.multiRun=0);break;case 1:n!=4&&(this.multiRun=0,i+="```\n");break;case 2:(l=e.paragraphStyle)!=null&&l.alignment||(this.multiRun=0,i+=`</p>
|
||
|
|
`);break}if(this.multiRun==0){if(n==4)this.multiRun=1,i+="\n```\n";else if(Fc.includes(n))this.multiRun=3,(s=e.paragraphStyle)!=null&&s.indentAmount&&(i+=`
|
||
|
|
-
|
||
|
|
`);else if((c=e.paragraphStyle)!=null&&c.alignment){this.multiRun=2;let p=this.convertAlign((u=e==null?void 0:e.paragraphStyle)==null?void 0:u.alignment);i+=`
|
||
|
|
<p style="text-align:${p};margin:0">`}}return i}async formatHtmlAttr(e){var i,a;e.strikethrough&&(e.fragment=`<s>${e.fragment}</s>`),e.underlined&&(e.fragment=`<u>${e.fragment}</u>`),e.superscript==1&&(e.fragment=`<sup>${e.fragment}</sup>`),e.superscript==-1&&(e.fragment=`<sub>${e.fragment}</sub>`);let n="";switch(e.fontWeight){case 1:e.fragment=`<b>${e.fragment}</b>`;break;case 2:e.fragment=`<i>${e.fragment}</i>`;break;case 3:e.fragment=`<b><i>${e.fragment}</i></b>`;break}return(i=e.font)!=null&&i.fontName&&e.font.fontName!==zg&&(n+=`font-family:${e.font.fontName};`),(a=e.font)!=null&&a.pointSize&&(n+=`font-size:${e.font.pointSize}pt;`),e.color&&(n+=`color:${this.convertColor(e.color)};`),e.link&&!is.test(e.link)?(n&&(n=` style="${n}"`),e.fragment=`<a href="${e.link}" rel="noopener" class="external-link" target="_blank"${n}>${e.fragment}</a>`):n&&(e.link&&(e.fragment=await this.getInternalLink(e.link,e.fragment)),e.fragment=`<span style="${n}">${e.fragment}</span>`),e.atLineStart?this.formatParagraph(e):e.fragment}async formatAttr(e){switch(e.fragment=e.fragment.replace(/([\[\]])/g,"\\$1"),e.fontWeight){case 1:e.fragment=`**${e.fragment}**`;break;case 2:e.fragment=`*${e.fragment}*`;break;case 3:e.fragment=`***${e.fragment}***`;break}return e.strikethrough&&(e.fragment=`~~${e.fragment}~~`),e.link&&e.link!=e.fragment&&(is.test(e.link)?e.fragment=await this.getInternalLink(e.link,e.fragment):e.fragment=`[${e.fragment}](${e.link})`),e.atLineStart?this.formatParagraph(e):e.fragment}formatParagraph(e){var o,l,s,c,u,p;let n=" ".repeat(((o=e.paragraphStyle)==null?void 0:o.indentAmount)||0),i=(l=e.paragraphStyle)==null?void 0:l.styleType,a=(s=e.paragraphStyle)!=null&&s.blockquote?"> ":"";switch(this.listNumber!=0&&(i!==102||this.listIndent!==((c=e.paragraphStyle)==null?void 0:c.indentAmount))&&(this.listIndent=((u=e.paragraphStyle)==null?void 0:u.indentAmount)||0,this.listNumber=0),i){case 0:return`${a}# ${e.fragment}`;case 1:return`${a}## ${e.fragment}`;case 2:return`${a}### ${e.fragment}`;case 101:case 100:return`${a}${n}- ${e.fragment}`;case 102:return this.listNumber++,`${a}${n}${this.listNumber}. ${e.fragment}`;case 103:let f=(p=e.paragraphStyle.checklist)!=null&&p.done?"[x]":"[ ]";return`${a}${n}- ${f} ${e.fragment}`}return this.multiRun==3&&(a+=n),`${a}${e.fragment}`}async formatAttachment(e,n){var c,u,p;let i,a,o;switch((c=e.attachmentInfo)==null?void 0:c.typeUti){case"com.apple.notes.inlinetextattachment.hashtag":case"com.apple.notes.inlinetextattachment.mention":return i=await this.importer.database.get`
|
||
|
|
SELECT zalttext FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,i.ZALTTEXT;case"com.apple.notes.inlinetextattachment.link":return i=await this.importer.database.get`
|
||
|
|
SELECT ztokencontentidentifier FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,await this.getInternalLink(i.ZTOKENCONTENTIDENTIFIER,void 0,n);case"com.apple.notes.table":return i=await this.importer.database.get`
|
||
|
|
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,o=this.importer.decodeData(i.zhexdata,Kn),await o.format();case"public.url":return i=await this.importer.database.get`
|
||
|
|
SELECT ztitle, zurlstring FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,`[**${i.ZTITLE}**](${i.ZURLSTRING})`;case"com.apple.notes.gallery":return i=await this.importer.database.get`
|
||
|
|
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,o=this.importer.decodeData(i.zhexdata,Zn),await o.format(!1,n);case"com.apple.paper.doc.scan":case"com.apple.drawing":case"com.apple.drawing.2":case"com.apple.paper":i=await this.importer.database.get`
|
||
|
|
SELECT z_pk, zhandwritingsummary
|
||
|
|
FROM (SELECT *, NULL AS zhandwritingsummary FROM ziccloudsyncingobject)
|
||
|
|
WHERE zidentifier = ${e.attachmentInfo.attachmentIdentifier}`,a=i==null?void 0:i.Z_PK;break;default:i=await this.importer.database.get`
|
||
|
|
SELECT zmedia FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${(u=e.attachmentInfo)==null?void 0:u.attachmentIdentifier}`,a=i==null?void 0:i.ZMEDIA;break}if(!a)return` **(unknown attachment: ${(p=e.attachmentInfo)==null?void 0:p.typeUti})** `;let l=await this.importer.resolveAttachment(a,e.attachmentInfo.typeUti),s=l?`
|
||
|
|
${this.app.fileManager.generateMarkdownLink(l,n)}
|
||
|
|
`:" **(error reading attachment)**";return this.importer.includeHandwriting&&i.ZHANDWRITINGSUMMARY&&(s=`
|
||
|
|
> [!Handwriting]-
|
||
|
|
> ${i.ZHANDWRITINGSUMMARY.replace(`
|
||
|
|
`,`
|
||
|
|
> `)}${s}`),s}async getInternalLink(e,n=void 0,i=""){let a=e.match(is)[1],o=await this.importer.database.get`
|
||
|
|
SELECT z_pk FROM ziccloudsyncingobject
|
||
|
|
WHERE zidentifier = ${a.toUpperCase()}`,l=await this.importer.resolveNote(o.Z_PK);return l?this.app.fileManager.generateMarkdownLink(l,i,void 0,n):"(unknown file link)"}convertColor(e){let n="#";for(let i of Object.values(e))n+=Math.floor(i*255).toString(16);return n}convertAlign(e){switch(e){default:return"left";case 1:return"center";case 2:return"right";case 3:return"justify"}}};Br.protobufType="ciofecaforensics.Document";function Gg(r){return r.attachmentInfo?!r.attachmentInfo.typeUti.includes("com.apple.notes.inlinetextattachment"):!1}function Lc(r,t){var e,n;if(!t||r.$type!=t.$type)return!1;for(let i of r.$type.fieldsArray)if(i.name!="length"){if((e=r[i.name])!=null&&e.$type&&((n=t[i.name])!=null&&n.$type)){if(!Lc(r[i.name],t[i.name]))return!1}else if(r[i.name]!=t[i.name])return!1}return!0}var Mc={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
|
||
|
|
`],{type:"text/javascript"}));r({workerScripts:{inflate:[t],deflate:[t]}})}cp(ea);var ue=Gr.Platform.isDesktopApp?window.require("node:original-fs"):null,gt=Gr.Platform.isDesktopApp?ue.promises:null,Je=Gr.Platform.isDesktopApp?window.require("node:os"):null,K=Gr.Platform.isDesktopApp?window.require("node:path"):null,pi=Gr.Platform.isDesktopApp?window.require("node:url"):null,up=Gr.Platform.isDesktopApp?window.require("node:zlib"):null;function En(r,t=0,e=r.byteLength-t){return r.buffer.slice(r.byteOffset+t,r.byteOffset+t+e)}var bt=class{constructor(t){this.type="file";this.filepath=t;let e=this.name=K.basename(t);this.fullpath=e;let n=K.extname(e);this.extension=n.substring(1).toLowerCase(),this.basename=K.basename(e,n)}async readText(){return gt.readFile(this.filepath,"utf8")}async read(){let t=await gt.readFile(this.filepath);return En(t)}async readZip(t){let e=null;try{e=await gt.open(this.filepath,"r");let n=await e.stat();return await t(new Vr(new Ls(e,n.size)))}finally{await(e==null?void 0:e.close())}}createReadStream(){return ue.createReadStream(this.filepath)}toString(){return this.filepath}},zr=class r{constructor(t){this.type="folder";this.filepath=t,this.name=K.basename(t)}async list(){let{filepath:t}=this,e=await gt.readdir(t,{withFileTypes:!0}),n=[];for(let i of e)i.isFile()?n.push(new bt(K.join(t,i.name))):i.isDirectory()&&n.push(new r(K.join(t,i.name)));return n}toString(){return this.filepath}},xa=class{constructor(t){this.type="file";this.file=t;let e=this.name=t.name;this.fullpath=e;let{basename:n,extension:i}=le(e);this.basename=n,this.extension=i}readText(){let{file:t}=this;return t.text?t.text():new Promise((e,n)=>{let i=new FileReader;i.addEventListener("load",()=>e(i.result)),i.addEventListener("error",n),i.readAsText(this.file)})}async read(){let{file:t}=this;return t.arrayBuffer?t.arrayBuffer():new Promise((e,n)=>{let i=new FileReader;i.addEventListener("load",()=>e(i.result)),i.addEventListener("error",n),i.readAsArrayBuffer(this.file)})}async readZip(t){return t(new Vr(new gr(this.file)))}toString(){return this.file.toString()}};async function Ms(r,t){let e=[];for(let n of r)try{n.type==="folder"?e.push(...await Ms(await n.list(),t)):n.type==="file"&&(!t||t(n))&&e.push(n)}catch(i){console.log("Skipping path: ",n.name,i)}return e}function le(r){let t=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\")),e=r,n="";t>=0&&(e=r.substring(t+1),n=r.substring(0,t));let[i,a]=_n(e);return{parent:n,name:e,basename:i,extension:a}}function _n(r){let t=r.lastIndexOf("."),e=r,n="";return t>0&&(e=r.substring(0,t),n=r.substring(t+1).toLowerCase()),[e,n]}var Ls=class extends wn{constructor(t,e){super(t),this.fd=t,this.size=e}async readUint8Array(t,e){let n=Buffer.alloc(e),i=await this.fd.read(n,0,e,t);return new Uint8Array(En(n,0,i.bytesRead))}};var pp=require("obsidian"),Sb=/[/\\]/g,Db=/[\?<>:\*\|"]/g,Rb=/[\x00-\x1f\x80-\x9f]/g,Ob=/^\.+$/,Ib=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,Fb=/[\. ]+$/,Lb=/^\./,Mb=/[\[\]#|^]/g;function Te(r){return r.replace(Sb,"-").replace(Db,"").replace(Rb,"").replace(Ob,"").replace(Fb,"").replace(Ib,"").replace(Lb,"").replace(Mb,"").trim()||"Untitled"}function Tn(r){let t=[];for(let e=0;e<r;e++)t.push((Math.random()*16|0).toString(16));return t.join("")}function At(r){return new DOMParser().parseFromString(r,"text/html").documentElement}function $b(r){return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}function $s(r){return $b(new TextEncoder().encode(r))}function yr(r){return Object.isEmpty(r)?"":`---
|
||
|
|
`+(0,pp.stringifyYaml)(r)+`---
|
||
|
|
`}function di(r,t,e="..."){return r.length<t?r:r.substring(0,t)+e}function Ct(r){if(typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string")return r.message}var Be=require("obsidian");var dp=300,Ee=class{constructor(t,e){this.files=[];this.outputLocation="";this.notAvailable=!1;this.outputFolder=null;this.app=t,this.vault=t.vault,this.modal=e,this.init()}async showTemplateConfiguration(t,e){return null}registerAuthCallback(t){this.modal.plugin.registerAuthCallback(t)}addFileChooserSetting(t,e,n=!1,i,a){let o=new Be.Setting(this.modal.contentEl).setName("Files to import").setDesc(i||"Pick the files that you want to import.").addButton(s=>s.setButtonText(n?"Choose files":"Choose file").onClick(async()=>{if(Be.Platform.isDesktopApp){let c=["openFile","dontAddToRecent"];n&&c.push("multiSelections");let u=window.electron.remote.dialog.showOpenDialogSync({title:"Pick files to import",properties:c,filters:[{name:t,extensions:e}],defaultPath:a||void 0});u&&u.length>0&&(this.files=u.map(p=>new bt(p)),l())}else{let c=createEl("input");c.type="file",c.accept=e.map(u=>"."+u.toLowerCase()).join(","),c.addEventListener("change",()=>{if(!c.files)return;let u=Array.from(c.files);u.length>0&&(this.files=u.map(p=>new xa(p)).filter(p=>e.contains(p.extension)),l())}),c.click()}}));n&&Be.Platform.isDesktopApp&&o.addButton(s=>s.setButtonText("Choose folders").onClick(async()=>{if(Be.Platform.isDesktopApp){let c=window.electron.remote.dialog.showOpenDialogSync({title:"Pick folders to import",properties:["openDirectory","multiSelections","dontAddToRecent"],defaultPath:a||void 0});if(c&&c.length>0){o.setDesc("Reading folders...");let u=c.map(p=>new zr(p));this.files=await Ms(u,p=>e.contains(p.extension)),l()}}}));let l=()=>{let s=document.createDocumentFragment(),c=this.files.length,u=this.files.map(p=>p.name).join(", ");u.length>dp&&(u=u.substring(0,dp)+"..."),s.createEl("span",{text:`These ${c} files will be imported: `}),s.createEl("br"),s.createEl("span",{cls:"u-pop",text:u}),o.setDesc(s)}}addOutputLocationSetting(t){this.outputLocation=t,new Be.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(e=>e.setValue(t).onChange(n=>{this.outputLocation=n,this.outputFolder=null}))}async getOutputFolder(){if(this.outputFolder)return this.outputFolder;let{vault:t}=this.app,e=this.outputLocation;e===""&&(e="/"),e=(0,Be.normalizePath)(e);let n=t.getAbstractFileByPath(e);return(n===null||!(n instanceof Be.TFolder))&&(await t.createFolder(e),n=t.getAbstractFileByPath(e)),n instanceof Be.TFolder?(this.outputFolder=n,n):null}async getAvailablePathForAttachment(t,e,n){let i=null;if(n){let{parent:f}=le(n);if(f){let d=this.vault.getAbstractFileByPath((0,Be.normalizePath)(f));d instanceof Be.TFolder&&(i={parent:d})}}if(!i){let f=await this.getOutputFolder();i=f?{parent:f}:null}let{basename:a,extension:o}=le(t),l=await this.vault.getAvailablePathForAttachments(a,o,i),s=le(l),c=s.extension?"."+s.extension:"."+o,u=1,p=l;for(;e.includes(p)||this.vault.getAbstractFileByPath(p);)p=K.join(s.parent,`${s.name} ${u}${c}`),u++;return(0,Be.normalizePath)(p)}async pause(t,e,n){let i=new Promise(a=>setTimeout(a,t*1e3));if(n){let a=n.statusMessage;n.status(`\u23F8\uFE0F Pausing import for ${t} seconds (${e})`),await i,n.status(a)}else await i}sanitizeFilePath(t){return t.replace(/[:|?<>*\\]/g,"")}async createFolders(t){let e=t.split("/").map(a=>a.replace(/^\.+/,"")).join("/"),n=(0,Be.normalizePath)(e),i=this.vault.getAbstractFileByPathInsensitive(n);if(i&&i instanceof Be.TFolder)return i;if(await this.vault.createFolder(n),i=this.vault.getAbstractFileByPathInsensitive(n),!(i instanceof Be.TFolder))throw new Error(`Failed to create folder at "${t}"`);return i}async saveAsMarkdownFile(t,e,n){let i=Te(e);return await this.app.fileManager.createNewMarkdownFile(t,i,n)}};var _f=Yn(df());var Il=require("obsidian");var ff=r=>{let e=Ha.execSync(`${r} --version`).toString().toString().match(/(\d+)\.(\d+).(\d+)/);return(e==null?void 0:e[1])>3||(e==null?void
|
||
|
|
`,n)].filter(s=>s>0),r.length-1);o=parseFloat(r.substring(n,l)),n=l}i==-1?e.push(o):(a[e[i]]=o,i++),(r[n]==`
|
||
|
|
`||e.length<i)&&(i!==-1&&t.push(a),i=0,a={}),n++}return t};function hf(r){for(var t=r[0],e=1,n=arguments.length;e<n;e++)t+=arguments[e]+r[e];return t}var{isArray:Ky}=Array,Wa=class extends String{},gf=(r,...t)=>{let e=[r[0]],n=[e];for(let i=0;i<t.length;i++)t[i]instanceof Wa?e[e.length-1]+=t[i]+r[i+1]:(Ky(t[i])?(e.push(...t[i].slice(1).map(a=>",")),n.push(...t[i].length?t[i]:[""])):n.push(t[i]),e.push(r[i+1]));return n},bf=r=>new Wa(r);var Ti=(r,t)=>{let e="SQLITE_ERROR",n=new Error(e+": "+t);return n.code=e,r(n),""},yf=(...r)=>bf(hf(...r)),{from:Xy}=Array,Jy=/'/g,Qy=r=>r.toString(16).padStart(2,"0"),ex=r=>`x'${Xy(r,Qy).join("")}'`,tx=r=>{switch(typeof r){case"string":return"'"+r.replace(Jy,"''")+"'";case"number":if(!isFinite(r))return;case"boolean":return+r;case"object":case"undefined":switch(!0){case!r:return"NULL";case r instanceof Date:return"'"+r.toISOString()+"'";case r instanceof Buffer:case r instanceof ArrayBuffer:r=new Uint8Array(r);case r instanceof Uint8Array:case r instanceof Uint8ClampedArray:return ex(r)}}},Dl=(r,t)=>{let[e,...n]=gf(...t),i=[e[0]];for(let o=0;o<n.length;o++){let l=tx(n[o]);if(l===void 0)return Ti(r,"incompatible "+typeof l+"value");i.push(l,e[o+1])}let a=i.join("").trim();return a.length?a:Ti(r,"empty query")};var Rl=Il.Platform.isDesktopApp?window.require("node:crypto"):null,Ha=Il.Platform.isDesktopApp?window.require("node:child_process"):null,Fl=Rl==null?void 0:Rl.randomUUID(),rx=`[{"_":"${Fl}"}]
|
||
|
|
`,nx=`'_'
|
||
|
|
'${Fl}'
|
||
|
|
`,{isArray:ix}=Array,{parse:wf}=JSON,{defineProperty:ax}=Object,ox=()=>{},sx=(r,t,e,n,i,a)=>{let o=[],{stdout:l,stderr:s}=Ha.spawn(n,i,a).on("close",u=>{if(c||u!==0){u!==0&&Ti(t,"busy DB or query too slow");return}let p=o.join("").trim();if(e==="query")r(p);else{let f=wf(p||"[]");r(e==="get"&&ix(f)?f.shift():f)}});l.on("data",u=>{o.push(u)});let c=!1;s.on("data",u=>{c=!0,Ti(t,"".trim.call(u))})},lx=(r,t,e)=>{let n=ff(r),i=n?rx:nx,{stdin:a,stdout:o,stderr:l}=Ha.spawn(r,t);n?a.write(`.mode json
|
||
|
|
`):a.write(`.mode quote
|
||
|
|
.headers on
|
||
|
|
`),e&&a.write(`.timeout ${e}
|
||
|
|
`);let s=Promise.resolve();return(c,u,p,f,d)=>{p==="close"?(a.write(`.quit
|
||
|
|
`),s=null):s&&(s=s.then(()=>new Promise(g=>{let m="",h=P=>{m+=P;let k=!1;for(;m.endsWith(i);)k=!0,m=m.slice(0,-i.length);if(k){for(T();m.startsWith(i);)m=m.slice(i.length);if(p==="query")c(m);else{let O=n?wf(m||"[]"):mf(m);c(p==="get"?O.shift():O)}}},b=P=>{T(),u(new Error(P))},T=()=>{g(),o.removeListener("data",h),l.removeListener("data",b)};o.on("data",h),l.once("data",b),a.write(`${d[d.length-1]};
|
||
|
|
`),a.write(`SELECT '${Fl}' as _;
|
||
|
|
`)})))}},Ol=(r,t,e,n,i)=>(...a)=>new Promise((o,l)=>{let s=Dl(l,a);s.length&&(r==="get"&&/^SELECT\s+/i.test(s)&&!/\s+LIMIT\s+\d+$/i.test(s)&&(s+=" LIMIT 1"),e(o,l,r,t,n.concat(s),i))}),xf="";function Ll(r,t={}){r===":memory:"&&(r=xf||(xf=K.join(Je.tmpdir(),randomUUID())));let e=t.timeout||0,n=t.bin||"sqlite3",i=[r,"-bail"],a={timeout:e};t.readonly&&i.push("-readonly"),e&&i.push("-cmd",".timeout "+e);let o=i.concat("-json"),l=t.exec||(t.persistent?lx(n,i,e):sx);return{transaction(){let s=[];return ax((...c)=>{s.push(c)},"commit",{value(){return new Promise((c,u)=>{let p=["BEGIN TRANSACTION"];for(let f of s){let d=Dl(u,f);if(!d.length)return;p.push(d)}p.push("COMMIT"),l(c,u,"query",n,i.concat(p.join(";")),a)})}})},query:Ol("query",n,l,i,a),get:Ol("get",n,l,o,a),all:Ol("all",n,l,o,a),close:t.persistent?()=>l(null,null,"close"):ox,raw:yf}}var Ml="Library/Group Containers/group.com.apple.notes",vf="NoteStore.sqlite",cx=978307200,Ef="apple-notes-importer-file-prefix";var Va=class extends Ee{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.duplicateHandling="import-updated";this.trashFolders=[]}init(){if(!Fe.Platform.isMacOS||!Fe.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");let e=localStorage.getItem(Ef)||"";this.filePrefixFormat=e,new Fe.Setting(this.modal.contentEl).setName("File prefix format").setDesc("Format for the creation date prefix in filenames. Use YYYY, MM, DD for year, month, day. Leave blank for no prefix.").addText(n=>n.setValue(e).setPlaceholder("YYYY-MM-DD").onChange(async i=>{this.filePrefixFormat=i,localStorage.setItem(Ef,i)})),new Fe.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(n=>n.setValue(!1).onChange(async i=>this.importTrashed=i)),new Fe.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(n=>n.setValue(!0).onChange(async i=>this.omitFirstLine=i)),new Fe.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(n=>n.setValue(!1).onChange(async i=>this.includeHandwriting=i)),new Fe.Setting(this.modal.contentEl).setName("Handle duplicate files").setDesc("How to handle notes that already exist in the vault.").addDropdown(n=>n.addOption("skip","Skip import").addOption("import-updated","Import only updated").addOption("create-copy","Create a copy").setValue("import-updated").onChange(async i=>this.duplicateHandling=i))}async getNotesDatabase(){let e=K.join(Je.homedir(),Ml),n=window.electron.remote.dialog.showOpenDialogSync({defaultPath:e,properties:["openDirectory"],message:'Select the "group.com.apple.notes" folder to allow Obsidian to read Apple Notes data.'});if(!(n!=null&&n.includes(e)))return new Fe.Notice("Data import failed. Ensure you have selected the correct Apple Notes data folder."),null;let i=K.join(e,vf),a=K.join(Je.tmpdir(),vf);return await gt.copyFile(i,a),await gt.copyFile(i+"-shm",a+"-shm"),await gt.copyFile(i+"-wal",a+"-wal"),new Ll(a,{readonly:!0,persistent:!0})}async import(e){if(this.ctx=e,this.protobufRoot=_f.Root.fromJSON(Mc),this.rootFolder=await this.getOutputFolder(),!this.rootFolder){new Fe.Notice("Please select a location to export to.");return}if(this.database=await this.getNotesDatabase(),!this.database)return;this.keys=Object.fromEntries((await this.database.all`SELECT z_ent, z_name FROM z_primarykey`).map(o=>[o
|
||
|
|
SELECT z_pk FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICAccount}
|
||
|
|
`,i=await this.database.all`
|
||
|
|
SELECT z_pk, ztitle2 FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICFolder}
|
||
|
|
`;for(let o of n)await this.resolveAccount(o.Z_PK);for(let o of i)try{await this.resolveFolder(o.Z_PK)}catch(l){this.ctx.reportFailed(o.ZTITLE2,Ct(l)),console.error(l)}let a=await this.database.all`
|
||
|
|
SELECT
|
||
|
|
z_pk, zfolder, ztitle1 FROM ziccloudsyncingobject
|
||
|
|
WHERE
|
||
|
|
z_ent = ${this.keys.ICNote}
|
||
|
|
AND ztitle1 IS NOT NULL
|
||
|
|
AND zfolder NOT IN (${this.trashFolders})
|
||
|
|
`;this.noteCount=a.length;for(let o of a)try{await this.resolveNote(o.Z_PK)}catch(l){this.ctx.reportFailed(o.ZTITLE1,Ct(l)),console.error(l)}this.database.close()}async resolveAccount(e){!this.multiAccount&&Object.keys(this.resolvedAccounts).length&&(this.multiAccount=!0);let n=await this.database.get`
|
||
|
|
SELECT zname, zidentifier FROM ziccloudsyncingobject
|
||
|
|
WHERE z_ent = ${this.keys.ICAccount} AND z_pk = ${e}
|
||
|
|
`;this.resolvedAccounts[e]={name:n.ZNAME,uuid:n.ZIDENTIFIER,path:K.join(Je.homedir(),Ml,"Accounts",n.ZIDENTIFIER)}}async resolveFolder(e){var o;if(e in this.resolvedFiles)return this.resolvedFolders[e];let n=await this.database.get`
|
||
|
|
SELECT ztitle2, zparent, zidentifier, zfoldertype, zowner
|
||
|
|
FROM ziccloudsyncingobject
|
||
|
|
WHERE z_ent = ${this.keys.ICFolder} AND z_pk = ${e}
|
||
|
|
`,i;if(n.ZFOLDERTYPE==3)return null;if(!this.importTrashed&&n.ZFOLDERTYPE==1)return this.trashFolders.push(e),null;if(n.ZPARENT!==null)i=((o=await this.resolveFolder(n.ZPARENT))==null?void 0:o.path)+"/";else if(this.multiAccount){let l=this.resolvedAccounts[n.ZOWNER].name;i=`${this.rootFolder.path}/${l}/`}else i=`${this.rootFolder.path}/`;n.ZIDENTIFIER.startsWith("DefaultFolder")||(i+=Te(n.ZTITLE2));let a=await this.createFolders(i);return this.resolvedFolders[e]=a,this.owners[e]=n.ZOWNER,a}async resolveNote(e){if(e in this.resolvedFiles)return this.resolvedFiles[e];let n=await this.database.get`
|
||
|
|
SELECT
|
||
|
|
nd.z_pk, hex(nd.zdata) as zhexdata, zcso.ztitle1, zfolder,
|
||
|
|
zcreationdate1, zcreationdate2, zcreationdate3, zmodificationdate1, zispasswordprotected
|
||
|
|
FROM
|
||
|
|
zicnotedata AS nd,
|
||
|
|
(SELECT
|
||
|
|
*, NULL AS zcreationdate3, NULL AS zcreationdate2,
|
||
|
|
NULL AS zispasswordprotected FROM ziccloudsyncingobject
|
||
|
|
) AS zcso
|
||
|
|
WHERE
|
||
|
|
zcso.z_pk = nd.znote
|
||
|
|
AND zcso.z_pk = ${e}
|
||
|
|
`;if(n.ZISPASSWORDPROTECTED)return this.ctx.reportSkipped(n.ZTITLE1,"note is password protected"),null;let i=this.resolvedFolders[n.ZFOLDER]||this.rootFolder,a=n.ZTITLE1;if(this.filePrefixFormat){let u=this.decodeTime(n.ZCREATIONDATE3||n.ZCREATIONDATE2||n.ZCREATIONDATE1);a=`${(0,Fe.moment)(u).format(this.filePrefixFormat)} ${a}`}let o=K.join(i.path,`${a}.md`),l=this.vault.getAbstractFileByPath(o);if(l&&l instanceof Fe.TFile){if(this.duplicateHandling==="skip")return this.ctx.reportSkipped(n.ZTITLE1,"note is a duplicate"),l;if(this.duplicateHandling==="import-updated"){let u=this.decodeTime(n.ZMODIFICATIONDATE1),p=l.stat.mtime;if(u<=p)return this.ctx.reportSkipped(n.ZTITLE1,"note unchanged since last import"),l}}let s=await this.saveAsMarkdownFile(i,`${a}.md`,"");this.ctx.status(`Importing note ${a}`),this.resolvedFiles[e]=s,this.owners[e]=this.owners[n.ZFOLDER];let c=this.decodeData(n.zhexdata,Br);return this.vault.modify(s,await c.format(!1,s.path),{ctime:this.decodeTime(n.ZCREATIONDATE3||n.ZCREATIONDATE2||n.ZCREATIONDATE1),mtime:this.decodeTime(n.ZMODIFICATIONDATE1)}),this.parsedNotes++,this.ctx.reportProgress(this.parsedNotes,this.noteCount),this.ctx.reportNoteSuccess(a),s}async resolveAttachment(e,n){if(e in this.resolvedFiles)return this.resolvedFiles[e];let i,a,o,l,s;switch(n){case"com.apple.paper.doc.scan":l=await this.database.get`
|
||
|
|
SELECT
|
||
|
|
zidentifier, zfallbackpdfgeneration, zcreationdate, zmodificationdate, znote
|
||
|
|
FROM
|
||
|
|
(SELECT *, NULL AS zfallbackpdfgeneration FROM ziccloudsyncingobject)
|
||
|
|
WHERE
|
||
|
|
z_ent = ${this.keys.ICAttachment}
|
||
|
|
AND z_pk = ${e}
|
||
|
|
`,i=K.join("FallbackPDFs",l.ZIDENTIFIER,l.ZFALLBACKPDFGENERATION||"","FallbackPDF.pdf"),a="Scan",o="pdf";break;case"com.apple.notes.gallery":l=await this.database.get`
|
||
|
|
SELECT
|
||
|
|
zidentifier, zsizeheight, zsizewidth, zcreationdate, zmodificationdate, znote
|
||
|
|
FROM ziccloudsyncingobject
|
||
|
|
WHERE
|
||
|
|
z_ent = ${this.keys.ICAttachment}
|
||
|
|
AND z_pk = ${e}
|
||
|
|
`,i=K.join("Previews",`${l.ZIDENTIFIER}-1-${l.ZSIZEWIDTH}x${l.ZSIZEHEIGHT}-0.jpeg`),a="Scan Page",o="jpg";break;case"com.apple.paper":l=await this.database.get`
|
||
|
|
SELECT
|
||
|
|
zidentifier, zfallbackimagegeneration, zcreationdate, zmodificationdate,
|
||
|
|
znote, zhandwritingsummary
|
||
|
|
FROM
|
||
|
|
(SELECT *, NULL AS zfallbackimagegeneration FROM ziccloudsyncingobject)
|
||
|
|
WHERE
|
||
|
|
z_ent = ${this.keys.ICAttachment}
|
||
|
|
AND z_pk = ${e}
|
||
|
|
`,l.ZFALLBACKIMAGEGENERATION?i=K.join("FallbackImages",l.ZIDENTIFIER,l.ZFALLBACKIMAGEGENERATION,"FallbackImage.png"):i=K.join("FallbackImages",`${l.ZIDENTIFIER}.jpg`),a="Drawing",o="png";break;default:l=await this.database.get`
|
||
|
|
SELECT
|
||
|
|
a.zidentifier, a.zfilename,
|
||
|
|
a.zgeneration1, b.zcreationdate, b.zmodificationdate, b.znote
|
||
|
|
FROM
|
||
|
|
(SELECT *, NULL AS zgeneration1 FROM ziccloudsyncingobject) AS a,
|
||
|
|
ziccloudsyncingobject AS b
|
||
|
|
WHERE
|
||
|
|
a.z_ent = ${this.keys.ICMedia}
|
||
|
|
AND a.z_pk = ${e}
|
||
|
|
AND a.z_pk = b.zmedia
|
||
|
|
`,i=K.join("Media",l.ZIDENTIFIER,l.ZGENERATION1||"",l.ZFILENAME),[a,o]=_n(l.ZFILENAME);break}let c=a;if(this.filePrefixFormat&&l.ZCREATIONDATE){let g=this.decodeTime(l.ZCREATIONDATE);c=`${(0,Fe.moment)(g).format(this.filePrefixFormat)} ${a}`}let u=await this.getAvailablePathForAttachment(`${c}.${o}`,[]),{parent:p}=le(u),f=K.join(p,`${c}.${o}`),d=this.vault.getAbstractFileByPath(f);if(d&&d instanceof Fe.TFile){if(this.duplicateHandling==="skip")return this.ctx.reportSkipped(c,"attachment already exists"),d;if(this.duplicateHandling==="import-updated"){let g=this.decodeTime(l.ZMODIFICATIONDATE),m=d.stat.mtime;if(g<=m)return this.ctx.reportSkipped(c,"attachment unchanged since last import"),d}}try{let g=await this.getAttachmentSource(this.resolvedAccounts[this.owners[l.ZNOTE]],i),m=await this.getAvailablePathForAttachment(`${c}.${o}`,[]);s=await this.vault.createBinary(m,En(g),{ctime:this.decodeTime(l.ZCREATIONDATE),mtime:this.decodeTime(l.ZMODIFICATIONDATE)})}catch(g){return this.ctx.reportFailed(i),console.error(g),null}return this.resolvedFiles[e]=s,this.ctx.reportAttachmentSuccess(`${c}.${o}`),s}decodeData(e,n){let i=up.gunzipSync(Buffer.from(e,"hex")),a=this.protobufRoot.lookupType(n.protobufType).decode(i);return new n(this,a)}decodeTime(e){return!e||e<1?new Date().getTime():Math.floor((e+cx)*1e3)}async getAttachmentSource(e,n){try{return await gt.readFile(K.join(e.path,n))}catch(i){return await gt.readFile(K.join(Je.homedir(),Ml,n))}}async saveAsMarkdownFile(e,n,i){if(this.duplicateHandling==="skip"||this.duplicateHandling==="import-updated"){let a=Te(n),o=K.join(e.path,a),l=this.vault.getAbstractFileByPath(o);if(l&&l instanceof Fe.TFile)return l}return super.saveAsMarkdownFile(e,n,i)}};var Qe=require("obsidian");var ux="dddd, D MMMM YYYY",px="Journal",dx=new Map([["generic-map","location"],["multi-pin-map","location"]]),fx=new Set(["photo","live-photo","video"]),mx=".p2, .p3",hx=[".gridItemOverlayHeader",".gridItemOverlayFooter",".gridItemOverlayText",".activityType",".activityMetrics",".activityMetricsDistance",".activityMetricsCalories",".activityMetricsDuration",".mediaTitle",".mediaArtist",".mediaCategory"],Qr={Skip:"skip",ImportUpdated:"import-updated",CreateCopy:"create-copy"},Tf=Qr.ImportUpdated,za=class extends Ee{constructor(){super(...arguments);this.frontMatterEnabled=!0;this.duplicateHandling=Tf}init(){let e=Tx();this.addFileChooserSetting("Journal entries",["htm","html"],!0,"Pick the Journal app exported folder",e),new Qe.Setting(this.modal.contentEl).setName("Journal metadata").setHeading(),new Qe.Setting(this.modal.contentEl).setName("Add metadata as frontmatter").setDesc("Capture state-of-mind, contact, and similar tokens in YAML when available.").addToggle(n=>{n.setValue(this.frontMatterEnabled),n.onChange(i=>{this.frontMatterEnabled=i})}),new Qe.Setting(this.modal.contentEl).setName("Handle duplicate files").setDesc("How to handle entries that already exist in the vault.").addDropdown(n=>{n.addOption(Qr.Skip,"Skip import").addOption(Qr.ImportUpdated,"Import only updated").addOption(Qr.CreateCopy,"Create a copy").setValue(Tf).onChange(i=>{this.duplicateHandling=i})}),this.addOutputLocationSetting(px)}async import(e){if(this.files.length===0){new Qe.Notice("Please pick at least one file to import.");return}let n=await this.getOutputFolder();if(!n){new Qe.Notice("Please select a location to export to.");return}e.reportProgress(0,this.files.length);for(let i=0;i<this.files.length;i++){if(e.isCancelled())return;let a=this.files[i];if(a.name==="index.html"){e.reportSkipped(a.fullpath,"index file is not a journal entry"),e.reportProgress(i+1,this.files.length);continue}try{e.status(`Importing note ${a.basename}`),await this.importEntry(e,n,a)&&e.reportNoteSuccess(a.fullpath)}catch(o){e.reportFailed(a.fullpath,o)}e.reportProgress(i+1,this.files.length)}}async importEntry(e,n,i){var m,h;let a=await i.readText(),o=At(a),l=this.frontMatterEnabled?(m=xx(o))!=null?m:{}:{},s=gx(o);s&&(l.date=s);let c=bx(o),u=(0,Qe.htmlToMarkdown)(c);if(Object.keys(l).length>0){let b=yr(l);b&&(u=b+u)}let p=Te(i.basename),f=n
|
||
|
|
`),a=i>0?n.substring(2,i):n.substring(2);return a=a.trim(),a!==e.trim()&&a!==""?n:i>0?n.substring(i+1):""}};var tr=require("obsidian");var Cr=require("obsidian"),Ya=class{constructor(t){var e,n,i,a,o;this.fields=t.fields,this.placeholderSyntax=t.placeholderSyntax||"{{field_name}}",this.config={titleTemplate:((e=t.defaults)==null?void 0:e.titleTemplate)||"",locationTemplate:((n=t.defaults)==null?void 0:n.locationTemplate)||"",propertyNames:((i=t.defaults)==null?void 0:i.propertyNames)||new Map,propertyValues:((a=t.defaults)==null?void 0:a.propertyValues)||new Map,bodyTemplate:((o=t.defaults)==null?void 0:o.bodyTemplate)||""}}async show(t){return new Promise(e=>{t.empty(),t.createEl("p",{text:`Configure how your data should be imported. Use ${this.placeholderSyntax} syntax to reference field values.`}),new Cr.Setting(t).setName("Note title").setDesc("Template for the note title. Use {{field_name}} to insert values.").addText(l=>l.setPlaceholder("{{Title}}").setValue(this.config.titleTemplate).onChange(s=>{this.config.titleTemplate=s})),new Cr.Setting(t).setName("Note location").setDesc("Template for note location/path. Use {{field_name}} to organize notes.").addText(l=>l.setPlaceholder("{{Category}}/{{Subcategory}}").setValue(this.config.locationTemplate).onChange(s=>{this.config.locationTemplate=s})),t.createDiv({cls:"importer-frontmatter-header"}).createEl("h4",{text:"Properties"});let i=t.createDiv("importer-column-list"),a=i.createDiv("importer-column-header-row");a.createDiv("importer-column-name-col").setText("Property name"),a.createDiv("importer-column-value-col").setText("Property value"),a.createDiv("importer-column-example-col").setText("Example"),a.createDiv("importer-column-delete-col");for(let l of this.fields){let s=i.createDiv("importer-column-row"),u=s.createDiv("importer-column-name-col").createEl("input",{type:"text",cls:"importer-column-property",value:this.config.propertyNames.get(l.id)||""});u.addEventListener("input",()=>{this.config.propertyNames.set(l.id,u.value)});let f=s.createDiv("importer-column-value-col").createEl("input",{type:"text",cls:"importer-column-property",value:this.config.propertyValues.get(l.id)||""});f.addEventListener("input",()=>{this.config.propertyValues.set(l.id,f.value)});let d=s.createDiv("importer-column-example-col"),g=l.exampleValue||"",m=g.length>50?g.substring(0,50)+"...":g;d.setText(m||"\u2014");let b=s.createDiv("importer-column-delete-col").createEl("button",{cls:"clickable-icon",attr:{"aria-label":"Delete property"}});(0,Cr.setIcon)(b,"trash-2"),b.addEventListener("click",()=>{this.config.propertyNames.delete(l.id),this.config.propertyValues.delete(l.id),s.remove()})}new Cr.Setting(t).setName("Note content").setDesc("Template for the note content. Use {{field_name}} to insert values.").addTextArea(l=>{l.setPlaceholder("{{Content}}").setValue(this.config.bodyTemplate).onChange(s=>{this.config.bodyTemplate=s}),l.inputEl.rows=6});let o=t.createDiv("modal-button-container");o.createEl("button",{cls:"mod-cta",text:"Continue"},l=>{l.addEventListener("click",()=>{if(!this.config.titleTemplate.trim()){new Cr.Notice("Please provide a note title template.");return}e(this.config)})}),o.createEl("button",{text:"Cancel"},l=>{l.addEventListener("click",()=>{e(null)})})})}};function Ci(r,t){return r?r.replace(/\{\{\s*([^}]+?)\s*\}\}/g,(e,n)=>{let i=n.trim();return t[i]!==void 0?t[i]:e}):""}function Ax(r){let t=r.trim().toLowerCase();return t==="null"||t==="undefined"||r===""?"":t==="true"||t==="false"?t:isNaN(Number(r))?JSON.stringify(r):r}function Af(r,t,e){if(t.size===0)return"";let n=["---"];for(let[i,a]of t){if(!a)continue;let o=e.get(i)||"";if(!o)continue;let l=Ci(o,r),s=Ax(l);n.push(`${a}: ${s}`)}return n.push("---"),n.join(`
|
||
|
|
`)}var Dn=require("obsidian");async function Cf(r,t,e,n){let i=(0,Dn.stringifyYaml)(e),a=(0,Dn.normalizePath)(K.join(r.path,t+".base")),o=n.getAbstractFileByPath(a);return o instanceof Dn.TFile?(await n.modify(o,i),o):await n.create(a,i)}var Za=class extends Ee{constructor(){super(...arguments);this.csvHeaders=[];this.csvRows=[];this.config=null}init(){this.addFileChooserSetting("CSV",["csv"]),this.addOutputLocationSetting("CSV import"),this.hasHeaderRow=!0,new tr.Setting(this.modal.contentEl).setName("CSV has header row").setDesc("If enabled, the first row of the CSV file will be treated as column headers.").addToggle(e=>{e.setValue(this.hasHeaderRow),e.onChange(async n=>{this.hasHeaderRow=n})})}async showTemplateConfiguration(e,n){let{files:i}=this;if(i.length===0)return new tr.Notice("Please pick at least one CSV file to import."),!1;if(i.length>1)return new tr.Notice("CSV files must be imported one at a time."),!1;let a=i[0];if(e.isCancelled())return!1;e.status("Parsing "+a.name);let o=await a.readText(),l=this.parseCSV(o);if(this.csvHeaders.length===0&&l.rows.length>0&&(this.csvHeaders=l.headers),this.csvRows.push(...l.rows),this.csvHeaders.length===0||this.csvRows.length===0)return new tr.Notice("No data found in CSV file(s)."),!1;let s=this.csvHeaders.map(d=>({id:d,label:d,exampleValue:this.findExampleValue(d)})),c=new Map,u=new Map;this.csvHeaders.forEach(d=>{c.set(d,this.sanitizeYAMLKey(d)),u.set(d,`{{${d}}}`)});let p=this.csvHeaders.length>0?`{{${this.csvHeaders[0]}}}`:"",f=new Ya({fields:s,defaults:{titleTemplate:p,locationTemplate:"",bodyTemplate:"",propertyNames:c,propertyValues:u},placeholderSyntax:"{{column_name}}"});return this.config=await f.show(n),this.config!==null}async import(e){if(!this.config){new tr.Notice("Configuration is missing.");return}await this.processRows(e)}findExampleValue(e){for(let n of this.csvRows){let i=n[e];if(i&&i.trim().length>0)return i}return""}parseCSV(e){let n=this.splitCSVLines(e);if(n.length===0)return{headers:[],rows:[]};let i,a;this.hasHeaderRow?(i=this.parseCSVLine(n[0]),a=1):(i=this.parseCSVLine(n[0]).map((s,c)=>`Column ${c+1}`),a=0);let o=[];for(let l=a;l<n.length;l++){let s=this.parseCSVLine(n[l]);if(s.length===0)continue;let c={};for(let u=0;u<i.length;u++)c[i[u]]=s[u]||"";o.push(c)}return{headers:i,rows:o}}splitCSVLines(e){let n=[],i="",a=!1;for(let o=0;o<e.length;o++){let l=e[o],s=e[o+1];l==='"'?(i+=l,a&&s==='"'?(i+='"',o++):a=!a):l===`
|
||
|
|
`&&!a?(i.trim().length>0&&n.push(i),i=""):l==="\r"&&s===`
|
||
|
|
`&&!a?(i.trim().length>0&&n.push(i),i="",o++):l==="\r"&&!a?(i.trim().length>0&&n.push(i),i=""):i+=l}return i.trim().length>0&&n.push(i),n}parseCSVLine(e){let n=[],i="",a=!1,o=!0;for(let l=0;l<e.length;l++){let s=e[l],c=e[l+1];s==='"'&&o?(a=!0,o=!1):s==='"'&&a?c==='"'?(i+='"',l++):a=!1:s===","&&!a?(n.push(i),i="",o=!0):(s!==" "||!o||i.length>0)&&(i+=s,o=!1)}return n.push(i),n.map(l=>l.trim())}sanitizeYAMLKey(e){return e.replace(/[^\w\s-]/g,"")}async processRows(e){if(!this.config){new tr.Notice("Configuration is missing.");return}let n=await this.getOutputFolder();if(!n){new tr.Notice("Please select a location to export to.");return}e.reportProgress(0,this.csvRows.length);for(let i=0;i<this.csvRows.length;i++){if(e.isCancelled())return;let a=this.csvRows[i];try{let o=Ci(this.config.titleTemplate,a);if(!o.trim()){e.reportSkipped(`Row ${i+1}`,"Empty title");continue}e.status(`Creating note: ${o}`);let l=Ci(this.config.locationTemplate,a),s=await this.getTargetFolder(n,l),c="",u=Af(a,this.config.propertyNames,this.config.propertyValues);u&&(c+=u+`
|
||
|
|
|
||
|
|
`);let p=Ci(this.config.bodyTemplate,a);p&&(c+=p),await this.saveAsMarkdownFile(s,o,c),e.reportNoteSuccess(o)}catch(o){e.reportFailed(`Row ${i+1}`,o)}e.reportProgress(i+1,this.csvRows.length)}!e.isCancelled()&&n.path!==""&&await this.createBase(n)}async createBase(e){try{let i=["file.name",...Array.from(this.config.propertyNames.values()).filter(s=>s&&s.trim())],a=e.name,o=e.parent||e,l={filters:`file.folder == "${e.path}"`,views:[{type:"table",name:"Table",order:i}]};await Cf(o,a,l,this.app.vault)}catch(n){console.error("Failed to create Base file:",n)}}async getTargetFolder(e,n){if(!n||!n.trim())return e;let i=this.sanitizeFilePath(n),a=e.path+"/"+i;return await this.createFolders(a)}};var Oi=require("obsidian");var Rh=require("obsidian");var kf=require("obsidian");var Nf=r=>({...r,created:ki(r.created),statusupdated:ki(r.statusupdated),updated:ki(r.updated),duedate:ki(r.duedate),taskflag:r.taskflag==="true",reminderdate:r.reminder?ki(r.reminder.reminderdate):void 0,sortweight:r.sortweight}),ki=r=>r?(0,kf.moment)(r,"YYYYMMDDThhmmssZ").toDate():void 0;var pm=Yn(Hf());var Oe=r=>{let t={get(e,n){return e[n]}};return new Proxy(r.attributes,t)};var Wf="\n```\n",jl=r=>{let t=Oe(r);return t.style&&t.style.value.indexOf("-en-codeblock:true")>=0},Lx=r=>{let t=Oe(r),e="padding-left:",n=0;return t.style&&t.style.value.indexOf(e)>=0&&(n=Math.floor(t.style.value.split(e)[1].split("px")[0]/20)),n},Ul=r=>r.replace(/\\(.)/g,"$1"),Vf=(r,t)=>{let e=Lx(t);return r=`${" ".repeat(e)}${r}`,jl(t)?(r=Ul(r),`${Wf}${r}${Wf}`):t.parentElement&&jl(t.parentElement)&&t.parentElement.firstElementChild===t?`${r}`:t.parentElement&&jl(t.parentElement)?`
|
||
|
|
${r}`:t.isBlock?`
|
||
|
|
${r}
|
||
|
|
`:r};var Ka="\n```\n",Mx="-en-codeblock:true",$x=/\b(Courier|Mono|Consolas|Console|Inconsolata|Pitch|Monaco|monospace)\b/,zf=r=>{var a,o;if(r.nodeType!==1)return null;let t=r.childNodes,e=t.length;if(e>1)return"mixed";if(e===1){let l=zf(t[0]);if(l)return l}let n=Oe(r);if(r.tagName==="FONT")return(a=n.face)==null?void 0:a.value;let i=(o=n.style)==null?void 0:o.value;if(i){let l=i.match(/font-family:([^;]+)/);if(l)return l[1]}return null},Ni=r=>{var i;let e=(i=Oe(r).style)==null?void 0:i.value;if(e&&e.includes(Mx))return!0;let n=zf(r);return!!n&&$x.test(n)},Gf=(r,t)=>{if(Ni(t)){let e=t.previousSibling,n=e&&e.tagName===t.tagName&&Ni(e),i=t.nextSibling,a=i&&i.tagName===t.tagName&&Ni(i);return n||a?(r=n?`
|
||
|
|
${r}`:`${Ka}${r}`,r=a?`${r}
|
||
|
|
`:`${r}${Ka}`,r):(r=Ul(r),r.trim()?`${Ka}${r}${Ka}`:r)}return t.parentElement&&Ni(t.parentElement)&&t.parentElement.firstElementChild===t?r:t.parentElement&&Ni(t.parentElement)?`
|
||
|
|
${r}`:t.isBlock?`
|
||
|
|
${r}
|
||
|
|
`:r};var _t=r=>t=>t.nodeName===r||t.nodeName.toLowerCase()===r;var Yf={filter:_t("IMG"),replacement:(r,t)=>{let e=Oe(t);if(!e.src)return"";let n=e.src.value,i=t.width||"",a=t.height||"",o=n;Q.sanitizeResourceNameSpaces?o=o.replace(/ /g,Q.replacementChar):Q.urlEncodeFileNamesAndLinks&&(o=encodeURI(o));let l=i||a?` =${i}x${a}`:"";if(Q.keepImageSize)return l=i||a?`|${i||0}x${a||0}`:"",o.startsWith("./")?`![[${o}${l}]]`:``;if(!n.match(/^[a-z]+:/))return`![[${o}]]`;let s=e.src.value.split("/");return`![${s[s.length-1]}](${o})`}};var et=class r{constructor(){this.noteIdNameMap={},this.noteIdNameTOCMap={}}static getInstance(){return r.instance||(r.instance=new r),r.instance}addItemToMap(t){this.noteIdNameMap[t.url]={...this.noteIdNameMap[t.url],title:t.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:t.uniqueEnd}}addItemToTOCMap(t){this.noteIdNameTOCMap[t.url]={...this.noteIdNameMap[t.url],title:t.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:t.uniqueEnd}}getNoteIdNameMap(){return this.noteIdNameMap}getNoteIdNameTOCMap(){return this.noteIdNameTOCMap}getAllNoteIdNameMap(){return{...this.noteIdNameMap,...this.noteIdNameTOCMap}}getNoteIdNameMapByNoteTitle(t){return Object.values(this.getAllNoteIdNameMap()).filter(e=>e.title===t)}setCurrentNotebookName(t){this.currentNotebookName=t}getCurrentNotebookName(){return this.currentNotebookName}setCurrentNotebookFullpath(t){this.currentNotebookFullpath=t}setCurrentNoteName(t){this.currentNoteName=t}getCurrentNoteName(){return this.currentNoteName}getCurrentNotePath(){return this.currentNotePath}setCurrentNotePath(t){this.currentNotePath=t}getCurrentNotebookFullpath(){return this.currentNotebookFullpath}};var Kf=require("obsidian");var Rn=r=>r.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var Bx={"application/andrew-inset":"ez","application/applixware":"aw","application/atom+xml":"atom","application/atomcat+xml":"atomcat","application/atomdeleted+xml":"atomdeleted","application/atomsvc+xml":"atomsvc","application/atsc-dwd+xml":"dwd","application/atsc-held+xml":"held","application/atsc-rsat+xml":"rsat","application/bdoc":"bdoc","application/calendar+xml":"xcs","application/ccxml+xml":"ccxml","application/cdfx+xml":"cdfx","application/cdmi-capability":"cdmia","application/cdmi-container":"cdmic","application/cdmi-domain":"cdmid","application/cdmi-object":"cdmio","application/cdmi-queue":"cdmiq","application/cpl+xml":"cpl","application/cu-seeme":"cu","application/dash+xml":"mpd","application/dash-patch+xml":"mpp","application/davmount+xml":"davmount","application/docbook+xml":"dbk","application/dssc+der":"dssc","application/dssc+xml":"xdssc","application/ecmascript":"es","application/emma+xml":"emma","application/emotionml+xml":"emotionml","application/epub+zip":"epub","application/exi":"exi","application/express":"exp","application/fdt+xml":"fdt","application/font-tdpfr":"pfr","application/geo+json":"geojson","application/gml+xml":"gml","application/gpx+xml":"gpx","application/gxf":"gxf","application/gzip":"gz","application/hjson":"hjson","application/hyperstudio":"stk","application/inkml+xml":"ink","application/ipfix":"ipfix","application/its+xml":"its","application/java-archive":"jar","application/java-serialized-object":"ser","application/java-vm":"class","application/javascript":"js","application/json":"json","application/json5":"json5","application/jsonml+json":"jsonml","application/ld+json":"jsonld","application/lgr+xml":"lgr","application/lost+xml":"lostxml","application/mac-binhex40":"hqx","application/mac-compactpro":"cpt","application/mads+xml":"mads","application/manifest+json":"webmanifest","application/marc":"mrc","application/marcxml+xml":"mrcx","application/mathematica":"ma","application/mathml+xml":"mathml","application/mbox":"mbox","application/media-policy-dataset+xml":"mpf","application/mediaservercontrol+xml":"mscml","application/metalink+xml":"metalink","application/metalink4+xml":"meta4","application/mets+xml":"mets","application/mmt-aei+xml":"maei","application/mmt-usd+xml":"musd","appl
|
||
|
|
`).replace(/\n/gm,`
|
||
|
|
${cm}`),s=a>0?o:n(t)?`${eo} `:i(t)?`${Qa} `:"* ",c=t.parentNode;if(c.nodeName==="OL"){let p=c.getAttribute("start"),f=Array.prototype.indexOf.call(c.children,t);s=`${p?Number(p)+f:f+1}. `}let u;return u=s+l+(t.nextSibling&&!/\n$/.test(l)?`
|
||
|
|
`:""),u}};var Ja=r=>{let t=new window.TurndownService({br:"",...r.turndownOptions,blankReplacement:(e,n)=>n.isBlock?`
|
||
|
|
|
||
|
|
`:"",keepReplacement:(e,n)=>n.isBlock?`
|
||
|
|
${n.outerHTML}
|
||
|
|
`:n.outerHTML,defaultReplacement:(e,n)=>n.isBlock?`
|
||
|
|
${e}
|
||
|
|
`:e});return t.use(pm.gfm),t.addRule("span",nm),t.addRule("strikethrough",im),t.addRule("evernote task items",am),t.addRule("wikistyle links",tm),t.addRule("images",Yf),t.addRule("list",um),t.addRule("italic",lm),r.keepMDCharactersOfENNotes&&(t.escape=e=>e),t.addRule("divBlock",sm),r.keepOriginalAmountOfNewlines&&t.addRule("newline",om),t};var dm=r=>{r.replaceWith(...Array.from(r.children))},fm=r=>{let t=r.parentElement;t.replaceWith(...Array.from(t.childNodes)),t.append(...Array.from(r.childNodes)),r.appendChild(t)},nw=r=>(Array.from(r.querySelectorAll("span>en-todo")).forEach(fm),Array.from(r.querySelectorAll("a>en-todo")).forEach(fm),r),iw=r=>{let t=r.replace(/<li>/g,"<li><div>");return t=t.replace(/<\/li>/g,"</div></li>"),t=t.replace(/<li><div>(\s)*<div>/g,"<li><div>"),t=t.replace(/<\/div>(\s)*<\/div><\/li>/g,"</div></li>"),t},aw=r=>{var a;let t=Array.from(r.getElementsByTagName("ul")),e=Array.from(r.getElementsByTagName("ol")),n=t.concat(e);n.forEach(o=>{o.parentElement.tagName==="LI"&&o.parentElement.replaceWith(o),o.previousElementSibling&&o.previousElementSibling.tagName==="LI"&&o.previousElementSibling.appendChild(o)});for(let o of n){let l=o.parentElement;(l==null?void 0:l.tagName)==="DIV"&&((a=l==null?void 0:l.parentElement)==null?void 0:a.tagName)==="UL"&&dm(l),((l==null?void 0:l.tagName)==="UL"||(l==null?void 0:l.tagName)==="OL")&&(l==null?void 0:l.childNodes.length)===1&&dm(l)}let i=Array.from(r.getElementsByTagName("li"));for(let o of i){let l=o.firstElementChild;if(l&&l.tagName==="DIV"){let s=Array.from(l.childNodes);l.replaceWith(...s)}}return r},mm=(r,{htmlContent:t})=>{let e=t.replace(/<!DOCTYPE en-note [^>]*>/,"<!DOCTYPE html>").replace(/(<a [^>]*)\/>/,"$1></a>").replace(/<div[^\/\<]*\/>/g,""),n=new DOMParser().parseFromString(iw(e),"text/html").getElementsByTagName("en-note").item(0),i=Ja(r).turndown(nw(aw(n))),a=new RegExp("<YARLE_NEWLINE_PLACEHOLDER>","g");return i=i.replace(a,""),i&&i!=="undefined"?{content:i}:{content:""}};var oh=Yn(require("crypto"));var rr=require("obsidian");var hm=(r,t)=>({createdAt:ow(r),updatedAt:sw(r),sourceUrl:lw(r),location:cw(r),reminderTime:uw(r),reminderOrder:pw(r),reminderDoneTime:dw(r),notebookName:t});var ow=r=>!Q.skipCreationTime&&r.created?(0,rr.moment)(r.created).format(Q.dateFormat):"",sw=r=>!Q.skipUpdateTime&&r.updated?(0,rr.moment)(r.updated).format(Q.dateFormat):"",lw=r=>!Q.skipSourceUrl&&r["note-attributes"]?r["note-attributes"]["source-url"]:"",cw=r=>!Q.skipLocation&&r["note-attributes"]&&r["note-attributes"].longitude?`${r["note-attributes"].latitude},${r["note-attributes"].longitude}`:"",uw=r=>!Q.skipReminderTime&&r["note-attributes"]&&r["note-attributes"]["reminder-time"]?(0,rr.moment)(r["note-attributes"]["reminder-time"]).format(Q.dateFormat):"",pw=r=>!Q.skipReminderOrder&&r["note-attributes"]&&r["note-attributes"]["reminder-order"]?r["note-attributes"]["reminder-order"]:"",dw=r=>!Q.skipReminderDoneTime&&r["note-attributes"]&&r["note-attributes"]["reminder-done-time"]?(0,rr.moment)(r["note-attributes"]["reminder-done-time"]).format(Q.dateFormat):"",gm=r=>({tags:fw(r)}),fw=r=>{if(!Q.skipTags&&r.tag){let t=Array.isArray(r.tag)?r.tag:[r.tag],e=Q.nestedTags;return t.map(i=>{let a=i.toString().replace(/^#/,"");e&&(a=a.replace(new RegExp(Rn(e.separatorInEN),"g"),e.replaceSeparatorWith));let o=e&&e.replaceSpaceWith||"-";return a=a.replace(/ /g,o),`${Q.useHashTags?"#":""}${a}`}).join(" ")}return""},Wl;try{Wl=window.require("btime")}catch(r){}var to=(r,t)=>{let e=(0,rr.moment)(t.created).valueOf();e>0&&Wl&&Wl.btime(r,e);let i=(0,rr.moment)(t.updated).valueOf()/1e3;try{ue.utimesSync(r,i,i)}catch(a){}},bm=r=>r["resource-attributes"]&&r["resource-attributes"].timestamp?(0,rr.moment)(r["resource-attributes"].timestamp):(0,rr.moment)();var ym=(r,t,e)=>{let n=r.lastIndexOf(t);return n<0?r:r.substring(0,n)+e+r.substring(n+t.length)};var Ye={mdPath:"",resourcePath:""},no=249,Vl=100,xm=(r,t,e="")=>{let n=t,i=t,a=1,o=`${r}${K.sep}${i}${e}`;for(;ue.existsSync(o);)if(i=`${n} (${a})`,o=`${r}${K.sep}${i}${e}`,a++,a>9999)throw new Error(`Too many duplicate items with name:
|
||
|
|
|\r|
|
||
|
|
))*?(?=${n})${n}`;return r.replace(new RegExp(o,"g"),"")};var Pr=(r,t,e,n)=>({template:r,check:t,startBlockPlaceholder:e.START_BLOCK,endBlockPlaceholder:e.END_BLOCK,valuePlaceholder:e.CONTENT_PLACEHOLDER,value:n});var Om=(r,t,e)=>{let n=Pr(t,e,Yl,r.content);return Nr(n)};var Si={};ot(Si,{CONTENT_PLACEHOLDER:()=>ww,END_BLOCK:()=>Ew,START_BLOCK:()=>vw});var ww="{tags}",vw="{tags-block}",Ew="{end-tags-block}";var Im=(r,t,e)=>{let n=Pr(t,e,Si,r.tags);return Nr(n)};var Zl={};ot(Zl,{CONTENT_PLACEHOLDER:()=>_w,END_BLOCK:()=>Aw,START_BLOCK:()=>Tw});var _w="{title}",Tw="{title-block}",Aw="{end-title-block}";var Fm=(r,t,e)=>{let n=Pr(t,e,Zl,r.title);return Nr(n)};var tn={};ot(tn,{CONTENT_PLACEHOLDER:()=>Cw,END_BLOCK:()=>Nw,START_BLOCK:()=>kw});var Cw="{created-at}",kw="{created-at-block}",Nw="{end-created-at-block}";var Ze=(r,t,e)=>r.replace(new RegExp(`${t.CONTENT_PLACEHOLDER}`,"g"),e||"").replace(new RegExp(`${t.START_BLOCK}`,"g"),"").replace(new RegExp(`${t.END_BLOCK}`,"g"),"");var Lm=(r,t)=>Ze(t,tn,r.createdAt);var rn={};ot(rn,{CONTENT_PLACEHOLDER:()=>Pw,END_BLOCK:()=>Dw,START_BLOCK:()=>Sw});var Pw="{updated-at}",Sw="{updated-at-block}",Dw="{end-updated-at-block}";var Mm=(r,t)=>Ze(t,rn,r.updatedAt);var nn={};ot(nn,{CONTENT_PLACEHOLDER:()=>Rw,END_BLOCK:()=>Iw,START_BLOCK:()=>Ow});var Rw="{source-url}",Ow="{source-url-block}",Iw="{end-source-url-block}";var $m=(r,t)=>Ze(t,nn,r.sourceUrl);var an={};ot(an,{CONTENT_PLACEHOLDER:()=>Fw,END_BLOCK:()=>Mw,START_BLOCK:()=>Lw});var Fw="{location}",Lw="{location-block}",Mw="{end-location-block}";var Bm=(r,t)=>Ze(t,an,r.location);var on={};ot(on,{CONTENT_PLACEHOLDER:()=>$w,END_BLOCK:()=>qw,START_BLOCK:()=>Bw});var $w="{notebook}",Bw="{notebook-block}",qw="{end-notebook-block}";var qm=(r,t)=>Ze(t,on,r.notebookName);var Fn={};ot(Fn,{CONTENT_PLACEHOLDER:()=>jw,END_BLOCK:()=>Hw,START_BLOCK:()=>Uw});var jw="{reminder-time}",Uw="{reminder-time-block}",Hw="{end-reminder-time-block}";var jm=(r,t)=>Ze(t,Fn,r.reminderTime);var Ln={};ot(Ln,{CONTENT_PLACEHOLDER:()=>Ww,END_BLOCK:()=>zw,START_BLOCK:()=>Vw});var Ww="{reminder-order}",Vw="{reminder-order-block}",zw="{end-reminder-order-block}";var Um=(r,t)=>Ze(t,Ln,r.reminderOrder);var Mn={};ot(Mn,{CONTENT_PLACEHOLDER:()=>Gw,END_BLOCK:()=>Zw,START_BLOCK:()=>Yw});var Gw="{reminder-done-time}",Yw="{reminder-done-time-block}",Zw="{end-reminder-done-time-block}";var Hm=(r,t)=>Ze(t,Mn,r.reminderDoneTime);var Di={};ot(Di,{CONTENT_PLACEHOLDER:()=>Kw,END_BLOCK:()=>Jw,START_BLOCK:()=>Xw});var Kw="{tags-yaml-list}",Xw="{tags-yaml-list-block}",Jw="{end-tags-yaml-list-block}";var Wm=(r,t,e)=>{let n;r.tags&&(n=`
|
||
|
|
`+r.tags.split(" ").map(a=>` - ${a.replace(/^#/,"")}`).join(`
|
||
|
|
`));let i=Pr(t,e,Di,n);return Nr(i)};var Kl="{metadata-block}",Xl="{end-metadata-block}";var Vm=`\r?
|
||
|
|
?`;var Le=(r,t)=>r.replace(new RegExp(`${t.START_BLOCK}(?<=${t.START_BLOCK})(.*)(?=${t.END_BLOCK})${t.END_BLOCK}${Vm}`,"g"),"");var zm=r=>Le(r,tn);var Gm=r=>Le(r,rn);var Ym=r=>Le(r,nn);var Zm=r=>Le(r,on);var Km=r=>Le(r,an);var io={};ot(io,{CONTENT_PLACEHOLDER:()=>ev,END_BLOCK:()=>rv,START_BLOCK:()=>tv});var ev="{link-to-original}",tv="{link-to-original-block}",rv="{end-link-to-original-block}";var Xm=r=>Le(r,io);var Jm=r=>Le(r,Fn);var Qm=r=>Le(r,Mn);var eh=r=>Le(r,Ln);var th=(r,t)=>{let e=t.currentTemplate;return e=Fm(r,e,()=>r.title),e=Im(r,e,()=>!t.skipTags),e=Wm(r,e,()=>!t.skipTags),e=Om(r,e,()=>r.content),e=Xm(e),e=!t.skipCreationTime&&r.createdAt?Lm(r,e):zm(e),e=!t.skipUpdateTime&&r.updatedAt?Mm(r,e):Gm(e),e=!t.skipSourceUrl&&r.sourceUrl?$m(r,e):Ym(e),e=!t.skipLocation&&r.location?Bm(r,e):Km(e),e=t.isNotebookNameNeeded&&r.notebookName?qm(r,e):Zm(e),e=!t.skipReminderTime&&r.reminderTime?jm(r,e):Jm(e),e=!t.skipReminderOrder&&r.reminderOrder?Um(r,e):eh(e),e=!t.skipReminderDoneTime&&r.reminderDoneTime?Hm(r,e):Qm(e),e=e.replace(Kl,"").replace(Xl,""),e};var rh=(r,t,e)=>{try{ue.writeFileSync(r,t),to(r,e)}catch(n){throw console.error("Cannot write file ",n),n}};var nh=(r,t)=>{let e=Em(t);et.getInstance().setCurrentNotePath(e),rh(e,r,t),console.log(`Note saved to ${e}`)};var sh=r=>{let t=new RegExp(`\\${K.sep}`,"g"),e=_m(r).replace(t,Q.pathSeparator||"/");return{absoluteResourceWorkDir:zl(r),relativeResourceWorkDir:e}},lh=r=>{let t={},e=r.content,{absoluteResourceWorkDir:n,relativeResourceWorkDir:i}=sh(r);if(console.log(`relative resource work dir: ${i}`),console.log(`absolute resource work dir: ${n}`),Tm(r),Array.isArray(r.resource))for(let a of r.resource)t={...t,...ah(n,a)};else t={...t,...ah(n,r.resource)};for(let a of Object.keys(t))e=nv(e,t,a,i);return e},nv=(r,t,e,n)=>{let i=`${n}${Q.pathSeparator}${t[e].fileName.replace(/ /g," ")}`;console.log(`mediaReference src ${i} added`);let a,o=`<en-media ([^>]*)hash="${e}".([^>]*)>`,l=new RegExp(o,"g"),s=r.match(l),c=s&&s.length>0&&s[0].split("type=");if(c&&c.length>1&&c[1].startsWith('"image')){let u=s[0].match(/width="(\w+)"/),p=u?` width="${u[1]}"`:"",f=s[0].match(/height="(\w+)"/),d=f?` height="${f[1]}"`:"";a=r.replace(l,`<img src="${i}"${p}${d} alt="${t[e].fileName}">`)}else a=r.replace(l,`<a href="${i}" type="file">${t[e].fileName}</a>`);return a},ah=(r,t)=>{let e={};if(!t.data||!t.data.$text)return console.warn("Resource data is missing or empty, skipping resource:",t),e;let n=t.data.$text,i=bm(t),o=Xf(r,t).fileName,l=`${r}${K.sep}${o}`;console.log(t),console.log(n);let s=Buffer.from(n,"base64");ue.writeFileSync(l,s);let c=i.valueOf()/1e3;try{ue.utimesSync(l,c,c)}catch(u){}if(t.recognition&&o){let u=t.recognition.match(/[a-f0-9]{32}/);console.log(`resource ${o} added with hash ${u}`),e[u]={fileName:o,alreadyUsed:!1}}else{let u=oh.default.createHash("md5");u.update(s);let p=u.digest("hex");e[p]={fileName:o,alreadyUsed:!1}}return e},ch=(r,t)=>{if(t.indexOf('src="data:')<0)return t;let{absoluteResourceWorkDir:e,relativeResourceWorkDir:n}=sh(r);return ue.mkdirSync(e,{recursive:!0}),t.replace(/src="data:([^;,]*)(;base64)?,([^"]*)"/g,(i,a,o,l)=>{let s=iv(a,o===";base64",l,e,r);return`src="${`${n}${Q.pathSeparator}${s}`}"`})},iv=(r,t,e,n,i)=>{let a="embedded",o=av(r)||".dat",l=Pi(n,a),s=l<1?`${a}.${o}`:`${a}.${l}.${o}`,c=`${n}${K.sep}${s}`;return t||(e=decodeURIComponent(e)),ue.writeFileSync(c,e,t?"base64":void 0),to(c,i),console.log(`data url resource ${s} added`),s},av=r=>r.split("/").pop().split("+")[0];var uh=(r,t)=>{let e=new Date;et.getInstance().setCurrentNoteName(r.title),Array.isArray(r.content)&&(r.content=r.content.join(""));let i={title:r.title,content:r.content,htmlContent:r.content,originalContent:r.content};console.log(`Converting for note "${i.title}" started at ${e}...`);try{Dm(r)&&(i.htmlContent=lh(r)),i.htmlContent=ch(r,i.htmlContent),i={...i,...mm(Q,i)},i={...i,...hm(r,t)},i={...i,...gm(r)};let a=th(i,Q);nh(a,r)}catch(a){throw console.error(`Failed to convert note: ${i.title}`,a),a}finally{let a=new Date,o=(a.getTime()-e.getTime())/1e3;console.log(`Convers
|
||
|
|
`,uv=`{source-url-block}source: {source-url}{end-source-url-block}
|
||
|
|
`,pv=`{tags-yaml-list-block}
|
||
|
|
tags: {tags-yaml-list}
|
||
|
|
|
||
|
|
{end-tags-yaml-list-block}`,dv=`{content-block}{content}{end-content-block}
|
||
|
|
`,_h=Eh+pv+uv+Eh+dv;var Nv=Rh.Platform.isDesktopApp?Dh():null,so={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"}},Pv="@@@",Q={...so};function Sv(r){return r==null?r:JSON.parse(JSON.stringify(r))}function Oh(r,...t){for(let e of t)for(let n of Object.keys(e)){let i=e[n],a=r[n];!Array.isArray(i)&&typeof i=="object"&&!Array.isArray(a)&&typeof a=="object"?r[n]=Oh({},a,i):r[n]=Sv(i)}return r}var Dv=r=>{Q=Oh({},so,r);let t=Q.templateFile?ue.readFileSync(Q.templateFile,"utf-8"):_h;t=Q.currentTemplate?Q.currentTemplate:t,Q.skipCreationTime=!gh(t),Q.skipLocation=!bh(t),Q.skipSourceUrl=!xh(t),Q.skipTags=!wh(t),Q.skipUpdateTime=!vh(t),Q.isNotebookNameNeeded=yh(t),Q.currentTemplate=t,console.log(`Current config is: ${JSON.stringify(Q,null,4)}`),console.log(`Path separator:${K.sep}`)},Rv=async(r,t,e)=>{if(!(t instanceof bt))throw new Error("Evernote import currently only works on desktop");let n=et.getInstance();e.status("Processing "+t.name),console.log(`Getting stream from ${t}`);let i=t.createReadStream(),a={},o=n.getCurrentNotebookName();return new Promise((l,s)=>{let c=f=>(e.reportFailed(n.getCurrentNotebookFullpath(),f),s(f)),u=Nv(i),p=null;u.on("tag:note-attributes",f=>{p=f}),u.on("tag:note",f=>{if(e.isCancelled()){i.close();return}if(r.skipWebClips&&Rm(f))e.reportSkipped(f.title);else{e.status("Importing note "+f.title),p&&(f["note-attributes"]=p);try{uh(f,o),e.reportNoteSuccess(o+"/"+f.title)}catch(g){return e.reportFailed(f.title||t,g),l()}}p=null;let d=n.getCurrentNotePath();if(d)for(let g of Object.keys(a)){let m=`<YARLE-EN-V10-TASK>${g}</YARLE-EN-V10-TASK>`,h=ue.readFileSync(d,"utf8"),b=new Map([...a[g]].sort()),T=h.replace(m,[...b.values()].join(`
|
||
|
|
`));ue.writeFileSync(d,T)}}),u.on("tag:task",f=>{let d=Nf(f);a[d.taskgroupnotelevelid]||(a[d.taskgroupnotelevelid]=new Map),a[d.taskgroupnotelevelid].set(d.sortweight,mh(d,o))}),u.on("end",l),u.on("error",c),i.on("error",c)})};async function Ih(r,t){Dv(r);let e=[],n=r.outputDir;for(let i of r.enexSources){if(t.isCancelled())return;let a,o=et.getInstance();i.basename.includes(Pv)?(r.outputDir=km(i,r),a=Cm(i),Pm(a,r),o.setCurrentNotebookName(a.basename),o.setCurrentNotebookFullpath(a.fullpath)):(Nm(i,r),o.setCurrentNotebookName(i.basename),o.setCurrentNotebookFullpath(i.fullpath)),await Rv(r,i,t),e.push(Gl()),r.outputDir=n}t.isCancelled()||await hh(r,e)}var lo=class extends Ee{init(){this.addFileChooserSetting("Evernote",["enex"],!0),this.addOutputLocationSetting("Evernote")}async import(t){let{files:e}=this;if(e.length===0){new Oi.Notice("Please pick at least one file to import.");return}let n=await this.getOutputFolder();if(!n){new Oi.Notice("Please select a location to export to.");return}let{app:i}=this,a=i.vault.adapter;if(!(a instanceof Oi.FileSystemAdapter))return;let o={...so,enexSources:e,outputDir:K.join(a.getBasePath(),n.path)};await Ih(o,t)}};var tt=require("obsidian");var co=class extends Ee{init(){this.addFileChooserSetting("HTML",["htm","html"],!0),this.addAttachmentSizeLimit(0),this.addMinimumImageSize(65),this.addOutputLocationSetting("HTML import")}addAttachmentSizeLimit(t){this.attachmentSizeLimit=t*10**6,new tt.Setting(this.modal.contentEl).setName("Attachment size limit (MB)").setDesc("Set 0 to disable.").addText(e=>e.then(({inputEl:n})=>{n.type="number",n.step="0.1"}).setValue(t.toString()).onChange(n=>{let i=["+","-"].includes(n)?0:Number(n);if(Number.isNaN(i)||i<0){e.setValue((this.attachmentSizeLimit/10**6).toString());return}this.attachmentSizeLimit=i*10**6}))}addMinimumImageSize(t){this.minimumImageSize=t,new tt.Setting(this.modal.contentEl).setName("Minimum image size (px)").setDesc("Set 0 to disable.").addText(e=>e.then(({inputEl:n})=>n.type="number").setValue(t.toString()).onChange(n=>{let i=["+","-"].includes(n)?0:Number(n);if(!Number.isInteger(i)||i<0){e.setValue(this.minimumImageSize.toString());return}this.minimumImageSize=i}))}async import(t){let{files:e}=this;if(e.length===0){new tt.Notice("Please pick at least one file to import.");return}let n=await this.getOutputFolder();if(!n){new tt.Notice("Please select a location to export to.");return}let i=new Map;t.reportProgress(0,e.length);for(let s=0;s<e.length;s++){if(t.isCancelled())return;let c=e[s],u=await this.processFile(t,n,c);u&&i.set(c instanceof bt?pi.pathToFileURL(c.filepath).href:c.name,{file:c,tFile:u}),t.reportProgress(s+1,e.length)}let{metadataCache:a}=this.app,o,l=new Promise(s=>{o=s});a.onCleanCache(async()=>{for(let[s,{file:c,tFile:u}]of i){if(t.isCancelled())break;try{let p=await this.app.vault.cachedRead(u),f=a.computeMetadataAsync?await a.computeMetadataAsync($s(p)):a.getFileCache(u);if(!f)continue;let d=[];if(f.links)for(let{link:g,position:m,displayText:h}of f.links){let{path:b,subpath:T}=(0,tt.parseLinktext)(g),P;if(pi){let O=new URL(encodeURI(b),s);O.hash="",O.search="",P=decodeURIComponent(O.href)}else P=le(b.replace(/#/gu,"%23")).name;let k=i.get(P);if(k){let O=this.app.fileManager.generateMarkdownLink(k.tFile,u.path,T,h);d.push({from:m.start.offset,to:m.end.offset,text:O})}}d.sort((g,m)=>m.from-g.from);for(let g of d)p=p.substring(0,g.from)+g.text+p.substring(g.to);await this.vault.modify(u,p)}catch(p){t.reportFailed(c.fullpath,p)}}o()}),await l}async processFile(t,e,n){t.status("Processing "+n.name);try{let i=await n.readText(),a=At(i);Ov(a);let o=n instanceof bt?pi.pathToFileURL(n.filepath):void 0,l=o?new URL("./",o.href).href:void 0,s=new Map,c=new Map;for(let f of a.findAll("img, audio, video")){if(t.isCancelled())return;let d=f.getAttribute("src");if(d)try{let g=new URL(d.startsWith("//")?`https:${d}`:d,o);if(g.protocol==="data:")continue;let m=g.href,h=s.get(m);s.has(m)||(t.status("Downloading attachment for "+n.name),h=await this.downloadAttachment(e,f,g,l),s.set(m,h),h?(c.set(h.path,h),t.reportAttachmentS
|
||
|
|
`).filter(u=>u!==i);c.length>0&&(o.aliases=c)}let l=[];if(e.color&&e.color!=="DEFAULT"){let c=e.color.toLowerCase();c=Lh(c),l.push(`Keep/Color/${c}`)}if(e.isPinned&&l.push("Keep/Pinned"),e.attachments&&l.push("Keep/Attachment"),e.isArchived&&l.push("Keep/Archived"),e.isTrashed&&l.push("Keep/Deleted"),e.labels)for(let c of e.labels)l.push(`Keep/Label/${c.name}`);if(l.length>0&&(o.tags=l.map(c=>rc(c))),a.push(yr(o)),e.textContent&&(a.push(`
|
||
|
|
`),a.push(nc(e.textContent))),e.listContent){let c=[];for(let u of e.listContent){if(!u.text)continue;let p=`- [${u.isChecked?"X":" "}] ${u.text}`;c.push(nc(p))}a.push(`
|
||
|
|
|
||
|
|
`),a.push(c.join(`
|
||
|
|
`))}if(e.attachments){a.push(`
|
||
|
|
|
||
|
|
`);for(let c of e.attachments)a.push(`![[${c.filePath}]]`)}let s=await this.saveAsMarkdownFile(n,i,a.join(""));await this.vault.append(s,"",{ctime:e.createdTimestampUsec/1e3,mtime:e.userEditedTimestampUsec/1e3})}};var ir=require("obsidian");var ic=require("obsidian");function Mh({info:r,vault:t,targetFolderPath:e,parentsInSubfolders:n}){let i=t.getAllLoadedFiles(),a=new Set,o=new Set(i.map(l=>l.name));n&&Hv(r),Uv({info:r,pathDuplicateChecks:a,titleDuplicateChecks:o}),Wv({info:r,loadedFiles:i,titleDuplicateChecks:o,targetFolderPath:e})}function Uv({info:r,pathDuplicateChecks:t,titleDuplicateChecks:e}){for(let n of Object.values(r.idsToFileInfo)){let i=r.getPathForFile(n);if(t.has(`${i}${n.title}`)){let a=2;for(n.title=n.title+" "+a;t.has(`${i}${n.title}`);)a++,n.title=`${n.title.replace(/ \d+$/,"")} ${a}`}e.has(n.title+".md")&&(n.fullLinkPathNeeded=!0),t.add(`${i}${n.title}`),e.add(n.title+".md")}}function Hv(r){let t=new Set(Object.values(r.idsToFileInfo).map(e=>e.parentIds).concat(Object.values(r.pathsToAttachmentInfo).map(e=>e.parentIds)).map(e=>e.length>0?e[e.length-1]:""));for(let e of Object.keys(r.idsToFileInfo))t.has(e)&&r.idsToFileInfo[e].parentIds.push(e)}function Wv({info:r,loadedFiles:t,titleDuplicateChecks:e,targetFolderPath:n}){var s;let i=new Set(t.filter(c=>!c.path.endsWith(".md")).map(c=>c.path)),a=r.attachmentPath,o=/^\.\//.test(a),l=(s=a.match(/\.\/(.*)/))==null?void 0:s[1];for(let c of Object.values(r.pathsToAttachmentInfo)){e.has(c.nameWithExtension)&&(c.fullLinkPathNeeded=!0);let u="";if(o?u=(0,ic.normalizePath)(`${n}${r.getPathForFile(c)}${l!=null?l:""}`):u=(0,ic.normalizePath)(a+"/"),u.endsWith("/")||(u+="/"),i.has(u+c.nameWithExtension)){let p=2,{basename:f,extension:d}=le(c.path);for(;i.has(`${u}${f} ${p}.${d}`);)p++;c.nameWithExtension=`${f} ${p}.${d}`}c.targetParentFolder=u,i.add(u+c.nameWithExtension),e.add(c.nameWithExtension)}}var jn=require("obsidian");var $h=r=>r.replace(/-/g,"").replace(/[ -]?[a-z0-9]{32}(\.|$)/,"$1"),nr=r=>{var t;return(t=r.replace(/-/g,"").match(/([a-z0-9]{32})(\?|\.|$)/))==null?void 0:t[1]},ac=r=>{let{parent:t}=le(r);return t.split("/").map(e=>nr(e)).filter(e=>e)};function oc(r){return r.hour()===0&&r.minute()===0?r.format("YYYY-MM-DD"):r.format("YYYY-MM-DDTHH:mm")}function Bh(r){return r.replace(/^(\.\.\/)+/,"")}function qh(r){let t=/#\d*?(?:[-_/a-z]|[^\x00-\x7F])/gi;if(!t.test(r))return r;let e=r.split(`
|
||
|
|
`);for(let n=0;n<e.length;n++){let i=e[n].match(t);if(!i)continue;let a=e[n];for(let o of i)new RegExp(`\\[\\[[^\\]]*${o}(?:.*[^\\]])?\\]\\]|\\[[^\\]]*${o}[^\\]]*\\]\\([^\\)]*\\)|\\[[^\\]]*\\]\\([^\\)]*${o}[^\\)]*\\)|\\\\${o}|\`[^\`]*${o}[^\`]*\``).test(a)||(a=a.replace(o,"\\"+o));e[n]=a}return r=e.join(`
|
||
|
|
`),r}function sc(r){r.replaceWith(...Array.from(r.childNodes))}async function Zh(r,t){var u;let e=await t.readText(),n=At(e),i=n.find("div[class=page-body]");if(i===null)throw new Error("page body was not found");let a=jh(r,i);Yh(r,a,!0);let o={},l=n.find("table[class=properties] > tbody");if(l){let p=jh(r,l);Yh(r,p,!1),d2(l);for(let f of Array.from(l.rows)){let d=zv(f);d&&(d.title=="Tags"&&(d.title="tags",typeof d.content=="string"?d.content=d.content.replace(/ /g,"-"):d.content instanceof Array&&(d.content=d.content.map(g=>g.replace(/ /g,"-")))),o[d.title]=d.content)}}r2(i,["strong","em","mark","del"]),Qv(i),Yv(i),l2(i),Xv(i),s2(i),Jh(i),zh(i,"div.indented"),zh(i,"details"),c2(i),Gh(i,"ul"),Gh(i,"ol"),u2(i),p2(i),o2(i),e2(i);let s=(0,jn.htmlToMarkdown)(i.innerHTML);r.singleLineBreaks&&(s=s.replace(/\n\n(?!>)/g,`
|
||
|
|
`)),s=qh(s),s=Gv(s);let c=(u=n.find("p[class*=page-description]"))==null?void 0:u.textContent;return c&&(s=c+`
|
||
|
|
|
||
|
|
`+s),yr(o)+s}var Vv=new Map([["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"]]]);function zv(r){var o,l,s,c,u,p;let t=(o=r.className.match(/property-row-(.*)/))==null?void 0:o[1];if(!t)throw new Error("property type not found for: "+r);let e=(0,jn.htmlToMarkdown)((l=r.cells[0].textContent)!=null?l:""),n=r.cells[1],i;for(let[f,d]of Vv.entries())if(d.includes(t)){i=f;break}if(!i)throw new Error("type not found for: "+n);let a="";switch(i){case"checkbox":a=n.innerHTML.includes("checkbox-on");break;case"number":if(a=Number(n.textContent),isNaN(a))return;break;case"date":Jh(n);let f=n.getElementsByTagName("time");if(f.length===0)a="";else if(f.length===1)a=oc((0,jn.moment)((s=f.item(0))==null?void 0:s.textContent));else{let m=[];for(let h=0;h<f.length;h++)m.push(oc((0,jn.moment)((c=f.item(h))==null?void 0:c.textContent)));a=m.join(" - ")}if(a.length===0)return;break;case"list":let d=n.children,g=[];for(let m=0;m<d.length;m++){let h=(u=d.item(m))==null?void 0:u.textContent;h&&g.push(h)}if(a=g,a.length===0)return;break;case"text":if(a=(p=n.textContent)!=null?p:"",a.length===0)return;break}return{title:e,content:a}}function jh(r,t){var n,i;let e=[];for(let a of t.findAll("a")){let o=Bh(decodeURI((n=a.getAttribute("href"))!=null?n:"")),l=nr(o),s=Object.keys(r.pathsToAttachmentInfo).find(c=>c.includes(o));l&&o.endsWith(".html")?e.push({type:"relation",a,id:l}):s?e.push({type:"attachment",a,path:s}):l&&o.startsWith("#")&&((i=a.parentElement)!=null&&i.classList.contains("table_of_contents-item"))&&e.push({type:"toc-item",a,id:l})}return e}function Gv(r){let t=/\[\[[^\]]*(\\\\)\|[^\]]*\]\]/,e=r.match(new RegExp(t,"g"));return e==null||e.forEach(n=>{r=r.replace(n,n.replace(/\\\\\|/g,"\\|"))}),r}function Yv(r){t2(r,"style"),Kh(r,"span.notion-text-equation-token");let t=r.ownerDocument,e=r.findAll("figure.equation");for(let i of e){let a=i.find("annotation");if(!a)continue;let o=t.createElement("div");o.className="annotation",o.appendText(`$$${Uh(a.textContent)}$$`),i.replaceWith(o)}let n=r.findAll("span.notion-text-equation-token");for(let i of n){let a=i.find("annotation");a&&i.replaceWith(`$${Uh(a.textContent,!0)}$`)}}function Uh(r,t=!1){var n;let e=new RegExp(/^(?:\s|\\\\|\\\s)*(.*?)[\s\\]*$/,"s");return(n=r==null?void 0:r.replace(e,"$1").replace(/[\r\n]+/g,t?" ":`
|
||
|
|
`))!=null?n:""}function Zv(r){var e;let t=(e=r.match(/^[^\.\?\!\n]*[\.\?\!]?/))==null?void 0:e[0];return t!=null?t:""}function Kv(r){var t;return!!/callout|bookmark/.test((t=r.getAttribute("class"))!=null?t:"")}function Xv(r){var e;let t=r.ownerDocument;for(let n of r.findAll("figure.callout")){let i=(e=n.lastElementChild)==null?void 0:e.childNodes;if(!i)continue;let a=t.createElement("blockquote");a.append(...Array.from(i)),Jv(a),n.replaceWith(a)}}function Jv(r){var a,o,l;let t=r.firstChild,e=(a=t==null?void 0:t.nodeName)!=null?a:"",n=r.ownerDocument,i=n.createElement("p");if(i.appendText("[!important] "),e=="#text")i.appendText((o=t==null?void 0:t.textContent)!=null?o:"");else if(e=="P"||["EM","STRONG","DEL","MARK"].includes(e)){let s=t.cloneNode(!0);for(let c of Array.from(s.querySelectorAll("br")))c.replaceWith(n.createTextNode("<br>"));e=="P"?i.append(...Array.from(s.childNodes)):i.appendChild(s)}else{r.prepend(i);return}(l=r.firstChild)==null||l.replaceWith(i)}function Qv(r){var t,e,n;for(let i of r.findAll("a.bookmark.source")){let a=i.getAttribute("href"),o=(t=i.find("div.bookmark-title"))==null?void 0:t.textContent,l=Zv((n=(e=i.find("div.bookmark-description"))==null?void 0:e.textContent)!=null?n:""),s=`> [!info] ${o}
|
||
|
|
> ${l}
|
||
|
|
> [${a}](${a})
|
||
|
|
`;i.nextElementSibling&&Kv(i.nextElementSibling)&&(s+=`
|
||
|
|
`),i.replaceWith(s)}}function e2(r){var t,e,n;for(let i of r.findAll("span[class=user]"))i.innerText=(t=i.textContent)!=null?t:"";for(let i of r.findAll("td div[class*=checkbox]")){let a=createSpan();a.setText(i.hasClass("checkbox-on")?"X":""),i.replaceWith(a)}for(let i of r.findAll("table span[class*=selected-value]"))((e=i.parentElement)==null?void 0:e.lastElementChild)!==i&&i.setText(i.textContent+", ");for(let i of r.findAll("a[href]"))if(!/^(https?:\/\/|www\.)/.test(i.href)){let a=createSpan();a.setText((n=i.textContent)!=null?n:""),i.replaceWith(a)}}function t2(r,t){for(let e of r.findAll(t))e.remove()}function r2(r,t){for(let e of t)n2(r,e);for(let e of t)i2(r,e);for(let e of t)Kh(r,e);for(let e of t)a2(r,e)}function n2(r,t){for(let e of r.findAll(t)){if(!e.parentElement||e.parentElement.tagName===t.toUpperCase())continue;let n=e.find(t);for(;n;)sc(n),n=e.find(t)}}function i2(r,t){let e=t.toUpperCase();for(let n of r.findAll(t))if(n.parentElement)for(;;){let i=n.nextSibling,a=null;if(i&&i.nodeType===Node.TEXT_NODE&&/^ *$/.test(i.data)&&(a=i,i=i.nextSibling),!i||i.nodeName!==e)break;a&&n.appendChild(a),n.append(...Array.from(i.childNodes)),i.remove()}}function Kh(r,t){let e=r.findAll(t);if(e)for(let n of e){let i=n.previousSibling;(i==null?void 0:i.nodeName)=="BR"&&(i==null||i.remove())}}function a2(r,t){for(let e of r.findAll(t)){if(!e.parentElement||!Array.from(e.childNodes).some(l=>l.nodeName==="BR"))continue;let i=e.ownerDocument,a=[],o=i.createElement(t);for(let l of Array.from(e.childNodes))l.nodeName==="BR"?(o.hasChildNodes()&&a.push(o),a.push(l),o=i.createElement(t)):o.appendChild(l);o.hasChildNodes()&&a.push(o),e.replaceWith(...a)}}function Hh(r){var t;return Number((t=r==null?void 0:r.classList[1].slice(-1))!=null?t:-1)}function Xh(r,t){let e=Hh(r),n=Hh(t);if(e>n&&t.childElementCount==1){let i=createEl("ul");i.append(r),t.append(i)}else if(e>n&&t.childElementCount==2){let i=t.lastElementChild;i==null||i.append(r)}else if(e==n){let i=t.parentElement;i==null||i.append(r)}else e<n&&(t=t.parentElement.parentElement,Xh(r,t))}function Wh(r){var e;let t=createEl("li");return t.className=r.className,t.append((e=r.firstElementChild)!=null?e:""),t}function o2(r){let t=r.find(".table_of_contents"),e=t==null?void 0:t.children;if(!t||e.length==0)return;let n=createEl("ul"),i=Wh(e[0]);n.append(i);let a=i;for(let o=1;o<e.length;o++)i=Wh(e[o]),Xh(i,a),a=i;t.replaceWith(n)}function s2(r){let t=r.ownerDocument,e=t.createTreeWalker(r,NodeFilter.SHOW_TEXT),n=[],i=e.nextNode();for(;i;)i.data.includes(`
|
||
|
|
`)&&n.push(i),i=e.nextNode();for(let a of n){let o=a.data.split(`
|
||
|
|
`),l=[];for(let s=0;s<o.length;s++)o[s]&&l.push(t.createTextNode(o[s])),s<o.length-1&&l.push(t.createElement("br"));a.replaceWith(...l)}for(let a of r.findAll("code"))for(let o of a.findAll("br"))o.replaceWith(`
|
||
|
|
`)}function l2(r){var t;for(let e of r.findAll("link"))e.innerText=(t=e.textContent)!=null?t:""}function Jh(r){var t,e;for(let n of r.findAll("time"))n.textContent=(e=(t=n.textContent)==null?void 0:t.replace(/@/g,""))!=null?e:""}var Vh={"1.875em":"h1","1.5em":"h2","1.25em":"h3"};function c2(r){var e;let t=r.findAll("summary");for(let n of t){let i=n.getAttribute("style");if(i){for(let a of Object.keys(Vh))if(i.includes(a)){n.replaceWith(createEl(Vh[a],{text:(e=n.textContent)!=null?e:""}));break}}}}function zh(r,t){let e=r.findAll(t);for(let n of e)sc(n)}function u2(r){for(let t of r.findAll(".language-Mermaid"))t.removeClass("language-Mermaid"),t.addClass("language-mermaid")}function Gh(r,t){for(let e of r.findAll(t)){let n=[],i=[],a=e;for(;a.tagName===t.toUpperCase();){n.push(a);for(let l=0;l<a.children.length;l++)i.push(a.children[l]);if(!a.nextElementSibling||a.getAttribute("class")!==a.nextElementSibling.getAttribute("class"))break;a=a.nextElementSibling}let o=r.createEl(t);for(let l of i)o.appendChild(l);n[0].replaceWith(o),n.slice(1).forEach(l=>l.remove())}}function p2(r){for(let t of r.findAll(".checkbox.checkbox-on"))t.replaceWith("[x] ");for(let t of r.findAll(".checkbox.checkbox-off"))t.replaceWith("[ ] ")}function d2(r){var e;let t=r.findAll("a");if(t.length===0)return r;for(let n of t){let i=createSpan();i.setText((e=n.getAttribute("href"))!=null?e:""),n.replaceWith(i)}}function Yh(r,t,e){var n,i,a;for(let o of t){let l=createSpan(),s="";switch(o.type){case"relation":let c=r.idsToFileInfo[o.id];if(c){let f=o.a.closest("table");s=`[[${c.fullLinkPathNeeded?`${r.getPathForFile(c)}${c.title}${f?"\\":""}|${c.title}`:c.title}]]`}else{console.warn("missing relation data for id: "+o.id);let{basename:f}=le(decodeURI((n=o.a.getAttribute("href"))!=null?n:""));s=`[[${$h(f)}]]`}break;case"attachment":let u=r.pathsToAttachmentInfo[o.path];if(!u){console.warn("missing attachment data for: "+o.path);continue}s=`${e?"!":""}[[${u.fullLinkPathNeeded?u.targetParentFolder+u.nameWithExtension+"|"+u.nameWithExtension:u.nameWithExtension}]]`;break;case"toc-item":s=(i=o.a.textContent)!=null?i:"";let p=(a=s.endsWith("]"))!=null?a:!1;s=`[[#${s+(p?" ":"")}]]`}l.setText(s),o.a.replaceWith(l)}}var po=class{constructor(t,e){this.idsToFileInfo={};this.pathsToAttachmentInfo={};this.attachmentPath=t,this.singleLineBreaks=e}getPathForFile(t){let{idsToFileInfo:e}=this,n=t.path.split("/");if(t.parentIds.length>0){let l=t.parentIds.map(s=>{var c,u,p;return(p=(c=e[s])==null?void 0:c.title)!=null?p:(u=n.find(f=>f.contains(s)))==null?void 0:u.replace(` ${s}`,"")}).filter(s=>s).map(s=>s.replace(/[\. ]+$/,""));if(l.length>0)return l.join("/")+"/"}let{parent:i}=le(t.path);if(!i)return"";let o=i.split("/").filter(l=>l.length>0).map(l=>l.replace(/\s+[a-z0-9]{32}$/,"").trim()).filter(l=>l.length>0).map(l=>l.replace(/[\. ]+$/,"")).join("/");return o?o+"/":""}};async function eg(r,t){var n,i;let{filepath:e}=t;if(t.extension==="html"){let a=await t.readText(),o=At(a),s=o.find("body").children,c;for(let g=0;g<s.length&&(c=nr((n=s[g].getAttr("id"))!=null?n:""),!c);g++);if(!c)throw new Error("no id found for: "+e);let u=Qh(o,"property-row-created_time"),p=Qh(o,"property-row-last_edited_time"),f=((i=o.find("title"))==null?void 0:i.textContent)||"Untitled",d=f2(Te(f.replace(/\n/g," ").replace(/[:\/]/g,"-").replace(/#/g,"").trim()));r.idsToFileInfo[c]={path:e,parentIds:ac(e),ctime:u,mtime:p,title:d,fullLinkPathNeeded:!1}}else r.pathsToAttachmentInfo[e]={path:e,parentIds:ac(e),nameWithExtension:Te(decodeURIComponent(t.name)),targetParentFolder:"",fullLinkPathNeeded:!1}}function f2(r){if(r.length<200)return r;let t=r.split(" "),e=[],n=0,i=0,a=!1;for(;n<200;){if(!t[i]){a=!0;break}e.push(t[i]),n+=t[i].length+1,i++}let o=e.join(" ");return a||(o+="..."),o}function m2(r){let t=r.startsWith("@")?r.substr(1).trim():r.trim(),e=new Date(t);return isNaN(e.getTime())?null:e}function Qh(r,t){let e=r.querySelector(`tr.${t}`);if(e){let n=e.querySelector("time");return n&&n.textContent?m2(n.textContent):null}return null}var fo=class extends Ee{init(){this.parentsInSubfolders=!0,
|
||
|
|
`,o=await pn(t,e,0,n);if(o){let l=o.split(`
|
||
|
|
`).map(s=>`> ${s}`).join(`
|
||
|
|
`);a+=l}return a}function K2(r,t,e){let n=(e==null?void 0:e.indentLevel)||0,i=(e==null?void 0:e.singleLineBreaks)||!1,a=["bulleted_list_item","numbered_list_item","to_do"],o=a.includes(r),l=a.includes(t);return n>0?!!(["callout","toggle","quote","table"].includes(r)||t==="table"):i?!!(["callout","toggle","quote"].includes(r)||o&&!l||r==="table"||t==="table"||t==="divider"):!(o&&l)}async function Mo(r,t){let e=[];for(let n=0;n<r.length&&!t.ctx.isCancelled();n++){let i=r[n];if(i.type!=="numbered_list_item"&&t.listCounters){let o=t.indentLevel||0,l=[];t.listCounters.forEach((s,c)=>{c>o&&l.push(c)}),l.forEach(s=>t.listCounters.delete(s))}let a=await X2(i,t);if(a===""&&i.type==="paragraph")e.push("");else if(a&&(e.push(a),n<r.length-1)){let o=r[n+1],s=!((t==null?void 0:t.singleLineBreaks)||!1)&&Z2(o);K2(i.type,o.type,t)&&!s&&e.push("")}}return e.join(`
|
||
|
|
`)}async function X2(r,t){var i;let e=r.type,n="";switch(e){case"paragraph":n=J2(r,t);break;case"heading_1":case"heading_2":case"heading_3":n=await Q2(r,t);break;case"bulleted_list_item":n=await eE(r,t);break;case"to_do":n=await tE(r,t);break;case"column_list":n=await rE(r,t);break;case"toggle":n=await oE(r,t);break;case"synced_block":n=await aE(r,t);break;case"table":n=await sE(r,t);break;case"numbered_list_item":n=await lE(r,t);break;case"quote":n=await cE(r,t);break;case"callout":n=await uE(r,t);break;case"divider":n=pE(r);break;case"equation":n=dE(r);break;case"code":n=fE(r,t);break;case"image":n=await mE(r,t);break;case"video":n=await gE(r,t);break;case"file":n=await bE(r,t);break;case"pdf":n=await yE(r,t);break;case"bookmark":n=wE(r);break;case"embed":n=vE(r);break;case"link_preview":n=EE(r);break;case"child_database":let a=t.isProcessingSyncedBlock||!1,o=t.indentLevel||0,l=a?"SYNCED_CHILD_DATABASE":"DATABASE_PLACEHOLDER",s=Ht(l,r.id);o>0?n=" ".repeat(o)+s:n=s;break;case"child_page":let c=t.isProcessingSyncedBlock||!1,u=t.indentLevel||0;if(c){let p=r.id,f=Ht("SYNCED_CHILD_PAGE",p);u>0?n=" ".repeat(u)+f:n=f}else if(t.importPageCallback){let p=((i=r.child_page)==null?void 0:i.title)||"Untitled";try{await t.importPageCallback(r.id,t.currentFolderPath);let f=(0,zn.normalizePath)(`${t.currentFolderPath}/${Te(p)}.md`),d=t.vault.getAbstractFileByPath(f),g;if(d&&d instanceof zn.TFile){let m=t.currentFilePath||t.currentFolderPath;g=t.app.fileManager.generateMarkdownLink(d,m)}else g=`[[${p}]]`;u>0?n=" ".repeat(u)+g:n=g}catch(f){let d=f instanceof Error?f.message:String(f);console.error(`Failed to import child page "${p}":`,f),t.ctx.reportFailed(`Child page: ${p}`,d),n=`<!-- Failed to import child page: ${d} -->`}}else console.warn(`child_page block ${r.id} skipped: no import callback provided`),n="";break;default:console.log(`Unsupported block type: ${e}`),n=""}return n}function J2(r,t){return r.type!=="paragraph"?"":sr(r.paragraph.rich_text,t)}async function Q2(r,t){let e=(t==null?void 0:t.indentLevel)||0,n=" ".repeat(e),i="",a;if(r.type==="heading_1")i="# ",a=r.heading_1;else if(r.type==="heading_2")i="## ",a=r.heading_2;else if(r.type==="heading_3")i="### ",a=r.heading_3;else return"";let o=a.is_toggleable||!1,l=sr(a.rich_text,t);return o&&r.has_children?await _g(i+l,r,t,"toggleable heading"):n+i+l}async function eE(r,t){if(r.type!=="bulleted_list_item")return"";let e=t.indentLevel||0,i=" ".repeat(e)+"- "+sr(r.bulleted_list_item.rich_text,t),a=await pn(r,t,e+1,"bulleted list item");return a&&(i+=`
|
||
|
|
`+a),i}async function tE(r,t){if(r.type!=="to_do")return"";let e=t.indentLevel||0,n=" ".repeat(e),i=r.to_do.checked?"[x]":"[ ]",a=n+"- "+i+" "+sr(r.to_do.rich_text,t),o=await pn(r,t,e+1,"to-do item");return o&&(a+=`
|
||
|
|
`+o),a}async function rE(r,t){return r.type!=="column_list"?"":await Io({block:r,client:t.client,ctx:t.ctx,blocksCache:t.blocksCache,processor:async n=>{let i="";for(let a=0;a<n.length;a++){let o=n[a];if(o.type!=="column"){console.warn(`Expected column block, got ${o.type}`);continue}i+=`<!-- Column ${a+1} -->
|
||
|
|
`;let l=await nE(o,t);l&&(i+=l),a<n.length-1&&(i+=`
|
||
|
|
|
||
|
|
`)}return i},errorContext:"column_list"})||""}async function nE(r,t){return r.type!=="column"?"":await pn(r,t,void 0,"column")||""}async function iE(r,t){let{client:e,ctx:n,vault:i,currentFolderPath:a,currentPageTitle:o}=t;if(!a)throw new Error("currentFolderPath is required for synced blocks");let s=`${o||"Page"} synced block`;try{let c=await e.blocks.retrieve({block_id:r});if(!("type"in c))throw new Error(`Retrieved block ${r} is partial, cannot process synced block`);let p=c.has_children?await Oo(r,e,n,t.blocksCache):[],f=un(i,a,`${s}.md`),d={...t,currentFilePath:f,isProcessingSyncedBlock:!0},g=await Mo(p,d),m=Mi(g,"SYNCED_CHILD_PAGE");if(t.syncedChildPagePlaceholders&&m.length>0){let b=t.syncedChildPagePlaceholders.get(f)||new Set;m.forEach(T=>b.add(T)),t.syncedChildPagePlaceholders.set(f,b)}let h=Mi(g,"SYNCED_CHILD_DATABASE");if(t.syncedChildDatabasePlaceholders&&h.length>0){let b=t.syncedChildDatabasePlaceholders.get(f)||new Set;h.forEach(T=>b.add(T)),t.syncedChildDatabasePlaceholders.set(f,b)}return await i.create(f,g),console.log(`Created synced block file: ${f}`),f}catch(c){let u=c instanceof Error?c.message:String(c);throw console.error(`Failed to create synced block file "${s}":`,c),t.ctx.reportFailed(`Synced block: ${s}`,u),c}}async function aE(r,t){if(r.type!=="synced_block")return"";let e=r.synced_block;if(!e)return"";let{syncedBlocksMap:n}=t;if(!n)return console.error("syncedBlocksMap is required for synced blocks"),"";let a=e.synced_from===null?r.id:e.synced_from.block_id,o=n.get(a);if(!o)try{o=await iE(a,t),n.set(a,o)}catch(s){let c=s instanceof Error?s.message:String(s);return console.error(`Failed to process synced block ${a}:`,s),`<!-- Failed to import synced block: ${c} -->`}let l=t.vault.getAbstractFileByPath((0,zn.normalizePath)(o));if(l&&l instanceof zn.TFile){let s=t.currentFilePath||t.currentFolderPath;return`!${t.app.fileManager.generateMarkdownLink(l,s)}`}else{let{basename:s}=le(o);return`![[${s}]]`}}async function oE(r,t){if(r.type!=="toggle")return"";let n=r.toggle,i=sr(n.rich_text,t);return await _g(i,r,t,"toggle block")}async function sE(r,t){if(r.type!=="table")return"";let i=r.table.table_width||0,a=new Array(i).fill("left"),o=await Io({block:r,client:t.client,ctx:t.ctx,blocksCache:t.blocksCache,processor:async l=>{let s=[];for(let c=0;c<l.length;c++){let u=l[c];if(u.type!=="table_row")continue;let f=u.table_row;if(!f.cells)continue;let d=f.cells,g=[];for(let m=0;m<d.length;m++){let h=d[m],b=sr(h,t);b=b.replace(/\n/g,"<br>"),b.trim()||(b=" "),g.push(b)}if(s.push("| "+g.join(" | ")+" |"),c===0){let m=a.map(h=>{switch(h){case"left":return"---";case"center":return":---:";case"right":return"---:";default:return"---"}});s.push("| "+m.join(" | ")+" |")}}return s},errorContext:"table"});return!o||o.length===0?"":o.join(`
|
||
|
|
`)}async function lE(r,t){if(r.type!=="numbered_list_item")return"";let e=t.indentLevel||0;t.listCounters||(t.listCounters=new Map);let n=(t.listCounters.get(e)||0)+1;t.listCounters.set(e,n);let a=" ".repeat(e)+`${n}. `+sr(r.numbered_list_item.rich_text,t),o=await pn(r,t,e+1,"numbered list item");return o&&(a+=`
|
||
|
|
`+o),a}async function cE(r,t){if(r.type!=="quote")return"";let e="> "+sr(r.quote.rich_text,t),n=await pn(r,t,0,"quote block");if(n){let i=n.split(`
|
||
|
|
`).map(a=>`> ${a}`).join(`
|
||
|
|
`);e+=`
|
||
|
|
`+i}return e}async function uE(r,t){if(r.type!=="callout")return"";let n=r.callout,i=n.icon&&"emoji"in n.icon?n.icon.emoji:"\u{1F4CC}",a=sr(n.rich_text,t),o="note";i==="\u{1F4A1}"||i==="\u26A1"?o="tip":i==="\u26A0\uFE0F"||i==="\u2757"?o="warning":i==="\u274C"||i==="\u{1F6AB}"?o="danger":i==="\u2705"||i==="\u2714\uFE0F"?o="success":i==="\u2139\uFE0F"||i==="\u2139"?o="info":(i==="\u2753"||i==="\u{1F914}")&&(o="question");let l=`> [!${o}] ${i}
|
||
|
|
`;l+=`> ${a}`;let s=await pn(r,t,0,"callout block");if(s){let c=s.split(`
|
||
|
|
`).map(u=>`> ${u}`).join(`
|
||
|
|
`);l+=`
|
||
|
|
`+c}return l}function pE(r){return r.type!=="divider"?"":"---"}function dE(r){if(r.type!=="equation")return"";let e=r.equation;return e.expression?`$$
|
||
|
|
${e.expression}
|
||
|
|
$$`:""}function fE(r,t){if(r.type!=="code")return"";let n=r.code;if(!n)return"";let i=n.rich_text.map(o=>o.plain_text||"").join("");return`\`\`\`${n.language||""}
|
||
|
|
${i}
|
||
|
|
\`\`\``}async function $o(r,t,e){let{type:n,isEmbed:i,fallbackText:a,beforeDownload:o}=e,l=bg(r);if(!l)return"";let s=qi(r);if(o){let c=o(l,r);if(c!==null)return c}try{return await Do(l,t,{caption:s,isEmbed:i,fallbackText:a})}catch(c){let u=c instanceof Error?c.message:String(c);console.error(`Failed to convert ${n} block:`,c),t.ctx.reportFailed(`${n.charAt(0).toUpperCase()+n.slice(1)} attachment`,u);let p=s||l.name||a;return`${i?"!":""}[${p}](${l.url})`}}async function mE(r,t){return r.type!=="image"?"":$o(r,t,Lo.image)}function hE(r){return r.includes("youtube.com")||r.includes("youtu.be")}async function gE(r,t){return r.type!=="video"?"":$o(r,t,{...Lo.video,beforeDownload:(e,n)=>e.type==="external"&&hE(e.url)?``:null})}async function bE(r,t){return r.type!=="file"?"":$o(r,t,Lo.file)}async function yE(r,t){return r.type!=="pdf"?"":$o(r,t,Lo.pdf)}function xE(r){return r.includes("youtube.com")||r.includes("youtu.be")||r.includes("twitter.com")||r.includes("x.com")}function wE(r){if(r.type!=="bookmark")return"";let n=r.bookmark.url||"",i=qi(r);return i?`[${i}](${n})`:`[${n}](${n})`}function vE(r){if(r.type!=="embed")return"";let n=r.embed.url||"",i=qi(r);return xE(n)?``:i?`[${i}](${n})`:`[${n}](${n})`}function EE(r){if(r.type!=="link_preview")return"";let n=r.link_preview.url||"";return`[${n}](${n})`}function sr(r,t){return!r||r.length===0?"":r.map(e=>{var a;let n=e.type,i="";return n==="text"?i=e.plain_text||"":n==="mention"?i=_E(e,t):n==="equation"&&(i=`$${(((a=e.equation)==null?void 0:a.expression)||"").trim()}$`),e.annotations&&n!=="equation"&&(e.annotations.bold&&(i=`**${i}**`),e.annotations.italic&&(i=`*${i}*`),e.annotations.code&&(i=`\`${i}\``),e.annotations.strikethrough&&(i=`~~${i}~~`),e.annotations.underline&&(i=`<u>${i}</u>`),e.annotations.color&&e.annotations.color.includes("background")&&(i=`==${i}==`)),e.href&&n!=="mention"&&(i=`[${i}](${e.href})`),i}).join("")}function _E(r,t){var i,a,o;let e=r.mention;if(!e)return r.plain_text||"";switch(e.type){case"database":return t!=null&&t.mentionedIds&&t.mentionedIds.add(e.database.id),Ht("NOTION_DB",e.database.id);case"page":return t!=null&&t.mentionedIds&&t.mentionedIds.add(e.page.id),Ht("NOTION_PAGE",e.page.id);case"date":let l=e.date,s="";return l.start&&(s=l.start,l.end&&(s+=` \u2192 ${l.end}`)),` ${s} `;case"link_mention":let c=((i=e.link_mention)==null?void 0:i.href)||"";return`[${((a=e.link_mention)==null?void 0:a.title)||r.plain_text||c}](${c})`;case"user":let p=e.user;if(p){let g=p.name||r.plain_text||"";return p.type==="person"&&((o=p.person)!=null&&o.email)?` [${g}](mailto:${p.person.email}) `:` ${g} `}return` ${r.plain_text||""} `;default:return` ${r.plain_text||""} `}}var Wt=require("obsidian");var it={CHECKBOX:"checkbox",DATE:"date",DATETIME:"datetime",MULTITEXT:"multitext",NUMBER:"number",TEXT:"text"};async function TE(r,t){var i;if(r.type!=="child_database")return"";let e=r.id,n="Untitled Database";try{let a=await Bo(e,t);n=a.sanitizedTitle;let o=t.vault.getAbstractFileByPath((0,Wt.normalizePath)(a.baseFilePath));if(o&&o instanceof Wt.TFile){let l=t.currentFilePath||t.currentPageFolderPath;return`!${t.app.fileManager.generateMarkdownLink(o,l)}`}else return`![[${a.sanitizedTitle}.base]]`}catch(a){let o=a instanceof Error?a.message:String(a);return o.includes("Linked database")||o.includes("not supported by Notion API")?(console.log(`Skipping linked database (block ID: ${e})`),"<!-- Linked database (not supported by Notion API) -->"):(o.includes("Could not find database with ID")||o.includes("APIResponseError"))&&((i=r.child_database)==null?void 0:i.title)==="Untitled"&&!r.has_children?(console.log(`Skipping linked database view (block ID: ${e}) - this is a reference to an existing database`),"<!-- Linked database view (skipped - references an existing database) -->"):(console.error(`Failed to convert database "${n}":`,a),t.ctx.reportFailed(`Database: ${n}`,o),`<!-- Failed to import database: ${o} -->`)}}async function AE(r,t,e){var a;let n=[],i;do{let o=await Tt(()=>r.dataSources.query({data_source_id:t,star
|
||
|
|
|
||
|
|
${(0,Wt.stringifyYaml)(c)}`}function PE(r,t="hybrid"){let e={},n=null;for(let[o,l]of Object.entries(r)){let s=l.type,c=l.name||o;switch(s){case"title":n=c;break;case"formula":let u=So(l.formula);if(t==="static")e[o]={displayName:c};else if(t==="hybrid")if(u&&Bi(u)){let f=gg(u,r);f&&(e[`formula.${o}`]={displayName:c,formula:f})}else console.warn(`\u26A0\uFE0F Formula "${c}" cannot be converted to Obsidian syntax, falling back to text property.`),console.warn(` Original: ${u}`),console.warn(" Reason: Contains unsupported functions (e.g., substring, slice, split, format, etc.)"),e[o]={displayName:c};break;case"relation":e[o]={displayName:c,isRelation:!0,relationConfig:l.relation};break;case"rollup":let p=DE(l.rollup);p?e[`formula.${o}`]={displayName:c,formula:p}:console.warn(`Failed to convert rollup property "${c}" to formula.`);break;case"button":break;default:e[o]={displayName:c}}}let i=[],a=[];for(let[o,l]of Object.entries(e))l.formula?i.push({key:o,config:l}):a.push({key:o,config:l});return{formulas:i,regularProperties:a,titlePropertyName:n}}function SE(r,t){let e={};for(let[n,i]of Object.entries(r)){let a=i.type,o=i.name||n;switch(a){case"checkbox":e[o]=it.CHECKBOX;break;case"date":let l=!1,s=!1;for(let c of t){let u=c.properties;if(u&&u[n]){let p=u[n];if(p.type==="date"&&p.date){if(p.date.end){l=!0;break}p.date.start&&p.date.start.includes("T")&&(s=!0)}}}l?e[o]=it.TEXT:e[o]=s?it.DATETIME:it.DATE;break;case"number":e[o]=it.NUMBER;break;case"select":case"status":e[o]=it.TEXT;break;case"multi_select":e[o]=it.MULTITEXT;break;case"title":break;case"rich_text":case"url":case"email":case"phone_number":e[o]=it.TEXT;break;case"formula":break;case"relation":e[o]=it.MULTITEXT;break;case"rollup":break;case"people":e[o]=it.MULTITEXT;break;case"files":e[o]=it.MULTITEXT;break;case"created_time":case"last_edited_time":e[o]=it.DATETIME;break;case"created_by":case"last_edited_by":e[o]=it.TEXT;break;case"button":break;case"place":e[o]=it.MULTITEXT;break;default:console.log(`Unsupported property type: ${a}, treating as text`),e[o]=it.TEXT}}return e}function DE(r){if(!r)return null;let t=r.relation_property_name||r.relation_property_key,e=r.rollup_property_name||r.rollup_property_key,n=r.function;if(!t||!n)return null;let i=t;switch(n){case"show_original":if(e){let a=e;return`note["${i}"].map(value.asFile().properties["${a}"])`}return`note["${i}"]`;case"show_unique":if(e){let a=e;return`note["${i}"].map(value.asFile().properties["${a}"]).flat().unique()`}return`note["${i}"].unique()`;case"count":return`note["${i}"].length`;case"count_values":if(e){let a=e;return`note["${i}"].map(value.asFile().properties["${a}"]).flat().length`}return`note["${i}"].length`;case"unique":if(e){let a=e;return`note["${i}"].map(value.asFile().properties["${a}"]).flat().unique().length`}return`note["${i}"].unique().length`;case"empty":if(e){let a=e;return`note["${i}"].filter(value.asFile().properties["${a}"] == null || value.asFile().properties["${a}"] == "" || (typeof value.asFile().properties["${a}"] == "object" && value.asFile().properties["${a}"].length == 0)).length`}return`if(note["${i}"].length == 0, 1, 0)`;case"not_empty":if(e){let a=e;return`note["${i}"].filter(value.asFile().properties["${a}"] != null && value.asFile().properties["${a}"] != "" && !(typeof value.asFile().properties["${a}"] == "object" && value.asFile().properties["${a}"].length == 0)).length`}return`if(note["${i}"].length > 0, 1, 0)`;case"percent_empty":if(e){let a=e,o=`note["${i}"].length`,l=`note["${i}"].filter(value.asFile().properties["${a}"] == null || value.asFile().properties["${a}"] == "" || (typeof value.asFile().properties["${a}"] == "object" && value.asFile().properties["${a}"].length == 0)).length`;return`if(${o} == 0, 0, (${l} / ${o}) * 100)`}return`if(note["${i}"].length == 0, 100, 0)`;case"percent_not_empty":if(e){let a=e,o=`note["${i}"].length`,l=`note["${i}"].filter(value.asFile().properties["${a}"] != null && value.asFile().properties["${a}"] != "" && !(typeof value.asFile().properties["${a}"] == "object" && value.asFile().properties["${a}"].length == 0)).length`
|
||
|
|
`),P=null,k=new Map;for(let O of T){let w=O.match(/^([a-zA-Z0-9_-]+):\s*$/);if(w){P=w[1];continue}if(P){let C=O.match(h);if(C)for(let y of C)O.includes(`[[${y}`)||(k.has(P)||k.set(P,[]),k.get(P).push(y))}}for(let[O,w]of k.entries())w.length>0&&this.relationPlaceholders.push({pageId:n,propertyKey:O,relatedPageIds:w,targetDatabaseId:""});k.size>0&&console.log(`[Incremental Import] Collected ${k.size} unresolved relation(s) from skipped file: ${n}`)}}let l=/\[\[NOTION_PAGE:([a-f0-9-]+)\]\]/g,s=/\[\[NOTION_DB:([a-f0-9-]+)\]\]/g,c=new Set,u;for(;(u=l.exec(e))!==null;)c.add(u[1]);for(;(u=s.exec(e))!==null;)c.add(u[1]);c.size>0&&(this.mentionPlaceholders.set(i,c),console.log(`[Incremental Import] Collected ${c.size} unresolved mention(s) from skipped file: ${i}`));let p=/\[\[SYNCED_CHILD_PAGE:([a-f0-9-]+)\]\]/g,f=/\[\[SYNCED_CHILD_DATABASE:([a-f0-9-]+)\]\]/g,d=new Set,g=new Set;for(;(u=p.exec(e))!==null;)d.add(u[1]);for(;(u=f.exec(e))!==null;)g.add(u[1]);d.size>0&&(this.syncedChildPagePlaceholders.set(i,d),console.log(`[Incremental Import] Collected ${d.size} unresolved synced child page(s) from skipped file: ${i}`)),g.size>0&&(this.syncedChildDatabasePlaceholders.set(i,g),console.log(`[Incremental Import] Collected ${g.size} unresolved synced child database(s) from skipped file: ${i}`))}async getUniqueFilePathWithIncrementalCheck(e,n,i,a){let o=e?`${e}/${n}`:n;return await this.shouldSkipExistingFile(o,i,a)?null:this.vault.getAbstractFileByPath((0,ne.normalizePath)(o))?un(this.vault,e,n):o}async cleanupNotionIds(e){if(this.notionIdToPath.size===0)return;let n=0,i=0;for(let a of this.notionIdToPath.values()){if(e.isCancelled())break;try{let o=this.vault.getAbstractFileByPath(a+".md");if(!o||!(o instanceof ne.TFile))continue;let l=await this.vault.read(o),s=/^---\n([\s\S]*?)\n---/,c=l.match(s);if(!c)continue;let u=c[1];if(!/^notion-id:\s*.+$/m.test(u))continue;let f=u.split(`
|
||
|
|
`).filter(g=>!g.match(/^notion-id:\s*.+$/)).join(`
|
||
|
|
`),d=l.replace(s,`---
|
||
|
|
${f}
|
||
|
|
---`);await ji(this.vault,o,d),n++}catch(o){console.error(`Failed to clean notion-id from file: ${a}`,o),i++}}n>0&&console.log(`\u2713 Cleaned notion-id from ${n} file(s)`),i>0&&console.warn(`\u26A0\uFE0F Failed to clean notion-id from ${i} file(s)`)}};function ji(r,t,e){return r.modify(t,e,{mtime:t.stat.mtime,ctime:t.stat.ctime})}var Ue=require("obsidian");function Ui(r){return r instanceof HTMLElement?r.style.fontFamily.includes("Consolas"):!1}function bc(r){return r!=null&&r instanceof HTMLParagraphElement&&Array.from(r.childNodes).every(t=>Ui(t)||Hi(t))}function yc(r){var t;return Ui(r)&&r.nodeName==="SPAN"&&xc(r).length===0&&Array.from(r.childNodes).every(e=>e.nodeType===Node.TEXT_NODE)&&!((t=r.textContent)!=null&&t.trim().includes(`
|
||
|
|
`))}function kg(r){return Ui(r)&&!yc(r)}function Hi(r){return r instanceof HTMLBRElement}function xc(r){let t=[],e=r.nextSibling;for(;Ui(e)||Hi(e);)t.push(e),e=e.nextSibling;let n=t.findLastIndex(Ui);return n===-1?[]:(t.length=n+1,t)}var OE="http://www.w3.org/2003/InkML";var Ng={color:"#000000",width:70,height:70,transparency:0};function IE(r){let t=r.match(/<\/(?:inkml:)?ink>/);return t&&t.index!==void 0?r.substring(0,t.index+t[0].length):r}function wc(r,t){let e=Array.from(r.getElementsByTagNameNS(OE,t));return e.length===0&&(e=Array.from(r.getElementsByTagName(t))),e}function FE(r){let t=new Map,e=wc(r,"brush");for(let n of e){let i=n.getAttributeNS("http://www.w3.org/XML/1998/namespace","id")||n.getAttribute("xml:id")||n.getAttribute("id");if(!i)continue;let a={...Ng},o=wc(n,"brushProperty");for(let l of o){let s=l.getAttribute("name"),c=l.getAttribute("value");if(!(!s||c===null))switch(s){case"color":a.color=c;break;case"width":a.width=parseFloat(c);break;case"height":a.height=parseFloat(c);break;case"transparency":a.transparency=parseFloat(c);break}}t.set(i,a)}return t}function LE(r){let t=IE(r),n=new DOMParser().parseFromString(t,"text/xml"),i=n.querySelector("parsererror");if(i)throw new Error(`Failed to parse InkML: ${i.textContent}`);let a=FE(n),o=wc(n,"trace"),l=[];for(let s of o){let c=s.getAttributeNS("http://www.w3.org/XML/1998/namespace","id")||s.getAttribute("xml:id")||s.getAttribute("id")||"0",u=s.getAttribute("brushRef")||"";u.startsWith("#")&&(u=u.substring(1));let p=a.get(u)||Ng,d=(s.textContent||"").replace(/\n/g,"").split(",").map(g=>g.trim().split(" ").filter(m=>m.length>0).map(m=>{let h=parseFloat(m);return Number.isInteger(h)?Math.round(h):Math.round(h*1e4)})).filter(g=>g.length>=2);l.push({id:c,coords:d,brush:p})}return l}function ME(r){let t=1/0,e=1/0,n=-1/0,i=-1/0;for(let a of r)for(let o of a.coords)o.length>=2&&(t=Math.min(t,o[0]),e=Math.min(e,o[1]),n=Math.max(n,o[0]),i=Math.max(i,o[1]));return{minX:t,minY:e,maxX:n,maxY:i}}function Pg(r){if(!r||r.trim().length===0)return null;let t=LE(r);if(t.length===0)return null;let{minX:e,minY:n,maxX:i,maxY:a}=ME(t),o=i-e+10*2,l=a-n+10*2,s=[];for(let c of t){if(c.coords.length===0)continue;let u=c.brush.color,p=c.brush.width,f=1-c.brush.transparency,d=f<1?` opacity="${f.toFixed(2)}"`:"";if(c.coords.length===1){let g=c.coords[0][0]-e+10,m=c.coords[0][1]-n+10;s.push(`<circle cx="${g}" cy="${m}" r="${p/2}" fill="${u}"${d}/>`)}else{let g=c.coords.map((m,h)=>{let b=m[0]-e+10,T=m[1]-n+10;return h===0?`M ${b} ${T}`:`L ${b} ${T}`}).join(" ");s.push(`<path d="${g}" stroke="${u}" stroke-width="${p}" fill="none" stroke-linecap="round" stroke-linejoin="round"${d}/>`)}}return`<svg xmlns="http://www.w3.org/2000/svg" width="${o}" height="${l}" viewBox="0 0 ${o} ${l}">${s.join(`
|
||
|
|
`)}</svg>`}var Ig=Yn(Sg()),Ec="onenote-importer-refresh-token",Dg="66553851-08fa-44f2-8bb1-1436f121a73d",Rg=["user.read","notes.read"],$E=/<(object|iframe)([^>]*)\/>/g,Og=/(<\/p>)\s*(<p[^>]*>)|\n \n/g,BE=5,qE=new RegExp(/^data:[\w\d]+\/[\w\d]+;base64,/);function jE(r){throw new Error("Didn't expect to get here")}function UE(r){if(r==null)throw new Error("response is nullish");if(typeof r!="object")throw new Error("response is not an object type");if("@odata.nextLink"in r){let t=r["@odata.nextLink"];if(typeof t!="string")throw new Error(`Link of unknown type: ${typeof t}`)}if(!("value"in r))throw new Error("Expected response to have a 'value' property");if(!Array.isArray(r.value))throw new Error("Expected response to have an error in 'value' property")}function HE(r){return r instanceof HTMLElement}var jo=class extends Ee{constructor(){super(...arguments);this.importPreviouslyImported=!1;this.importIncompatibleAttachments=!1;this.selectedIds=[];this.notebooks=[];this.graphData={state:Tn(32),accessToken:""};this.attachmentDownloadPauseCounter=0;this.rememberMe=!1;this.lastSuccessfulFetchTime=performance.now()}async init(){this.addOutputLocationSetting("OneNote"),new Ue.Setting(this.modal.contentEl).setName("Import incompatible attachments").setDesc("Imports incompatible attachments which cannot be embedded in Obsidian, such as .exe files.").addToggle(i=>i.setValue(!1).onChange(a=>this.importIncompatibleAttachments=a)),new Ue.Setting(this.modal.contentEl).setName("Skip previously imported").setDesc("If enabled, notes imported previously by this plugin will be skipped.").addToggle(i=>i.setValue(!0).onChange(a=>this.importPreviouslyImported=!a));let e=!1;if(this.retrieveRefreshToken())try{await this.updateAccessToken(),e=!0}catch(i){}this.microsoftAccountSetting=new Ue.Setting(this.modal.contentEl).setName("Sign in with your Microsoft account").setDesc("You need to sign in to import your OneNote data.").addButton(i=>i.setCta().setButtonText("Sign in").onClick(()=>{this.registerAuthCallback(this.authenticateUser.bind(this));let a=new URLSearchParams({client_id:Dg,scope:"offline_access "+Rg.join(" "),response_type:"code",redirect_uri:Uo,response_mode:"query",state:this.graphData.state});window.open(`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${a.toString()}`)})),this.microsoftAccountSetting.settingEl.toggle(!e);let n=new Ue.Setting(this.modal.contentEl).setName("Remember me").setDesc("If checked, you will be automatically logged in for subsequent imports.").addToggle(i=>{i.onChange(a=>{this.rememberMe=a,a&&this.refreshToken?this.storeRefreshToken(this.refreshToken):this.clearStoredRefreshToken()})});n.settingEl.toggle(!e),this.switchUserSetting=new Ue.Setting(this.modal.contentEl).addButton(i=>i.setCta().setButtonText("Switch user").onClick(()=>{this.microsoftAccountSetting.settingEl.show(),n.settingEl.show(),this.clearStoredRefreshToken(),this.switchUserSetting.settingEl.hide(),this.contentArea.empty()})),this.loadingArea=this.modal.contentEl.createDiv({text:"Loading notebooks..."}),this.loadingArea.hide(),this.contentArea=this.modal.contentEl.createDiv(),this.contentArea.hide(),e?(await this.setSwitchUser(),await this.showSectionPickerUI()):this.switchUserSetting.settingEl.hide()}async authenticateUser(e){try{if(e.state!==this.graphData.state)throw new Error(`An incorrect state was returned.
|
||
|
|
Expected state: ${this.graphData.state}
|
||
|
|
Returned state: ${e.state}`);await this.updateAccessToken(e.code),await this.setSwitchUser(),await this.showSectionPickerUI()}catch(n){console.error("An error occurred while we were trying to sign you in. Error details: ",n),this.modal.contentEl.createEl("div",{text:"An error occurred while trying to sign you in."}).createEl("details",{text:String(n)}).createEl("summary",{text:"Click here to show error details"})}}async setSwitchUser(){let e=await this.fetchResource("https://graph.microsoft.com/v1.0/me","json");this.switchUserSetting.setDesc(`Signed in as ${e.displayName} (${e.mail}). If that's not the correct account, sign in again.`),this.switchUserSetting.settingEl.show(),this.microsoftAccountSetting.settingEl.hide()}async updateAccessToken(e){let n=new URLSearchParams({client_id:Dg,scope:"offline_access "+Rg.join(" "),redirect_uri:Uo});if(e)n.set("code",e),n.set("grant_type","authorization_code");else{let a=this.retrieveRefreshToken();if(!a)throw new Error("Missing token required for authentication. Please try logging in again.");n.set("refresh_token",a),n.set("grant_type","refresh_token")}let i=await(0,Ue.requestUrl)({method:"POST",url:"https://login.microsoftonline.com/common/oauth2/v2.0/token",contentType:"application/x-www-form-urlencoded",body:n.toString()}).json;if(!i.access_token)throw new Error(`Unexpected data was returned instead of an access token. Error details: ${i}`);i.refresh_token&&this.storeRefreshToken(i.refresh_token),this.graphData.accessToken=i.access_token}storeRefreshToken(e){this.refreshToken=e,this.rememberMe&&localStorage.setItem(Ec,e)}retrieveRefreshToken(){return this.refreshToken?this.refreshToken:localStorage.getItem(Ec)}clearStoredRefreshToken(){localStorage.removeItem(Ec)}async showSectionPickerUI(){var a,o;this.loadingArea.show(),this.selectedIds=[];let e="https://graph.microsoft.com/v1.0/me/onenote/notebooks",n=new URLSearchParams({$expand:"sections($select=id,displayName),sectionGroups($expand=sections,sectionGroups)",$select:"id,displayName,lastModifiedDateTime",$orderby:"lastModifiedDateTime DESC"}),i=`${e}?${n.toString()}`;try{this.notebooks=(await this.fetchResource(i,"json-wrapped")).value,this.contentArea.empty(),this.contentArea.createEl("h4",{text:"Choose data to import"});for(let l of this.notebooks){if(((a=l.sectionGroups)==null?void 0:a.length)!==0)for(let c of l.sectionGroups)await this.fetchNestedSectionGroups(c);let s=this.contentArea.createDiv();new Ue.Setting(s).setName(l.displayName).setDesc(`Last edited on: ${Ue.moment.utc(l.lastModifiedDateTime).format("Do MMMM YYYY")}. Contains ${(o=l.sections)==null?void 0:o.length} sections.`).addButton(c=>c.setCta().setButtonText("Select all").onClick(()=>{s.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach(u=>u.click())})),this.renderHierarchy(l,s)}}catch(l){console.error("An error occurred while fetching your OneNote data: ",l),this.showContentAreaErrorMessage()}this.loadingArea.hide(),this.contentArea.show()}async fetchNestedSectionGroups(e){if(e.sectionGroups=(await this.fetchResource(e.sectionGroupsUrl+"?$expand=sectionGroups($expand=sections),sections","json-wrapped")).value,e.sectionGroups)for(let n=0;n<e.sectionGroups.length;n++)await this.fetchNestedSectionGroups(e.sectionGroups[n])}renderHierarchy(e,n){if(e.sectionGroups)for(let i of e.sectionGroups){let a=n.createDiv({attr:{style:"padding-inline-start: 1em; padding-top: 8px"}});a.createEl("strong",{text:i.displayName}),this.renderHierarchy(i,a)}if(e.sections){let i=n.createEl("ul",{attr:{style:"padding-inline-start: 1em;"}});for(let a of e.sections){let l=i.createEl("li",{cls:"task-list-item"}).createEl("label"),s=l.createEl("input");s.type="checkbox",l.appendChild(document.createTextNode(a.displayName)),l.createEl("br"),s.addEventListener("change",()=>{if(s.checked)this.selectedIds.push(a.id);else{let c=this.selectedIds.findIndex(u=>u===a.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 aga
|
||
|
|
|
||
|
|
![[${k}]]
|
||
|
|
`,e.reportAttachmentSuccess(k)}}catch(P){console.error("Failed to convert InkML to SVG in page:",i.title,P)}let f=this.convertTags(At(l.html)),d=await this.getAllAttachments(e,f.replace(Og,"<br />"));this.combineCodeBlocksAsNecessary(d),this.styledElementToHTML(d),this.convertInternalLinks(d),this.convertMathML(d),this.removeExtraListItemParagraphs(d),this.escapeTextNodes(d);let g=(0,Ue.htmlToMarkdown)(d).trim().replace(Og," ");p&&(g+=p);let m=await this.saveAsMarkdownFile(u,i.title,g),h=i!=null&&i.lastModifiedDateTime?Date.parse(i.lastModifiedDateTime):null,b=i!=null&&i.createdDateTime?Date.parse(i.createdDateTime):null,T={ctime:(a=b!=null?b:h)!=null?a:Date.now(),mtime:(o=h!=null?h:b)!=null?o:Date.now()};await this.vault.append(m,"",T),e.reportNoteSuccess(i.title)}catch(l){e.reportFailed(i.title,l)}}convertMathML(e){var i,a;let n=Array.from(e.querySelectorAll("math"));for(let o of n)try{let l=o.outerHTML,c=`$${Ig.MathMLToLaTeX.convert(l)}$`,u=document.createTextNode(c);(i=o.parentNode)==null||i.replaceChild(u,o)}catch(l){console.warn("Failed to convert MathML to LaTeX:",l);let s=document.createTextNode("[Math equation - conversion failed]");(a=o.parentNode)==null||a.replaceChild(s,o)}}isLatexMath(e){let n=e.trim();return n.startsWith("$")&&n.endsWith("$")||n.startsWith("$$")&&n.endsWith("$$")}escapeTextNodes(e){if(e.nodeType===Node.TEXT_NODE&&e.textContent){if(this.isLatexMath(e.textContent))return;e.textContent=e.textContent.replace(/([<>])/g,"\\$1")}else for(let n=0;n<e.childNodes.length;n++)this.escapeTextNodes(e.childNodes[n])}convertFormat(e){let n={html:"",inkml:""},i=e.split(`
|
||
|
|
`,1)[0];e.slice(0,-2);let a=e.split(i);if(a.shift(),a.length===2)for(let o of a){let s=o.split(`
|
||
|
|
`).find(u=>u.includes("Content-Type")).split(";")[0].split(":")[1].trim(),c=o.split(`
|
||
|
|
`).slice(2).join(`
|
||
|
|
`).trim();s==="text/html"?n.html=c:s==="application/inkml+xml"&&(n.inkml=c)}else throw new Error("The input string is incorrect and may be missing data. Inputted string: "+e);return n}convertTags(e){var i,a;let n=Array.from(e.querySelectorAll("[data-tag]"));for(let o of n)if((i=o.getAttribute("data-tag"))!=null&&i.contains("to-do")){let s=o.getAttribute("data-tag")==="to-do:completed"?"[x]":"[ ]";o.prepend(`- ${s} `)}else{let l=(a=o.getAttribute("data-tag"))==null?void 0:a.split(",");l==null||l.forEach(s=>{o.append(` #${s.replace(":","-")} `)})}return e.outerHTML}convertInternalLinks(e){let n=e.findAll("a");for(let i of n)if(i.href.startsWith("onenote:")){let a=i.href.indexOf("#")+1,o=i.href.indexOf("&",a);i.href=i.href.slice(a,o)}}getEntityPathNoParent(e,n){for(let i of this.notebooks){let a=this.getEntityPath(e,`${n}/${i.displayName}`,i);if(a)return a}return null}getEntityPath(e,n,i){let a=null;if("sectionGroups"in i&&i.sectionGroups){let o=this.searchSectionGroups(e,n,i.sectionGroups);o!==null&&(a=o)}if("sections"in i&&i.sections){let o=this.searchSectionGroups(e,n,i.sections);o!==null&&(a=o)}if("pages"in i&&i.pages){let o=this.searchPages(e,n,i);o!==null&&(a=o)}return a&&(a=this.sanitizeFilePath(a)),a}searchPages(e,n,i){var o;let a=null;for(let l=0;l<i.pages.length;l++){let s=i.pages[l],c=(o=s.contentUrl.split("page-id=")[1])==null?void 0:o.split("}")[0];if(s.id===e||c===e){if(s.level===0)i.pages[l+1]&&i.pages[l+1].level!==0?a=`${n}/${s.title}`:a=n;else{a=n;for(let u=i.pages.indexOf(s)-1;u>=0;u--)if(i.pages[u].level===s.level-1){a+="/"+i.pages[u].title;break}}break}}return a}searchSectionGroups(e,n,i){let a=null;for(let o of i)if(o.id===e)a=`${n}/${o.displayName}`;else{let l=this.getEntityPath(e,`${n}/${o.displayName}`,o);if(l){a=l;break}}return a}sanitizeOCRText(e){return e=e.replace(/[^\w\d\s.,!?]/g,""),e=e.replace(/\s+/g," ").trim(),e.length>50&&(e=e.substring(0,50)+"..."),e}async getAllAttachments(e,n){var s,c,u,p;let i=At(n.replace($E,"<$1$2></$1>")),a=i.findAll("object"),o=i.findAll("img"),l=i.findAll("iframe");for(let f of a){for(;f.firstChild;)(s=f.parentNode)==null||s.insertBefore(f.firstChild,f.nextSibling);let d=f.getAttribute("data-attachment").split("."),g=d[d.length-1];if(!(!qn.contains(g)&&!this.importIncompatibleAttachments)){let m=f.getAttribute("data-attachment"),h=f.getAttribute("data"),b=await this.fetchAttachment(e,m,h),T=document.createElement("p");T.innerText=`![[${b}]]`,(c=f.parentNode)==null||c.replaceChild(T,f)}}for(let f=0;f<o.length;f++){let d=o[f],m=d.getAttribute("data-fullres-src-type").split("/")[1],b=`Exported image ${(0,Ue.moment)().format("YYYYMMDDHHmmss")}-${f}.${m}`,T=d.getAttribute("data-fullres-src"),P=await this.fetchAttachment(e,b,T);P&&(d.src=encodeURI(P),!d.alt||qE.test(d.alt)?d.alt="Exported image":d.alt=this.sanitizeOCRText(d.alt)||"Exported image")}for(let f of l)if(f.src.contains("youtube.com")||f.src.contains("youtu.be")){let d=document.createTextNode(``);(u=f.parentNode)==null||u.replaceChild(d,f)}else{let d=document.createElement("a");d.href=f.src,(p=f.parentNode)==null||p.replaceChild(d,f)}return i}async fetchAttachment(e,n,i){this.attachmentDownloadPauseCounter===7&&await new Promise(a=>{e.status("Pausing attachment download to avoid rate limiting."),this.attachmentDownloadPauseCounter=0,setTimeout(a,3e3)}),this.attachmentDownloadPauseCounter++,e.status("Downloading attachment "+n);try{let a=await this.getAvailablePathForAttachment(n,[]),o=await this.fetchResource(i,"file",e);return await this.app.vault.createBinary(a,o),e.reportAttachmentSuccess(n),a}catch(a){e.reportFailed(n),console.error(a)}}combineCodeBlocksAsNecessary(e){let n=e.querySelectorAll("p:has(+ br + p)");Array.from(n).reverse().forEach(i=>{let a=i,o=i.nextElementSibling;if(!Hi(o))throw new Error(`Expected a <br> element after the paragraph, but found: ${o==null?void 0:o.nodeName}`);let l=o.nextElementSibling;bc(a)&&bc(l)&&(a.appendChild(o),a.appendChild(o.cloneNode()),a.append(...Array.from(l.childNodes)),l.remove())})}styledElementToHTML(e){let n={"font-weight:bol
|
||
|
|
`):l.append(...Array.from(s.childNodes)),s.remove()}),l.append("\n```"),o.replaceWith(l)}else if(o.nodeName==="TD"){o.removeAttribute("style");return}else{let l=o.getAttribute("style")||"",s=Object.keys(n).find(c=>l.includes(c));if(s){let c=n[s],u=document.createElement(c);u.append(...Array.from(o.childNodes)),o.replaceWith(u)}}})}removeExtraListItemParagraphs(e){e.querySelectorAll("li > p:first-child").forEach(n=>{HE(n)&&n.style.marginBottom==="0pt"&&n.style.marginTop==="0pt"&&n.replaceWith(...Array.from(n.childNodes))})}async fetchResource(e,n,i,a=0){var s;if(a>=BE)throw new Error("Exceeded maximum retry attempts");let o=performance.now()-this.lastSuccessfulFetchTime,l=1e3*60*90;if(o>l&&this.modal.abortController.abort("stalled for >90 minutes"),this.modal.abortController.signal.aborted){let c=(s=this.modal.abortController.signal.reason)!=null?s:"no reason given";throw new Error(`The import was aborted (${c})`)}try{a>0&&console.log(`Retry attempt #${a} for ${e}`);let c=await fetch(e,{headers:{Authorization:`Bearer ${this.graphData.accessToken}`},signal:this.modal.abortController.signal});if(c.ok){let u;switch(n){case"text":u=await c.text();break;case"file":u=await c.arrayBuffer();break;case"json":u=await c.json();break;case"json-wrapped":u=await c.json(),UE(u),"@odata.nextLink"in u&&u.value.push(...(await this.fetchResource(u["@odata.nextLink"],"json-wrapped",i)).value);break;default:jE(n)}return this.lastSuccessfulFetchTime=performance.now(),u}else{let u=null,p=await c.json();if(p.hasOwnProperty("error")&&(u=p.error),console.log("An error has occurred while fetching an resource:",u||p),(u==null?void 0:u.code)==="40001"||(u==null?void 0:u.code)==="InvalidAuthenticationToken"||c.status===401)return await this.updateAccessToken(),this.fetchResource(e,n,i,a+1);if((u==null?void 0:u.code)==="20166"||c.status===429){let d=c.headers.get("Retry-After"),g=d?+d*1:60;return console.log(`Rate limit exceeded, waiting for: ${g} seconds`),await this.pause(g,"OneNote API is rate-limiting us",i),this.fetchResource(e,n,i,a)}return this.fetchResource(e,n,i,a+1)}}catch(c){return console.error(`An internal error occurred while trying to fetch '${e}'. Error details: `,c),this.fetchResource(e,n,i,a+1)}}};var Or=require("obsidian");var Fg=require("obsidian"),WE=/[\?<>\\:\*\|"]/g,VE=/[\x00-\x1f\x80-\x9f]/g,zE=/^\.+$/,GE=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,YE=/[\. ]+$/,ZE=/^\./,KE=/\[/g,XE=/\]/g;function Ho(r){return r.replace(WE,"").replace(VE,"").replace(zE,"").replace(YE,"").replace(GE,"").replace(KE,"").replace(XE,"").replace(ZE,"")}function Wo(r,t){let e="MMMM Do, YYYY",n=(0,Fg.moment)(r,e);return n.format(e)!==r?r:n.isValid()?n.format(t):r}var _c=/\(\(\b(.*?)\b\)\)/g;function Lg(r){return Array.from(r.matchAll(_c),t=>t[1])}var Vo=require("obsidian"),JE=["POMO","word-count","date","slider","encrypt","TaoOfRoam","orphans","count","character-count","comment-button","query","streak","attr-table","mentions","search","roam/render","calc"],QE=new RegExp(`\\{\\{(\\[\\[)?(${JE.join("|")})(\\]\\])?.*?\\}\\}(\\})?`,"g"),e1=/{{pdf:|{{\[\[pdf|{{\[\[audio|{{audio:|{{video:|{{\[\[video/,Mg=/https:\/\/firebasestorage(.*?)\?alt(.*?)\)/,t1=/https:\/\/firebasestorage(.*?)\?alt(.*?)/,zo=class extends Ee{constructor(){super(...arguments);this.downloadAttachments=!1;this.fileDateYAML=!1;this.titleYAML=!1;this.newestTimestamp=0;this.oldestTimestamp=0}init(){this.addFileChooserSetting("Roam (.json)",["json"]),this.addOutputLocationSetting("Roam"),this.userDNPFormat=this.getUserDNPFormat(),new Or.Setting(this.modal.contentEl).setName("Import settings").setHeading(),new Or.Setting(this.modal.contentEl).setName("Download all attachments").setDesc("If enabled, all attachments uploaded to Roam will be downloaded to your attachments folder.").addToggle(e=>{e.setValue(this.downloadAttachments),e.onChange(async n=>{this.downloadAttachments=n})}),new Or.Setting(this.modal.contentEl).setName("Add YAML created/update date").setDesc("If enabled, notes will have the create-time and edit-time from Roam added as properties.").addToggle(e=>{e.setValue(this.fileDate
|
||
|
|
`),C=w.findIndex(y=>y.contains("* "+T));C!==-1&&(w[C]=w[C].replace(T,P)),d.set(k,w.join(`
|
||
|
|
`))}}let{vault:g}=this,m=d.size,h=1;for(let[b,T]of d.entries()){if(e.isCancelled())return;try{let{parent:P}=le(b);await this.createFolders(P);let k=g.getAbstractFileByPath(b);k?await g.modify(k,T):await g.create(b,T),e.reportNoteSuccess(b),e.reportProgress(h,m)}catch(P){console.error("Error saving Markdown to file:",b,P),e.reportFailed(b)}h++}}}getUserDNPFormat(){let e=this.app.internalPlugins.getPluginById("daily-notes").instance;return e?e.options.format||"YYYY-MM-DD":(console.log('Daily note plugin is not enabled. Roam import defaulting to "YYYY-MM-DD" format.'),"YYYY-MM-DD")}preprocess(e){let n=new Map,i=new Map,a=this.userDNPFormat;function o(l,s){if(s.uid){let c=new Date(l.uid);if(!isNaN(c.getTime())){let f=Wo(l.title,a);l.title=f}let u={pageName:Ho(l.title),blockString:s.string};/.*?(\(\(.*?\)\)).*?/g.test(s.string)&&i.set(s.uid,u),n.set(s.uid,u)}if(s.children)for(let c of s.children)o(l,c)}for(let l of e)if(l.children)for(let s of l.children)o(l,s);return[n,i]}async roamMarkupScrubber(e,n,i,a=!1){return i=i.replace(QE,""),i.substring(0,8)==":hiccup "&&i.includes(":hr")?"---":(i=i.replace(/\[\[(.*?)\]\]/g,(o,l)=>`[[${Wo(Ho(l),this.userDNPFormat)}]]`),i=i.replace(/\[\[(.*\/.*)\]\]/g,(o,l)=>`[[${e}/${l}|${l}]]`),i=i.replace(/\[.+?\]\((\(.+?\)\))\)/g,"$1"),i=i.replace(/\[(.+?)\]\(\[\[(.+?)\]\]\)/g,"[[$2|$1]]"),i=i.replace(/\[\[>\]\]/g,">"),i=i.replace(/{{TODO}}|{{\[\[TODO\]\]}}/g,"[ ]"),i=i.replace(/{{DONE}}|{{\[\[DONE\]\]}}/g,"[x]"),i=i.replace("::",":"),i=i.replace(/{{.*?\bvideo\b.*?(\bhttp.*?\byoutu.*?)}}/g,""),i=i.replace(/(https?:\/\/twitter\.com\/(?:#!\/)?\w+\/status\/\d+(?:\?[\w=&-]+)?)/g,""),i=i.replace(/\_\_(.+?)\_\_/g,"*$1*"),i=i.replace(/\^\^(.+?)\^\^/g,"==$1=="),i=i.replace(/{{\[{0,2}embed.*?(\(\(.*?\)\)).*?}}/g,"$1"),i=i.replace(/{{\[{0,2}embed.*?(\[\[.*?\]\]).*?}}/g,"$1"),this.downloadAttachments&&!a&&i.includes("firebasestorage")&&(i=await this.downloadFirebaseFile(i,n)),i)}async jsonToMarkdown(e,n,i,a="",o=!1,l,s,c){let u=[],p=[],f=i["edit-time"],d=i["create-time"];if(this.newestTimestamp<this.oldestTimestamp&&(this.oldestTimestamp=this.newestTimestamp),this.newestTimestamp=!f||c>f?c:f,d!==void 0?s>10?this.oldestTimestamp=Math.min(s,d):this.oldestTimestamp=d:this.oldestTimestamp=s,"string"in i&&i.string){let g=i.heading?"#".repeat(i.heading)+" ":"",m=await this.roamMarkupScrubber(e,n,i.string);u.push(`${o?a+"* ":a}${g}${m}`)}if(i.children)for(let g of i.children)u.push(await this.jsonToMarkdown(e,n,g,a+" ",!0,"",this.oldestTimestamp,this.newestTimestamp));if((this.fileDateYAML||this.titleYAML)&&!o){let g=this.oldestTimestamp;if(p.push("---"),this.titleYAML&&p.push(`title: "${l}"`),this.fileDateYAML){let m="YYYY-MM-DD HH:mm:ss",h=this.newestTimestamp?(0,Vo.moment)(this.newestTimestamp).format(m):(0,Vo.moment)(new Date).format(m),b=g?(0,Vo.moment)(g).format(m):h;p.push("created: "+b),p.push("updated: "+h)}p.push("---"),u.unshift(p.join(`
|
||
|
|
`))}return u.join(`
|
||
|
|
`)}async modifySourceBlockString(e,n,i,a){if(!n.blockString.endsWith("^"+a)){let o=`${i}/${n.pageName}.md`,l=e.get(o);if(l){let s=l.split(`
|
||
|
|
`),c=s.findIndex(u=>u.contains("* "+n.blockString));if(c!==-1){let u=n.blockString+" ^"+a;s[c]=s[c].replace(n.blockString,u),n.blockString=n.blockString+" ^"+a}e.set(o,s.join(`
|
||
|
|
`))}}}async extractAndProcessBlockReferences(e,n,i,a){let o=Lg(a);if(o.length===0)return a;let l=[];for(let u of o)try{let p=n.get(u);if(!p){l.push(u);continue}let f=p.blockString.replace(/\[\[|\]\]/g,""),d=`[[${i}/${p.pageName}#^${u}|${f}]]`;await this.modifySourceBlockString(e,p,i,u),l.push(d)}catch(p){l.push(u)}let s=0;return a.replace(_c,()=>l[s++])}async downloadFirebaseFile(e,n){let{progress:i,vault:a}=this,o="";try{let l,s;if(e1.test(e)?(l=e.match(/https:\/\/firebasestorage(.*?)\?alt(.*?)\}/),s=e.match(/{{.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):Mg.test(e)?(l=e.match(Mg),s=e.match(/!\[.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):(l=e.match(t1),s=e.match(/https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)),l&&s){let c="https://firebasestorage"+l[1],u=decodeURIComponent(c.split("/").last()||"");if(u){let m=u.split("/");m.length>1&&(m.splice(-1,1),this.createFolders(`${n}/${m.join("/")}`))}else{let m=Math.floor(Date.now()/1e3),h=c.slice(-5).match(/(.*?)\.(.+)/);if(!h)return i.reportSkipped(l[1],"Unexpected file extension"),e;u=`${m}.${h[2]}`}let p=`${n}/${u}`;if(a.getAbstractFileByPath(p))return i.reportSkipped(l[1],"File already exists"),e;o=l[0].slice(0,-1);let g=await(await fetch(o,{})).arrayBuffer();return await a.createBinary(p,g),i.reportAttachmentSuccess(o),e.replace(s[0],`![[${p}]]`)}}catch(l){console.error(l),i.reportFailed(o,l)}return e}};var Ir=require("obsidian");var $g=/!\[\]\(assets\/([^)]*)\)/g,Go=class extends Ee{init(){Ir.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."});let t=Ir.Platform.isMacOS?["textbundle","textpack","zip"]:["textpack","zip"];this.addFileChooserSetting("Textbundle",t,!0),this.addOutputLocationSetting("Textbundle")}async import(t){let{files:e}=this;if(e.length===0){new Ir.Notice("Please pick at least one file to import.");return}let n=await this.getOutputFolder();if(!n){new Ir.Notice("Please select a location to export to.");return}this.attachmentsFolderPath=await this.createFolders(`${n.path}/assets`);for(let i of e)if(i.extension==="textpack")await er(i,async(a,o)=>{await this.process(t,i.name,o)});else if(i.extension==="zip")await er(i,async(a,o)=>{let l=this.groupFilesByTextbundle(i.name,o);for(let s of l)await this.process(t,i.name,s)});else{let o=await new zr(`${i.toString()}/`).list();await this.process(t,i.name,o)}}groupFilesByTextbundle(t,e){let n={},i=t+"/",a=".textbundle";for(let o of e){if(!o.fullpath.startsWith(i)){console.log("Skipping",o.fullpath);continue}let l=o.fullpath.slice(i.length);if(l.startsWith("._")||l.startsWith("__MACOSX")){console.log("Skipping",o.fullpath);continue}let s=l.indexOf(a);if(s===-1){console.log("Skipping",o.fullpath);continue}let c=l.slice(0,s)+".textbundle";if(l.slice(s+a.length+1).startsWith("._")){console.log("Skipping",o.fullpath);continue}c in n?n[c].push(o):n[c]=[o]}return Object.values(n)}async process(t,e,n){let i=n.find(a=>a.name==="info.json");if(i){let a=await i.readText(),o=JSON.parse(a);if(o.hasOwnProperty("type")&&o.type!=="net.daringfireball.markdown"){t.reportSkipped(e,"The textbundle does not contain markdown");return}}for(let a of n)if(!a.name.startsWith("._"))try{if(a.type==="file"&&(a.extension==="md"||a.extension==="markdown")){let o="parent"in a?a.parent:e;o=o.replace(/.textbundle$/,"");let l=await a.readText();l.match($g)&&(l=l.replace($g,`![[${this.attachmentsFolderPath.path}/$1]]`));let s=(0,Ir.normalizePath)(o),c=await this.getOutputFolder();await this.saveAsMarkdownFile(c,s,l),t.reportNoteSuccess(o)}else if(a.type==="file"&&a.fullpath.contains("assets/"))await this.importAsset(t,a);else if(a.type==="folder"){let{basename:o}=le(a.toString());if(o!=="assets")continue;let s=await new zr(`${a.toString()}/`).list();for(let c of s)await this.importAsset(t,c)}else a.name!=="info.json"&&t.reportSkipped(a.name,"the file is not a media or markdown file.")}catch(o){t.reportFailed(a.name,o)}}async importAsset(t,e){if(e.type==="folder"){t.reportSk
|
||
|
|
`);o.forEach((l,s)=>{l&&e.push({text:l,xmlPath:a.xmlPath}),s<o.length-1&&e.push({text:`
|
||
|
|
`,xmlPath:"newline"})})});let n=[],i=[];return e.forEach(a=>{a.xmlPath==="newline"?(n.push({contentSections:i}),i=[]):i.push(a)}),i.length>0&&n.push({contentSections:i}),n}extractContentSections(t,e){let n=[];return t.childNodes.forEach(i=>{if(i.nodeType===Node.TEXT_NODE){let a=i.textContent||"";a.length>0&&n.push({text:a,xmlPath:e})}else if(i.nodeType===Node.ELEMENT_NODE){let a=i,o=a.tagName,l=e?`${e}/${o}`:o;a.textContent?!Array.from(a.childNodes).some(c=>c.nodeType===Node.TEXT_NODE&&c.textContent&&c.textContent.length>0)&&a.children.length===0?n.push({text:a.textContent,xmlPath:l}):n.push(...this.extractContentSections(a,l)):n.push(...this.extractContentSections(a,l))}}),n}convertToMarkdown(t){this.updateTodoContext(1,t.title);let e=this.convertStructuredContent(t.content),n=Te(t.title),i=t.title!==n,a=!1;switch(this.keepTitleMode){case"yes":a=!0;break;case"no":a=!1;break;case"automatic":default:a=i;break}let o=e.split(`
|
||
|
|
`),l=this.escapeMarkdownSpecialChars(t.title);if(o.length>0&&o[0].trim()===l.trim())if(a)o[0]=`# ${t.title}`,e=o.join(`
|
||
|
|
`);else{let d=1;for(;d<o.length&&o[d].trim()==="";)d++;e=o.slice(d).join(`
|
||
|
|
`)}let s=["---"];if(t.createDate){let d=t.createDate.toISOString().split(".")[0];s.push(`created: ${d}`)}if(t.lastChangeDate){let d=t.lastChangeDate.toISOString().split(".")[0];s.push(`changed: ${d}`)}let c="system:notebook:",u=t.tags.filter(d=>d.startsWith(c)).map(d=>d.substring(c.length));t.tags.contains("system:template")&&u.push("template"),u.length>0&&s.push(`tags: [${u.map(d=>`"${d}"`).join(", ")}]`);let f="";return s.length>1&&(s.push("---"),f=s.join(`
|
||
|
|
`)+`
|
||
|
|
|
||
|
|
`),f+e}escapeMarkdownSpecialChars(t){return t.replace(/([\\`*_\[\]#])/g,"\\$1")}formatLineStream(t,e,n=!1){let i="",a=new Set,o="";for(t.forEach((l,s)=>{let c=l.text,u=l.xmlPath.includes("link:internal"),{coreText:p,leadingWhitespace:f,trailingWhitespace:d}=this.extractWhitespaceFromText(c),g=u?Te(p):this.escapeMarkdownSpecialChars(p),m={strikethrough:!n&&l.xmlPath.includes("strikethrough"),highlight:l.xmlPath.includes("highlight"),bold:!e&&l.xmlPath.includes("bold"),italic:l.xmlPath.includes("italic"),monospace:l.xmlPath.includes("monospace")},h=this.calculateFormattingChanges(a,m);i+=h.closeTags,i+=o+f,i+=h.openTags,h.openingSpans&&h.openingSpans.forEach(b=>this.activeFormatStack.push(b)),u&&(i+="[["),i+=g,u&&(i+="]]"),a=new Set(Object.keys(m).filter(b=>m[b])),o=d});this.activeFormatStack.length>0;)i+=this.activeFormatStack.pop().closeTag;return i}calculateFormattingChanges(t,e){let n=[];for(;this.activeFormatStack.length>0;){let a=this.activeFormatStack[this.activeFormatStack.length-1],o=a.format;if(!e[o])n.push(a.closeTag),this.activeFormatStack.pop();else break}let i=[];return Object.keys(e).forEach(a=>{if(e[a]&&!t.has(a)){let o=this.getMarkdownTag(a),l={format:a,openTag:o.open,closeTag:o.close};i.push(l)}}),{closeTags:n.join(""),openTags:i.map(a=>a.openTag).join(""),openingSpans:i}}getMarkdownTag(t){switch(t){case"bold":return{open:"**",close:"**"};case"italic":return{open:"*",close:"*"};case"strikethrough":return{open:"~~",close:"~~"};case"monospace":return{open:"`",close:"`"};case"highlight":return{open:"==",close:"=="};default:return{open:"",close:""}}}extractWhitespaceFromText(t){let e=t.match(/^\s*/)[0],n=t.match(/\s*$/)[0];return e.length===t.length?{coreText:"",leadingWhitespace:t,trailingWhitespace:""}:{coreText:t.substring(e.length,t.length-n.length),leadingWhitespace:e,trailingWhitespace:n}}convertStructuredContent(t){let e="";return t.forEach((n,i)=>{let a="",o=n.contentSections[0],l="",s=this.isTodoMode(),c=!1;if(o&&o.xmlPath.includes("list-item")){let f=(o.xmlPath.match(/\/list\//g)||[]).length,d=" ".repeat(f);if(s){c=this.isFullyStrikethrough(n.contentSections);let g=c?"[x]":"[ ]";l=d+"- "+g+" "}else l=d+"- "}let u="",p=!1;if(n.contentSections.length>0&&l===""){let f=n.contentSections.map(h=>h.xmlPath),d=f.every(h=>h.includes("bold")),g=f.every(h=>h.includes("size:huge")),m=f.every(h=>h.includes("size:large"));if(d||g||m){let h=6;g?h-=4:m&&(h-=2),d&&(h-=1,p=!0),u="#".repeat(h)+" ";let T=n.contentSections.map(P=>P.text).join("").trim();this.updateTodoContext(h,T)}}a=this.formatLineStream(n.contentSections,p,c),u?e+=u+a.trim():e+=l+a,i<t.length-1&&(e+=`
|
||
|
|
`)}),e}};var Zo=class extends Ee{getDefaultTomboyPath(){if(!lt.Platform.isDesktopApp||!Je||!K)return"";try{if(lt.Platform.isMacOS)return K.join(Je.homedir(),"Library","Application Support","Tomboy");if(lt.Platform.isWin)return K.join(process.env.APPDATA||"","Roaming","Tomboy");if(lt.Platform.isLinux){let t=Je.homedir();return K.join(t,".local","share","tomboy")}}catch(t){console.warn("Error detecting default Tomboy path:",t)}return""}getOSSpecificDescription(){return lt.Platform.isMacOS?"Tomboy notes are typically found in: ~/Library/Application Support/Tomboy":lt.Platform.isWin?"Tomboy notes are typically found in: %APPDATA%\\Tomboy":lt.Platform.isLinux?"Tomboy notes are typically found in: ~/.local/share/tomboy - or GNote: ~/.local/share/gnote":"Pick the files that you want to import."}init(){this.todoEnabled=!0,this.coreConverter=new Yo,this.keepTitleMode="automatic",this.addFileChooserSetting("Tomboy/Gnote",["note"],!0,this.getOSSpecificDescription(),this.getDefaultTomboyPath()),this.addOutputLocationSetting("Tomboy"),new lt.Setting(this.modal.contentEl).setName("Convert TODO lists to checkboxes").setDesc('When enabled, lists in notes with "TODO" in the title will be converted to task lists with checkboxes. Strikethrough items will be marked as completed.').addToggle(t=>{t.setValue(this.todoEnabled).onChange(e=>this.todoEnabled=e)}),new lt.Setting(this.modal.contentEl).setName("Keep title in Markdown").setDesc('Choose whether to keep the note title in the Markdown content. "Automatic" keeps titles only when special characters are lost in filename conversion.').addDropdown(t=>{t.addOption("automatic","Automatic").addOption("yes","Keep titles").addOption("no","Filename only").setValue(this.keepTitleMode).onChange(e=>this.keepTitleMode=e)})}async import(t){let{files:e}=this;if(e.length===0){new lt.Notice("Please pick at least one file to import.");return}let n=await this.getOutputFolder();if(!n){new lt.Notice("Please select a location to export to.");return}this.coreConverter.setTodoEnabled(this.todoEnabled),this.coreConverter.setKeepTitleMode(this.keepTitleMode),t.reportProgress(0,e.length);for(let i=0;i<e.length;i++){if(t.isCancelled())return;let a=e[i];t.status("Processing "+a.name);try{await this.processFile(t,n,a),t.reportNoteSuccess(a.fullpath)}catch(o){t.reportFailed(a.fullpath,o)}t.reportProgress(i+1,e.length)}}async processFile(t,e,n){let i=await n.readText(),a=this.coreConverter.parseTomboyXML(i),o=this.coreConverter.convertToMarkdown(a);await this.saveAsMarkdownFile(e,a.title,o)}};var Uo="obsidian://importer-auth/",qn=["png","webp","jpg","jpeg","gif","bmp","svg","mpg","m4a","webm","wav","ogv","3gp","mov","mp4","mkv","pdf"],Ko=class{constructor(t){this.notes=0;this.attachments=0;this.skipped=[];this.failed=[];this.maxFileNameLength=100;this.statusMessage="";this.cancelled=!1;this.el=t,this.createProgressUI(t)}createProgressUI(t){t.empty(),this.el=t,this.statusEl=t.createDiv("importer-status"),this.progressBarEl=t.createDiv("importer-progress-bar",e=>{this.progressBarInnerEl=e.createDiv("importer-progress-bar-inner")}),t.createDiv("importer-stats-container",e=>{e.createDiv("importer-stat mod-imported",n=>{this.importedCountEl=n.createDiv({cls:"importer-stat-count",text:this.notes.toString()}),n.createDiv({cls:"importer-stat-name",text:"imported"})}),e.createDiv("importer-stat mod-attachments",n=>{this.attachmentCountEl=n.createDiv({cls:"importer-stat-count",text:this.attachments.toString()}),n.createDiv({cls:"importer-stat-name",text:"attachments"})}),e.createDiv("importer-stat mod-remaining",n=>{this.remainingCountEl=n.createDiv({cls:"importer-stat-count",text:"0"}),n.createDiv({cls:"importer-stat-name",text:"remaining"})}),e.createDiv("importer-stat mod-skipped",n=>{this.skippedCountEl=n.createDiv({cls:"importer-stat-count",text:this.skipped.length.toString()}),n.createDiv({cls:"importer-stat-name",text:"skipped"})}),e.createDiv("importer-stat mod-failed",n=>{this.failedCountEl=n.createDiv({cls:"importer-stat-count",text:this.failed.length.toString()}),n.createDiv({cls:"importer-stat-name",text:"failed"})})}
|
||
|
|
/*! Bundled license information:
|
||
|
|
|
||
|
|
sax/lib/sax.js:
|
||
|
|
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
|
||
|
|
*/
|
||
|
|
|
||
|
|
/* nosourcemap */
|