Files
StudyDiary-20251025/.obsidian/plugins/obsidian-importer/main.js
T

234 lines
356 KiB
JavaScript
Raw Normal View History

2025-07-05 20:48:33 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
2025-08-30 08:29:39 +08:00
var Cd=Object.create;var Ai=Object.defineProperty;var Dd=Object.getOwnPropertyDescriptor;var Id=Object.getOwnPropertyNames;var Fd=Object.getPrototypeOf,Ld=Object.prototype.hasOwnProperty;var z=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Oe=(n,e)=>{for(var t in e)Ai(n,t,{get:e[t],enumerable:!0})},ls=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Id(e))!Ld.call(n,r)&&r!==t&&Ai(n,r,{get:()=>e[r],enumerable:!(i=Dd(e,r))||i.enumerable});return n};var Jr=(n,e,t)=>(t=n!=null?Cd(Fd(n)):{},ls(e||!n||!n.__esModule?Ai(t,"default",{value:n,enumerable:!0}):t,n)),Pd=n=>ls(Ai({},"__esModule",{value:!0}),n);var Po=z((hw,Hl)=>{"use strict";Hl.exports=Oh;function Oh(n,e){for(var t=new Array(arguments.length-1),i=0,r=2,o=!0;r<arguments.length;)t[i++]=arguments[r++];return new Promise(function(s,l){t[i]=function(p){if(o)if(o=!1,p)l(p);else{for(var m=new Array(arguments.length-1),g=0;g<m.length;)m[g++]=arguments[g];s.apply(null,m)}};try{n.apply(e||null,t)}catch(c){o&&(o=!1,l(c))}})}});var zl=z(Yl=>{"use strict";var Ji=Yl;Ji.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&e.charAt(t)==="=";)++i;return Math.ceil(e.length*3)/4-i};var _n=new Array(64),Wl=new Array(123);for(Ze=0;Ze<64;)Wl[_n[Ze]=Ze<26?Ze+65:Ze<52?Ze+71:Ze<62?Ze-4:Ze-59|43]=Ze++;var Ze;Ji.encode=function(e,t,i){for(var r=null,o=[],a=0,s=0,l;t<i;){var c=e[t++];switch(s){case 0:o[a++]=_n[c>>2],l=(c&3)<<4,s=1;break;case 1:o[a++]=_n[l|c>>4],l=(c&15)<<2,s=2;break;case 2:o[a++]=_n[l|c>>6],o[a++]=_n[c&63],s=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return s&&(o[a++]=_n[l],o[a++]=61,s===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var ql="invalid encoding";Ji.decode=function(e,t,i){for(var r=i,o=0,a,s=0;s<e.length;){var l=e.charCodeAt(s++);if(l===61&&o>1)break;if((l=Wl[l])===void 0)throw Error(ql);switch(o){case 0:a=l,o=1;break;case 1:t[i++]=a<<2|(l&48)>>4,a=l,o=2;break;case 2:t[i++]=(a&15)<<4|(l&60)>>2,a=l,o=3;break;case 3:t[i++]=(a&3)<<6|l,o=0;break}}if(o===1)throw Error(ql);return i-r};Ji.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Gl=z((yw,Zl)=>{"use strict";Zl.exports=Qi;function Qi(){this._listeners={}}Qi.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this};Qi.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var i=this._listeners[e],r=0;r<i.length;)i[r].fn===t?i.splice(r,1):++r;return this};Qi.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],r=1;r<arguments.length;)i.push(arguments[r++]);for(r=0;r<t.length;)t[r].fn.apply(t[r++].ctx,i)}return this}});var tc=z((bw,ec)=>{"use strict";ec.exports=Vl(Vl);function Vl(n){return typeof Float32Array!="undefined"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),i=t[3]===128;function r(l,c,p){e[0]=l,c[p]=t[0],c[p+1]=t[1],c[p+2]=t[2],c[p+3]=t[3]}function o(l,c,p){e[0]=l,c[p]=t[3],c[p+1]=t[2],c[p+2]=t[1],c[p+3]=t[0]}n.writeFloatLE=i?r:o,n.writeFloatBE=i?o:r;function a(l,c){return t[0]=l[c],t[1]=l[c+1],t[2]=l[c+2],t[3]=l[c+3],e[0]}function s(l,c){return t[3]=l[c],t[2]=l[c+1],t[1]=l[c+2],t[0]=l[c+3],e[0]}n.readFloatLE=i?a:s,n.readFloatBE=i?s:a}():function(){function e(i,r,o,a){var s=r<0?1:0;if(s&&(r=-r),r===0)i(1/r>0?0:2147483648,o,a);else if(isNaN(r))i(2143289344,o,a);else if(r>34028234663852886e22)i((s<<31|2139095040)>>>0,o,a);else if(r<11754943508222875e-54)i((s<<31|Math.round(r/1401298464324817e-60))>>>0,o,a);else{var l=Math.floor(Math.log(r)/Math.LN2),c=Math.round(r*Math.pow(2,-l)*8388608)&8388607;i((s<<31|l+127<<23|c)>>>0,o,a)}}n.writeFloatLE=e.bind(null,Kl),n.writeFloatBE=e.bind(null,Xl);function t(i,r,o){var a=i(r,o),s=(a>>31)*2+1,l=a>>>23&255,c=a&8388607;return l===255?c?NaN:s*(1/0):l===0?s*1401298464324817e-60*c:s*Math.pow(2,l-150)*(c+8388608)}n.readFloatLE=t.bind(null,Jl),n.readFloatBE=t.bind(null,Ql)}(),typeof Float64Array!="undefined"?
2025-07-05 20:48:33 +08:00
`+t.join(`
`)+`
2025-08-30 08:29:39 +08:00
}`}return i.toString=r,i}Xo.verbose=!1});var Pc=z((Dw,Lc)=>{"use strict";Lc.exports=si;var Bh=Po(),Uh=Mo(),Jo=Uh("fs");function si(n,e,t){return typeof e=="function"?(t=e,e={}):e||(e={}),t?!e.xhr&&Jo&&Jo.readFile?Jo.readFile(n,function(r,o){return r&&typeof XMLHttpRequest!="undefined"?si.xhr(n,e,t):r?t(r):t(null,e.binary?o:o.toString("utf8"))}):si.xhr(n,e,t):Bh(si,this,n,e)}si.xhr=function(e,t,i){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4){if(r.status!==0&&r.status!==200)return i(Error("status "+r.status));if(t.binary){var a=r.response;if(!a){a=[];for(var s=0;s<r.responseText.length;++s)a.push(r.responseText.charCodeAt(s)&255)}return i(null,typeof Uint8Array!="undefined"?new Uint8Array(a):a)}return i(null,r.responseText)}},t.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",e),r.send()}});var Bc=z($c=>{"use strict";var ea=$c,Mc=ea.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},Qo=ea.normalize=function(e){e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var t=e.split("/"),i=Mc(e),r="";i&&(r=t.shift()+"/");for(var o=0;o<t.length;)t[o]===".."?o>0&&t[o-1]!==".."?t.splice(--o,2):i?t.splice(o,1):++o:t[o]==="."?t.splice(o,1):++o;return r+t.join("/")};ea.resolve=function(e,t,i){return i||(t=Qo(t)),Mc(t)?t:(i||(e=Qo(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?Qo(e+"/"+t):t)}});var an=z(Uc=>{"use strict";var li=Uc,jh=be(),Hh=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function ci(n,e){var t=0,i={};for(e|=0;t<n.length;)i[Hh[t+e]]=n[t++];return i}li.basic=ci([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);li.defaults=ci([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",jh.emptyArray,null]);li.long=ci([0,0,0,1,1],7);li.mapKey=ci([0,0,0,5,5,0,0,0,1,1,0,2],2);li.packed=ci([1,5,0,0,0,5,5,0,0,0,1,1,0])});var It=z((Lw,qc)=>{"use strict";qc.exports=je;var rr=sn();((je.prototype=Object.create(rr.prototype)).constructor=je).className="Field";var jc=Ke(),Hc=an(),fe=be(),ta,qh=/^required|optional|repeated$/;je.fromJSON=function(e,t){return new je(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)};function je(n,e,t,i,r,o,a){if(fe.isObject(i)?(a=r,o=i,i=r=void 0):fe.isObject(r)&&(a=o,o=r,r=void 0),rr.call(this,n,o),!fe.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!fe.isString(t))throw TypeError("type must be a string");if(i!==void 0&&!qh.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(r!==void 0&&!fe.isString(r))throw TypeError("extend must be a string");i==="proto3_optional"&&(i="optional"),this.rule=i&&i!=="optional"?i:void 0,this.type=t,this.id=e,this.extend=r||void 0,this.required=i==="required",this.optional=!this.required,this.repeated=i==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=fe.Long?Hc.long[t]!==void 0:!1,this.bytes=t==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=a}Object.defineProperty(je.prototype,"packed",{get:function(){return this._packed===null&&(this._packed=this.getOption("packed")!==!1),this._packed}});je.prototype.setOption=function(e,t,i){return e==="packed"&&(this._packed=null),rr.prototype.setOption.call(this,e,t,i)};je.prototype.toJSON=function(e){var t=e?!!e.keepComments:!1;return fe.toObject(["rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])};je.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=Hc.defaults[this.type])===void 0?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof ta?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.optio
`,t:" "};function Ap(n){return n.replace(Ag,function(e,t){switch(t){case"\\":case"":return t;default:return kg[t]||""}})}kp.unescape=Ap;function kp(n,e){n=n.toString();var t=0,i=n.length,r=1,o=0,a={},s=[],l=null;function c(A){return Error("illegal "+A+" (line "+r+")")}function p(){var A=l==="'"?wg:xg;A.lastIndex=t-1;var O=A.exec(n);if(!O)throw c("string");return t=A.lastIndex,f(l),l=null,Ap(O[1])}function m(A){return n.charAt(A)}function g(A,O,_){var k={type:n.charAt(A++),lineEmpty:!1,leading:_},w;e?w=2:w=3;var D=A-w,C;do if(--D<0||(C=n.charAt(D))===`
`){k.lineEmpty=!0;break}while(C===" "||C===" ");for(var N=n.substring(A,O).split(Tg),P=0;P<N.length;++P)N[P]=N[P].replace(e?Eg:vg,"").trim();k.text=N.join(`
`).trim(),a[r]=k,o=r}function b(A){var O=v(A),_=n.substring(A,O),k=/^\s*\/\//.test(_);return k}function v(A){for(var O=A;O<i&&m(O)!==`
`;)O++;return O}function d(){if(s.length>0)return s.shift();if(l)return p();var A,O,_,k,w,D=t===0;do{if(t===i)return null;for(A=!1;_g.test(_=m(t));)if(_===`
`&&(D=!0,++r),++t===i)return null;if(m(t)==="/"){if(++t===i)throw c("comment");if(m(t)==="/")if(e){if(k=t,w=!1,b(t-1)){w=!0;do if(t=v(t),t===i||(t++,!D))break;while(b(t))}else t=Math.min(i,v(t)+1);w&&(g(k,t,D),D=!0),r++,A=!0}else{for(w=m(k=t+1)==="/";m(++t)!==`
`;)if(t===i)return null;++t,w&&(g(k,t-1,D),D=!0),++r,A=!0}else if((_=m(t))==="*"){k=t+1,w=e||m(k)==="*";do{if(_===`
`&&++r,++t===i)throw c("comment");O=_,_=m(t)}while(O!=="*"||_!=="/");++t,w&&(g(k,t-2,D),D=!0),A=!0}else return"/"}}while(A);var C=t;_a.lastIndex=0;var N=_a.test(m(C++));if(!N)for(;C<i&&!_a.test(m(C));)++C;var P=n.substring(t,t=C);return(P==='"'||P==="'")&&(l=P),P}function f(A){s.push(A)}function h(){if(!s.length){var A=d();if(A===null)return null;f(A)}return s[0]}function E(A,O){var _=h(),k=_===A;if(k)return d(),!0;if(!O)throw c("token '"+_+"', '"+A+"' expected");return!1}function T(A){var O=null,_;return A===void 0?(_=a[r-1],delete a[r-1],_&&(e||_.type==="*"||_.lineEmpty)&&(O=_.leading?_.text:null)):(o<A&&h(),_=a[A],delete a[A],_&&!_.lineEmpty&&(e||_.type==="/")&&(O=_.leading?null:_.text)),O}return Object.defineProperty({next:d,peek:h,push:f,skip:E,cmnt:T},"line",{get:function(){return r}})}});var Ip=z((ev,Dp)=>{"use strict";Dp.exports=gt;gt.filename=null;gt.defaults={keepCase:!1};var Ng=Aa(),Sp=yr(),Rp=mr(),Op=It(),Sg=lr(),Cp=An(),Rg=Ke(),Og=pr(),Cg=cr(),ka=an(),Na=be(),Dg=/^[1-9][0-9]*$/,Ig=/^-?[1-9][0-9]*$/,Fg=/^0[x][0-9a-fA-F]+$/,Lg=/^-?0[x][0-9a-fA-F]+$/,Pg=/^0[0-7]+$/,Mg=/^-?0[0-7]+$/,$g=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,at=/^[a-zA-Z_][a-zA-Z_0-9]*$/,st=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,Bg=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function gt(n,e,t){e instanceof Sp||(t=e,e=new Sp),t||(t=gt.defaults);var i=t.preferTrailingComment||!1,r=Ng(n,t.alternateCommentMode||!1),o=r.next,a=r.push,s=r.peek,l=r.skip,c=r.cmnt,p=!0,m,g,b,v,d=!1,f=e,h=t.keepCase?function(x){return x}:Na.camelCase;function E(x,S,I){var F=gt.filename;return I||(gt.filename=null),Error("illegal "+(S||"token")+" '"+x+"' ("+(F?F+", ":"")+"line "+r.line+")")}function T(){var x=[],S;do{if((S=o())!=='"'&&S!=="'")throw E(S);x.push(o()),l(S),S=s()}while(S==='"'||S==="'");return x.join("")}function A(x){var S=o();switch(S){case"'":case'"':return a(S),T();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return _(S,!0)}catch(I){if(x&&st.test(S))return S;throw E(S,"value")}}function O(x,S){var I,F;do S&&((I=s())==='"'||I==="'")?x.push(T()):x.push([F=k(o()),l("to",!0)?k(o()):F]);while(l(",",!0));l(";")}function _(x,S){var I=1;switch(x.charAt(0)==="-"&&(I=-1,x=x.substring(1)),x){case"inf":case"INF":case"Inf":return I*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if(Dg.test(x))return I*parseInt(x,10);if(Fg.test(x))return I*parseInt(x,16);if(Pg.test(x))return I*parseInt(x,8);if($g.test(x))return I*parseFloat(x);throw E(x,"number",S)}function k(x,S){switch(x){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!S&&x.charAt(0)==="-")throw E(x,"id");if(Ig.test(x))return parseInt(x,10);if(Lg.test(x))return parseInt(x,16);if(Mg.test(x))return parseInt(x,8);throw E(x,"id")}function w(){if(m!==void 0)throw E("package");if(m=o(),!st.test(m))throw E(m,"name");f=f.define(m),l(";")}function D(){var x=s(),S;switch(x){case"weak":S=b||(b=[]),o();break;case"public":o();default:S=g||(g=[]);break}x=T(),l(";"),S.push(x)}function C(){if(l("="),v=T(),d=v==="proto3",!d&&v!=="proto2")throw E(v,"syntax");l(";")}function N(x,S){switch(S){case"option":return U(x,S),l(";"),!0;case"message":return L(x,S),!0;case"enum":return Z(x,S),!0;case"service":return Yt(x,S),!0;case"extend":return u(x,S),!0}return!1}function P(x,S,I){var F=r.line;if(x&&(typeof x.comment!="string"&&(x.comment=c()),x.filename=gt.filename),l("{",!0)){for(var $;($=o())!=="}";)S($);l(";",!0)}else I&&I(),l(";"),x&&(typeof x.comment!="string"||i)&&(x.comment=c(F)||x.comment)}function L(x,S){if(!at.test(S=o()))throw E(S,"type name");var I=new Rp(S);P(I,function($){if(!N(I,$))switch($){case"map":M(I,$);break;case"required":case"repeated":j(I,$);break;case"optional":d?j(I,"proto3_optional"):j(I,"optional");break;case"oneof":ne(I,$);break;case"extensions":O(I.extensions||(I.extensions=[]));break;case"reserved":O(I.reserved||(I.reserved=[]),!0);break;default:if(!d||!st.test($))throw E($);a($),j(I,"optional");break}}),x.add(I)}function j(x,S,I){var F=o();if(F==="group"){Y(x,S);return}for(;F.endsWith(".")||s().startsWith(".");)F+=o()
2025-07-05 20:48:33 +08:00
`+i.fence+o+`
`+t.firstChild.textContent+`
`+i.fence+`
2025-08-30 08:29:39 +08:00
`}})}function nu(n){n.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(e){return"~~"+e+"~~"}})}var t0=Array.prototype.indexOf,n0=Array.prototype.every,Mt={},i0={left:":---",right:"---:",center:":---:"},La=null,iu=null,eu=new WeakMap;function r0(n){return n?(n.getAttribute("align")||n.style.textAlign||"").toLowerCase():""}function ru(n){return n?i0[n]:"---"}function ou(n,e){for(var t={left:0,right:0,center:0,"":0},i="",r=0;r<n.rows.length;++r){var o=n.rows[r];if(e<o.childNodes.length){var a=r0(o.childNodes[e]);++t[a],t[a]>t[i]&&(i=a)}}return i}Mt.tableCell={filter:["th","td"],replacement:function(n,e){return Ma(cu(e))?n:au(n,e)}};Mt.tableRow={filter:"tr",replacement:function(n,e){let t=cu(e);if(Ma(t))return n;var i="";if(o0(e)){let a=pu(t);for(var r=0;r<a;r++){let s=r<e.childNodes.length?e.childNodes[r]:null;var o=ru(ou(t,r));i+=au(o,s,r)}}return`
2025-07-05 20:48:33 +08:00
`+n+(i?`
2025-08-30 08:29:39 +08:00
`+i:"")}};Mt.table={filter:function(n,e){return n.nodeName==="TABLE"},replacement:function(n,e){if(lu(e,iu)){let s=e.outerHTML,l=l0(e);return l===null||!l.classList.contains("joplin-table-wrapper")?`
2025-07-05 20:48:33 +08:00
<div class="joplin-table-wrapper">${s}</div>
`:s}else{if(Ma(e))return n;n=n.replace(/\n+/g,`
`);var t=n.trim().split(`
2025-08-30 08:29:39 +08:00
`);t.length>=2&&(t=t[1]);var i=/\| :?---/.test(t),r=pu(e),o="";if(r&&!i){o="|"+" |".repeat(r)+`
|`;for(var a=0;a<r;++a)o+=" "+ru(ou(e,a))+" |"}let s=e.caption&&e.caption.textContent||"",l=s?`${s}
2025-07-05 20:48:33 +08:00
`:"",c=`${o}${n}`.trimStart();return`
${l}${c}
2025-08-30 08:29:39 +08:00
`}}};Mt.tableCaption={filter:["caption"],replacement:()=>""};Mt.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Mt.tableSection={filter:["thead","tbody","tfoot"],replacement:function(n){return n}};function o0(n){var e=n.parentNode;return e.nodeName==="THEAD"||e.firstChild===n&&(e.nodeName==="TABLE"||a0(e))&&n0.call(n.childNodes,function(t){return t.nodeName==="TH"})}function a0(n){var e=n.previousSibling;return n.nodeName==="TBODY"&&(!e||e.nodeName==="THEAD"&&/^\s*$/i.test(e.textContent))}function au(n,e=null,t=null){t===null&&(t=t0.call(e.parentNode.childNodes,e));var i=" ";t===0&&(i="| ");let r=n.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");for(r=r.replace(/\|+/g,"\\|");r.length<3;)r+=" ";return e&&(r=c0(r,e," ")),i+r+" |"}function su(n){if(!n.childNodes)return!1;for(let e=0;e<n.childNodes.length;e++){let t=n.childNodes[e];if(t.nodeName==="TABLE"||su(t))return!0}return!1}var Pa=(n,e)=>{if(!n.childNodes)return!1;for(let t=0;t<n.childNodes.length;t++){let i=n.childNodes[t];if(e==="code"&&La&&La(i)||e.includes(i.nodeName)||Pa(i,e))return!0}return!1},lu=(n,e)=>{let t=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];return e.preserveNestedTables&&t.push("TABLE"),Pa(n,"code")||Pa(n,t)};function Ma(n){let e=eu.get(n);if(e!==void 0)return e;let t=s0(n);return eu.set(n,t),t}function s0(n){return!!(!n||!n.rows||n.rows.length===1&&n.rows[0].childNodes.length<=1||su(n))}function l0(n){let e=n.parentNode;for(;e.nodeName!=="DIV";)if(e=e.parentNode,!e)return null;return e}function cu(n){let e=n.parentNode;for(;e.nodeName!=="TABLE";)if(e=e.parentNode,!e)return null;return e}function c0(n,e,t){let i=e.getAttribute("colspan")||1;for(let r=1;r<i;r++)n+=" | "+t.repeat(3);return n}function pu(n){let e=0;for(let t=0;t<n.rows.length;t++){let r=n.rows[t].childNodes.length;r>e&&(e=r)}return e}function uu(n){La=n.isCodeBlock,iu=n.options,n.keep(function(t){return!!(t.nodeName==="TABLE"&&lu(t,n.options))});for(var e in Mt)n.addRule(e,Mt[e])}function fu(n){n.addRule("taskListItems",{filter:function(e){return e.type==="checkbox"&&e.parentNode.nodeName==="LI"},replacement:function(e,t){return(t.checked?"[x]":"[ ]")+" "}})}function p0(n){n.use([tu,nu,uu,fu])}cn.gfm=p0;cn.highlightedCodeBlock=tu;cn.strikethrough=nu;cn.tables=uu;cn.taskListItems=fu});var Zf=z(Fr=>{(function(n){n.parser=function(y,u){return new t(y,u)},n.SAXParser=t,n.SAXStream=c,n.createStream=l,n.MAX_BUFFER_LENGTH=64*1024;var e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];n.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function t(y,u){if(!(this instanceof t))return new t(y,u);var R=this;r(R),R.q=R.c="",R.bufferCheckPosition=n.MAX_BUFFER_LENGTH,R.opt=u||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!y,R.noscript=!!(y||R.opt.noscript),R.state=w.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(n.XML_ENTITIES):Object.create(n.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(v)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),C(R,"onready")}Object.create||(Object.create=function(y){function u(){}u.prototype=y;var R=new u;return R}),Object.keys||(Object.keys=function(y){var u=[];for(var R in y)y.hasOwnProperty(R)&&u.push(R);return u});function i(y){for(var u=Math.max(n.MAX_BUFFER_LENGTH,10),R=0,x=0,S=e.length;x<S;x++){var I=y[e[x]].length;if(I>u)switch(e[x]){case"textNode":P(y);break;case"cdata":N(y,"oncdata",y.cdata),y.cdata="";break;case"script":N(y,"onscript",y.script),y.script="";break;default:j(y,"Max buffer length exceeded: "+e[x])}R=Math.max(R,I)}var F=n.MAX_BUFFER_LENGTH-R;y.bufferCheckPosition=F+y.position}function r(y){for(var u=0,R=e.length;u<R;u++)y[e[u]]=""}func
`||y==="\r"||y===" "}function A(y){return y==='"'||y==="'"}function O(y){return y===">"||T(y)}function _(y,u){return y.test(u)}function k(y,u){return!_(y,u)}var w=0;n.STATE={BEGIN:w++,BEGIN_WHITESPACE:w++,TEXT:w++,TEXT_ENTITY:w++,OPEN_WAKA:w++,SGML_DECL:w++,SGML_DECL_QUOTED:w++,DOCTYPE:w++,DOCTYPE_QUOTED:w++,DOCTYPE_DTD:w++,DOCTYPE_DTD_QUOTED:w++,COMMENT_STARTING:w++,COMMENT:w++,COMMENT_ENDING:w++,COMMENT_ENDED:w++,CDATA:w++,CDATA_ENDING:w++,CDATA_ENDING_2:w++,PROC_INST:w++,PROC_INST_BODY:w++,PROC_INST_ENDING:w++,OPEN_TAG:w++,OPEN_TAG_SLASH:w++,ATTRIB:w++,ATTRIB_NAME:w++,ATTRIB_NAME_SAW_WHITE:w++,ATTRIB_VALUE:w++,ATTRIB_VALUE_QUOTED:w++,ATTRIB_VALUE_CLOSED:w++,ATTRIB_VALUE_UNQUOTED:w++,ATTRIB_VALUE_ENTITY_Q:w++,ATTRIB_VALUE_ENTITY_U:w++,CLOSE_TAG:w++,CLOSE_TAG_SAW_WHITE:w++,SCRIPT:w++,SCRIPT_ENDING:w++},n.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},n.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(n.ENTITIES).forEach(function(y){var u=n.ENTITIES[y],R=typeof u=="number"?String.fromCharCode(u):u;n.ENTITIES[y]=R});for(var D in n.STATE)n.STATE[n.STATE[D]]=D;w=n.STATE;function C(y,u,R){y[u]&&y[u](R)}function N(y,u,R){y.textNode&&P(y),C(y,u,R)}function P(y){y.textNode=L(y.opt,y.textNode),y.textNode&&C(y,"ontext",y.textNode),y.textNode=""}function L(y,u){return y.trim&&(u=u.trim()),y.normalize&&(u=u.replace(/\s+/g," ")),u}function j(y,u){return P(y),y.trackPosition&&(u+=`
2025-07-05 20:48:33 +08:00
Line: `+y.line+`
Column: `+y.column+`
Char: `+y.c),u=new Error(u),y.error=u,C(y,"onerror",u),y}function Y(y){return y.sawRoot&&!y.closedRoot&&M(y,"Unclosed root tag"),y.state!==w.BEGIN&&y.state!==w.BEGIN_WHITESPACE&&y.state!==w.TEXT&&j(y,"Unexpected end"),P(y),y.c="",y.closed=!0,C(y,"onend"),t.call(y,y.strict,y.opt),y}function M(y,u){if(typeof y!="object"||!(y instanceof t))throw new Error("bad call to strictFail");y.strict&&j(y,u)}function ne(y){y.strict||(y.tagName=y.tagName[y.looseCase]());var u=y.tags[y.tags.length-1]||y,R=y.tag={name:y.tagName,attributes:{}};y.opt.xmlns&&(R.ns=u.ns),y.attribList.length=0,N(y,"onopentagstart",R)}function Z(y,u){var R=y.indexOf(":"),x=R<0?["",y]:y.split(":"),S=x[0],I=x[1];return u&&y==="xmlns"&&(S="xmlns",I=""),{prefix:S,local:I}}function pe(y){if(y.strict||(y.attribName=y.attribName[y.looseCase]()),y.attribList.indexOf(y.attribName)!==-1||y.tag.attributes.hasOwnProperty(y.attribName)){y.attribName=y.attribValue="";return}if(y.opt.xmlns){var u=Z(y.attribName,!0),R=u.prefix,x=u.local;if(R==="xmlns")if(x==="xml"&&y.attribValue!==g)M(y,"xml: prefix must be bound to "+g+`
Actual: `+y.attribValue);else if(x==="xmlns"&&y.attribValue!==b)M(y,"xmlns: prefix must be bound to "+b+`
2025-08-30 08:29:39 +08:00
Actual: `+y.attribValue);else{var S=y.tag,I=y.tags[y.tags.length-1]||y;S.ns===I.ns&&(S.ns=Object.create(I.ns)),S.ns[x]=y.attribValue}y.attribList.push([y.attribName,y.attribValue])}else y.tag.attributes[y.attribName]=y.attribValue,N(y,"onattribute",{name:y.attribName,value:y.attribValue});y.attribName=y.attribValue=""}function U(y,u){if(y.opt.xmlns){var R=y.tag,x=Z(y.tagName);R.prefix=x.prefix,R.local=x.local,R.uri=R.ns[x.prefix]||"",R.prefix&&!R.uri&&(M(y,"Unbound namespace prefix: "+JSON.stringify(y.tagName)),R.uri=x.prefix);var S=y.tags[y.tags.length-1]||y;R.ns&&S.ns!==R.ns&&Object.keys(R.ns).forEach(function(ss){N(y,"onopennamespace",{prefix:ss,uri:R.ns[ss]})});for(var I=0,F=y.attribList.length;I<F;I++){var $=y.attribList[I],W=$[0],te=$[1],ee=Z(W,!0),re=ee.prefix,gn=ee.local,Xr=re===""?"":R.ns[re]||"",zt={name:W,value:te,prefix:re,local:gn,uri:Xr};re&&re!=="xmlns"&&!Xr&&(M(y,"Unbound namespace prefix: "+JSON.stringify(re)),zt.uri=re),y.tag.attributes[W]=zt,N(y,"onattribute",zt)}y.attribList.length=0}y.tag.isSelfClosing=!!u,y.sawRoot=!0,y.tags.push(y.tag),N(y,"onopentag",y.tag),u||(!y.noscript&&y.tagName.toLowerCase()==="script"?y.state=w.SCRIPT:y.state=w.TEXT,y.tag=null,y.tagName=""),y.attribName=y.attribValue="",y.attribList.length=0}function Re(y){if(!y.tagName){M(y,"Weird empty close tag."),y.textNode+="</>",y.state=w.TEXT;return}if(y.script){if(y.tagName!=="script"){y.script+="</"+y.tagName+">",y.tagName="",y.state=w.SCRIPT;return}N(y,"onscript",y.script),y.script=""}var u=y.tags.length,R=y.tagName;y.strict||(R=R[y.looseCase]());for(var x=R;u--;){var S=y.tags[u];if(S.name!==x)M(y,"Unexpected close tag");else break}if(u<0){M(y,"Unmatched closing tag: "+y.tagName),y.textNode+="</"+y.tagName+">",y.state=w.TEXT;return}y.tagName=R;for(var I=y.tags.length;I-- >u;){var F=y.tag=y.tags.pop();y.tagName=y.tag.name,N(y,"onclosetag",y.tagName);var $={};for(var W in F.ns)$[W]=F.ns[W];var te=y.tags[y.tags.length-1]||y;y.opt.xmlns&&F.ns!==te.ns&&Object.keys(F.ns).forEach(function(ee){var re=F.ns[ee];N(y,"onclosenamespace",{prefix:ee,uri:re})})}u===0&&(y.closedRoot=!0),y.tagName=y.attribValue=y.attribName="",y.attribList.length=0,y.state=w.TEXT}function G(y){var u=y.entity,R=u.toLowerCase(),x,S="";return y.ENTITIES[u]?y.ENTITIES[u]:y.ENTITIES[R]?y.ENTITIES[R]:(u=R,u.charAt(0)==="#"&&(u.charAt(1)==="x"?(u=u.slice(2),x=parseInt(u,16),S=x.toString(16)):(u=u.slice(1),x=parseInt(u,10),S=x.toString(10))),u=u.replace(/^0+/,""),isNaN(x)||S.toLowerCase()!==u?(M(y,"Invalid character entity"),"&"+y.entity+";"):String.fromCodePoint(x))}function Q(y,u){u==="<"?(y.state=w.OPEN_WAKA,y.startTagPosition=y.position):T(u)||(M(y,"Non-whitespace before first tag."),y.textNode=u,y.state=w.TEXT)}function ct(y,u){var R="";return u<y.length&&(R=y.charAt(u)),R}function Yt(y){var u=this;if(this.error)throw this.error;if(u.closed)return j(u,"Cannot write after close. Assign an onready handler.");if(y===null)return Y(u);typeof y=="object"&&(y=y.toString());for(var R=0,x="";x=ct(y,R++),u.c=x,!!x;)switch(u.trackPosition&&(u.position++,x===`
2025-07-05 20:48:33 +08:00
`?(u.line++,u.column=0):u.column++),u.state){case w.BEGIN:if(u.state=w.BEGIN_WHITESPACE,x==="\uFEFF")continue;Q(u,x);continue;case w.BEGIN_WHITESPACE:Q(u,x);continue;case w.TEXT:if(u.sawRoot&&!u.closedRoot){for(var S=R-1;x&&x!=="<"&&x!=="&";)x=ct(y,R++),x&&u.trackPosition&&(u.position++,x===`
2025-08-30 08:29:39 +08:00
`?(u.line++,u.column=0):u.column++);u.textNode+=y.substring(S,R-1)}x==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=w.OPEN_WAKA,u.startTagPosition=u.position):(!T(x)&&(!u.sawRoot||u.closedRoot)&&M(u,"Text data outside of root node."),x==="&"?u.state=w.TEXT_ENTITY:u.textNode+=x);continue;case w.SCRIPT:x==="<"?u.state=w.SCRIPT_ENDING:u.script+=x;continue;case w.SCRIPT_ENDING:x==="/"?u.state=w.CLOSE_TAG:(u.script+="<"+x,u.state=w.SCRIPT);continue;case w.OPEN_WAKA:if(x==="!")u.state=w.SGML_DECL,u.sgmlDecl="";else if(!T(x))if(_(d,x))u.state=w.OPEN_TAG,u.tagName=x;else if(x==="/")u.state=w.CLOSE_TAG,u.tagName="";else if(x==="?")u.state=w.PROC_INST,u.procInstName=u.procInstBody="";else{if(M(u,"Unencoded <"),u.startTagPosition+1<u.position){var I=u.position-u.startTagPosition;x=new Array(I).join(" ")+x}u.textNode+="<"+x,u.state=w.TEXT}continue;case w.SGML_DECL:(u.sgmlDecl+x).toUpperCase()===p?(N(u,"onopencdata"),u.state=w.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+x==="--"?(u.state=w.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+x).toUpperCase()===m?(u.state=w.DOCTYPE,(u.doctype||u.sawRoot)&&M(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):x===">"?(N(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=w.TEXT):(A(x)&&(u.state=w.SGML_DECL_QUOTED),u.sgmlDecl+=x);continue;case w.SGML_DECL_QUOTED:x===u.q&&(u.state=w.SGML_DECL,u.q=""),u.sgmlDecl+=x;continue;case w.DOCTYPE:x===">"?(u.state=w.TEXT,N(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=x,x==="["?u.state=w.DOCTYPE_DTD:A(x)&&(u.state=w.DOCTYPE_QUOTED,u.q=x));continue;case w.DOCTYPE_QUOTED:u.doctype+=x,x===u.q&&(u.q="",u.state=w.DOCTYPE);continue;case w.DOCTYPE_DTD:u.doctype+=x,x==="]"?u.state=w.DOCTYPE:A(x)&&(u.state=w.DOCTYPE_DTD_QUOTED,u.q=x);continue;case w.DOCTYPE_DTD_QUOTED:u.doctype+=x,x===u.q&&(u.state=w.DOCTYPE_DTD,u.q="");continue;case w.COMMENT:x==="-"?u.state=w.COMMENT_ENDING:u.comment+=x;continue;case w.COMMENT_ENDING:x==="-"?(u.state=w.COMMENT_ENDED,u.comment=L(u.opt,u.comment),u.comment&&N(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+x,u.state=w.COMMENT);continue;case w.COMMENT_ENDED:x!==">"?(M(u,"Malformed comment"),u.comment+="--"+x,u.state=w.COMMENT):u.state=w.TEXT;continue;case w.CDATA:x==="]"?u.state=w.CDATA_ENDING:u.cdata+=x;continue;case w.CDATA_ENDING:x==="]"?u.state=w.CDATA_ENDING_2:(u.cdata+="]"+x,u.state=w.CDATA);continue;case w.CDATA_ENDING_2:x===">"?(u.cdata&&N(u,"oncdata",u.cdata),N(u,"onclosecdata"),u.cdata="",u.state=w.TEXT):x==="]"?u.cdata+="]":(u.cdata+="]]"+x,u.state=w.CDATA);continue;case w.PROC_INST:x==="?"?u.state=w.PROC_INST_ENDING:T(x)?u.state=w.PROC_INST_BODY:u.procInstName+=x;continue;case w.PROC_INST_BODY:if(!u.procInstBody&&T(x))continue;x==="?"?u.state=w.PROC_INST_ENDING:u.procInstBody+=x;continue;case w.PROC_INST_ENDING:x===">"?(N(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=w.TEXT):(u.procInstBody+="?"+x,u.state=w.PROC_INST_BODY);continue;case w.OPEN_TAG:_(f,x)?u.tagName+=x:(ne(u),x===">"?U(u):x==="/"?u.state=w.OPEN_TAG_SLASH:(T(x)||M(u,"Invalid character in tag name"),u.state=w.ATTRIB));continue;case w.OPEN_TAG_SLASH:x===">"?(U(u,!0),Re(u)):(M(u,"Forward-slash in opening tag not followed by >"),u.state=w.ATTRIB);continue;case w.ATTRIB:if(T(x))continue;x===">"?U(u):x==="/"?u.state=w.OPEN_TAG_SLASH:_(d,x)?(u.attribName=x,u.attribValue="",u.state=w.ATTRIB_NAME):M(u,"Invalid attribute name");continue;case w.ATTRIB_NAME:x==="="?u.state=w.ATTRIB_VALUE:x===">"?(M(u,"Attribute without value"),u.attribValue=u.attribName,pe(u),U(u)):T(x)?u.state=w.ATTRIB_NAME_SAW_WHITE:_(f,x)?u.attribName+=x:M(u,"Invalid attribute name");continue;case w.ATTRIB_NAME_SAW_WHITE:if(x==="=")u.state=w.ATTRIB_VALUE;else{if(T(x))continue;M(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",N(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",x===">"?U(u):_(d,x)?(u.attribName=x,u.state=w.ATTRIB_NAME):(M(u,"Invalid attribute name"),u.state=w.ATTRIB)}continue;case w.ATTRIB_VALUE:if(T(x))continue;A(x)?(u.q=x,u
`:"";function s(l,c,p){let m="",g,b=c,v=p?a+p:"",d=p+t,f="";return l=l||"",l.constructor===Array?(l.forEach(h=>{m+=s(h,b,p)}),m):(!b&&l.$name&&(b=l.$name),b&&(m=`${v}<${b}`,l.$attrs&&typeof l.$attrs=="object"&&(g=Object.keys(l.$attrs),g.forEach(h=>{m+=` ${h}=${JSON.stringify(String(l.$attrs[h]))}`}))),l==null||l===""||(typeof l=="object"?(g=Object.keys(l),g.forEach(h=>{let E=l[h];switch(h){case"$name":case"$attrs":break;case"$text":case"$markup":f+=s(E,null,d);break;case"$script":f+=s(E,"script",d);break;case"$cdata":f+=`${v}<![CDATA[${E}]]>`;break;default:f+=s(E,h,d)}})):f+=v+r(l)),b?f?m+=`>${f}${a}${p}</${b}>`:i?m+="/>":m+=`></${b}>`:m+=f,m)}return s(e,o,"")};Qf.exports=Ei});var l1={};Oe(l1,{ATTACHMENT_EXTS:()=>$n,AUTH_REDIRECT_URI:()=>qr,ImportContext:()=>Vr,ImporterModal:()=>_i,default:()=>Kr});module.exports=Pd(l1);var Wt=require("obsidian");var lt=require("obsidian");var vt=class{constructor(e){this.importer=e,this.app=e.app}};var Un=class extends vt{constructor(e,t){super(e),this.scan=t.mergableDataObject,this.objects=this.scan.mergeableDataObjectData.mergeableDataObjectEntry}async format(e,t){let i=[];for(let r of this.objects){if(!r.customMap)continue;let o=r.customMap.mapEntry[0].value.stringValue,a=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT z_pk, zmedia, ztypeuti FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${o}`,s=await this.importer.resolveAttachment(a.Z_PK,"com.apple.notes.gallery");if(s||(s=await this.importer.resolveAttachment(a.ZMEDIA,a.ZTYPEUTI)),s)i.push(this.importer.app.fileManager.generateMarkdownLink(s,t));else return"**Cannot decode scan**"}return`
${i.join(`
2025-07-05 20:48:33 +08:00
`)}
`}};Un.protobufType="ciofecaforensics.MergableDataProto";var jn=class extends vt{constructor(t,i){super(t);this.rowLocations={};this.columnLocations={};this.table=i.mergableDataObject;let r=this.table.mergeableDataObjectData;this.keys=r.mergeableDataObjectKeyItem,this.types=r.mergeableDataObjectTypeItem,this.uuids=r.mergeableDataObjectUuidItem.map(this.uuidToString),this.objects=r.mergeableDataObjectEntry}async parse(){let t=this.objects.find(r=>r.customMap&&this.types[r.customMap.type]=="com.apple.notes.ICTable");if(!t)return null;let i=null;for(let r of t.customMap.mapEntry){let o=this.objects[r.value.objectIndex];switch(this.keys[r.key]){case"crRows":[this.rowLocations,this.rowCount]=this.findLocations(o);break;case"crColumns":[this.columnLocations,this.columnCount]=this.findLocations(o);break;case"cellColumns":i=o;break}}return i?await this.computeCells(i):null}findLocations(t){let i=[],r={};for(let o of t.orderedSet.ordering.array.attachment)i.push(this.uuidToString(o.uuid));for(let o of t.orderedSet.ordering.contents.element){let a=this.getTargetUuid(o.key),s=this.getTargetUuid(o.value);r[s]=i.indexOf(a)}return[r,i.length]}async computeCells(t){let i=Array(this.rowCount).fill(0).map(()=>Array(this.columnCount));for(let r of t.dictionary.element){let o=this.columnLocations[this.getTargetUuid(r.key)],a=this.objects[r.value.objectIndex];for(let s of a.dictionary.element){let l=this.rowLocations[this.getTargetUuid(s.key)],c=this.objects[s.value.objectIndex];if(!(l in i)||!c)continue;let p=new Zt(this.importer,c);i[l][o]=await p.format(!0)}}return i}async format(){let t=await this.parse();if(!t)return"";let i=`
`;for(let r=0;r<t.length;r++)i+=`| ${t[r].join(" | ")} |
`,r==0&&(i+=`|${" -- |".repeat(t[0].length)}
`);return i+`
2025-08-30 08:29:39 +08:00
`}getTargetUuid(t){let r=this.objects[t.objectIndex].customMap.mapEntry[0].value.unsignedIntegerValue;return this.uuids[r]}uuidToString(t){return Buffer.from(t).toString("hex")}};jn.protobufType="ciofecaforensics.MergableDataProto";var Md=/(^\s+|(?:\s+)?\n(?:\s+)?|\s+$)/,Qr=/applenotes:note\/([-0-9a-f]+)(?:\?ownerIdentifier=.*)?/,$d=".AppleColorEmojiUI",ps=[100,101,102,103],Zt=class extends vt{constructor(t,i){super(t);this.listNumber=0;this.listIndent=0;this.multiRun=0;this.note=i.note}parseTokens(){let t=0,i=0,r=0,o=[];for(;t<this.note.attributeRun.length;){let a,s="",l=!0;do a=this.note.attributeRun[t],r=r+a.length,s+=this.note.noteText.substring(i,r),i=r,l=t==this.note.attributeRun.length-1?!1:us(a,this.note.attributeRun[t+1]),t++;while(l);for(let c of s.split(Md))c&&o.push({attr:a,fragment:c})}return o}async format(t=!1,i=""){var s;let r=this.parseTokens(),o=!t&&this.importer.omitFirstLine&&this.note.noteText.contains(`
`),a="";for(let l=0;l<r.length;l++){let{attr:c,fragment:p}=r[l];if(o)if(p.contains(`
`)||c.attachmentInfo)o=!1;else continue;c.fragment=p,c.atLineStart=l==0?!0:(s=r[l-1])==null?void 0:s.fragment.contains(`
`),a+=this.formatMultiRun(c),!/\S/.test(c.fragment)||this.multiRun==1?a+=c.fragment:c.attachmentInfo?a+=await this.formatAttachment(c,i):c.superscript||c.underlined||c.color||c.font||this.multiRun==2?a+=await this.formatHtmlAttr(c):a+=await this.formatAttr(c)}return this.multiRun!=0&&(a+=this.formatMultiRun({})),t&&a.replace(`
`,"<br>").replace("|","&#124;"),a.trim()}formatMultiRun(t){var o,a,s,l,c,p;let i=(o=t.paragraphStyle)==null?void 0:o.styleType,r="";switch(this.multiRun){case 3:(((a=t.paragraphStyle)==null?void 0:a.indentAmount)==0&&!ps.includes(i)||Bd(t))&&(this.multiRun=0);break;case 1:i!=4&&(this.multiRun=0,r+="```\n");break;case 2:(s=t.paragraphStyle)!=null&&s.alignment||(this.multiRun=0,r+=`</p>
`);break}if(this.multiRun==0){if(i==4)this.multiRun=1,r+="\n```\n";else if(ps.includes(i))this.multiRun=3,(l=t.paragraphStyle)!=null&&l.indentAmount&&(r+=`
2025-07-05 20:48:33 +08:00
- &nbsp;
`);else if((c=t.paragraphStyle)!=null&&c.alignment){this.multiRun=2;let m=this.convertAlign((p=t==null?void 0:t.paragraphStyle)==null?void 0:p.alignment);r+=`
2025-08-30 08:29:39 +08:00
<p style="text-align:${m};margin:0">`}}return r}async formatHtmlAttr(t){var r,o;t.strikethrough&&(t.fragment=`<s>${t.fragment}</s>`),t.underlined&&(t.fragment=`<u>${t.fragment}</u>`),t.superscript==1&&(t.fragment=`<sup>${t.fragment}</sup>`),t.superscript==-1&&(t.fragment=`<sub>${t.fragment}</sub>`);let i="";switch(t.fontWeight){case 1:t.fragment=`<b>${t.fragment}</b>`;break;case 2:t.fragment=`<i>${t.fragment}</i>`;break;case 3:t.fragment=`<b><i>${t.fragment}</i></b>`;break}return(r=t.font)!=null&&r.fontName&&t.font.fontName!==$d&&(i+=`font-family:${t.font.fontName};`),(o=t.font)!=null&&o.pointSize&&(i+=`font-size:${t.font.pointSize}pt;`),t.color&&(i+=`color:${this.convertColor(t.color)};`),t.link&&!Qr.test(t.link)?(i&&(i=` style="${i}"`),t.fragment=`<a href="${t.link}" rel="noopener" class="external-link" target="_blank"${i}>${t.fragment}</a>`):i&&(t.link&&(t.fragment=await this.getInternalLink(t.link,t.fragment)),t.fragment=`<span style="${i}">${t.fragment}</span>`),t.atLineStart?this.formatParagraph(t):t.fragment}async formatAttr(t){switch(t.fontWeight){case 1:t.fragment=`**${t.fragment}**`;break;case 2:t.fragment=`*${t.fragment}*`;break;case 3:t.fragment=`***${t.fragment}***`;break}return t.strikethrough&&(t.fragment=`~~${t.fragment}~~`),t.link&&t.link!=t.fragment&&(Qr.test(t.link)?t.fragment=await this.getInternalLink(t.link,t.fragment):t.fragment=`[${t.fragment}](${t.link})`),t.atLineStart?this.formatParagraph(t):t.fragment}formatParagraph(t){var a,s,l,c,p,m;let i=" ".repeat(((a=t.paragraphStyle)==null?void 0:a.indentAmount)||0),r=(s=t.paragraphStyle)==null?void 0:s.styleType,o=(l=t.paragraphStyle)!=null&&l.blockquote?"> ":"";switch(this.listNumber!=0&&(r!==102||this.listIndent!==((c=t.paragraphStyle)==null?void 0:c.indentAmount))&&(this.listIndent=((p=t.paragraphStyle)==null?void 0:p.indentAmount)||0,this.listNumber=0),r){case 0:return`${o}# ${t.fragment}`;case 1:return`${o}## ${t.fragment}`;case 2:return`${o}### ${t.fragment}`;case 101:case 100:return`${o}${i}- ${t.fragment}`;case 102:return this.listNumber++,`${o}${i}${this.listNumber}. ${t.fragment}`;case 103:let g=(m=t.paragraphStyle.checklist)!=null&&m.done?"[x]":"[ ]";return`${o}${i}- ${g} ${t.fragment}`}return this.multiRun==3&&(o+=i),`${o}${t.fragment}`}async formatAttachment(t,i){var c,p,m;let r,o,a;switch((c=t.attachmentInfo)==null?void 0:c.typeUti){case"com.apple.notes.inlinetextattachment.hashtag":case"com.apple.notes.inlinetextattachment.mention":return r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT zalttext FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,r.ZALTTEXT;case"com.apple.notes.inlinetextattachment.link":return r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT ztokencontentidentifier FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,await this.getInternalLink(r.ZTOKENCONTENTIDENTIFIER,void 0,i);case"com.apple.notes.table":return r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,a=this.importer.decodeData(r.zhexdata,jn),await a.format();case"public.url":return r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT ztitle, zurlstring FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,`[**${r.ZTITLE}**](${r.ZURLSTRING})`;case"com.apple.notes.gallery":return r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,a=this.importer.decodeData(r.zhexdata,Un),await a.format(!1,i);case"com.apple.paper.doc.scan":case"com.apple.drawing":case"com.apple.drawing.2":case"com.apple.paper":r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT z_pk, zhandwritingsummary
FROM (SELECT *, NULL AS zhandwritingsummary FROM ziccloudsyncingobject)
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,o=r==null?void 0:r.Z_PK;break;default:r=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT zmedia FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${(p=t.attachmentInfo)==null?void 0:p.attachmentIdentifier}`,o=r==null?void 0:r.ZMEDIA;break}if(!o)return` **(unknown attachment: ${(m=t.attachmentInfo)==null?void 0:m.typeUti})** `;let s=await this.importer.resolveAttachment(o,t.attachmentInfo.typeUti),l=s?`
${this.app.fileManager.generateMarkdownLink(s,i)}
`:" **(error reading attachment)**";return this.importer.includeHandwriting&&r.ZHANDWRITINGSUMMARY&&(l=`
2025-07-05 20:48:33 +08:00
> [!Handwriting]-
2025-08-30 08:29:39 +08:00
> ${r.ZHANDWRITINGSUMMARY.replace(`
2025-07-05 20:48:33 +08:00
`,`
2025-08-30 08:29:39 +08:00
> `)}${l}`),l}async getInternalLink(t,i=void 0,r=""){let o=t.match(Qr)[1],a=await this.importer.database.get`
2025-07-05 20:48:33 +08:00
SELECT z_pk FROM ziccloudsyncingobject
2025-08-30 08:29:39 +08:00
WHERE zidentifier = ${o.toUpperCase()}`,s=await this.importer.resolveNote(a.Z_PK);return s?this.app.fileManager.generateMarkdownLink(s,r,void 0,i):"(unknown file link)"}convertColor(t){let i="#";for(let r of Object.values(t))i+=Math.floor(r*255).toString(16);return i}convertAlign(t){switch(t){default:return"left";case 1:return"center";case 2:return"right";case 3:return"justify"}}};Zt.protobufType="ciofecaforensics.Document";function Bd(n){return n.attachmentInfo?!n.attachmentInfo.typeUti.includes("com.apple.notes.inlinetextattachment"):!1}function us(n,e){var t,i;if(!e||n.$type!=e.$type)return!1;for(let r of n.$type.fieldsArray)if(r.name!="length"){if((t=n[r.name])!=null&&t.$type&&((i=e[r.name])!=null&&i.$type)){if(!us(n[r.name],e[r.name]))return!1}else if(n[r.name]!=e[r.name])return!1}return!0}var fs={nested:{ciofecaforensics:{nested:{Color:{fields:{red:{type:"float",id:1},green:{type:"float",id:2},blue:{type:"float",id:3},alpha:{type:"float",id:4}}},AttachmentInfo:{fields:{attachmentIdentifier:{type:"string",id:1},typeUti:{type:"string",id:2}}},Font:{fields:{fontName:{type:"string",id:1},pointSize:{type:"float",id:2},fontHints:{type:"int32",id:3}}},ParagraphStyle:{fields:{styleType:{type:"int32",id:1,options:{default:-1}},alignment:{type:"int32",id:2},indentAmount:{type:"int32",id:4},checklist:{type:"Checklist",id:5},blockquote:{type:"int32",id:8}}},Checklist:{fields:{uuid:{type:"bytes",id:1},done:{type:"int32",id:2}}},DictionaryElement:{fields:{key:{type:"ObjectID",id:1},value:{type:"ObjectID",id:2}}},Dictionary:{fields:{element:{rule:"repeated",type:"DictionaryElement",id:1,options:{packed:!1}}}},ObjectID:{fields:{unsignedIntegerValue:{type:"uint64",id:2},stringValue:{type:"string",id:4},objectIndex:{type:"int32",id:6}}},RegisterLatest:{fields:{contents:{type:"ObjectID",id:2}}},MapEntry:{fields:{key:{type:"int32",id:1},value:{type:"ObjectID",id:2}}},AttributeRun:{fields:{length:{type:"int32",id:1},paragraphStyle:{type:"ParagraphStyle",id:2},font:{type:"Font",id:3},fontWeight:{type:"int32",id:5},underlined:{type:"int32",id:6},strikethrough:{type:"int32",id:7},superscript:{type:"int32",id:8},link:{type:"string",id:9},color:{type:"Color",id:10},attachmentInfo:{type:"AttachmentInfo",id:12}}},NoteStoreProto:{fields:{document:{type:"Document",id:2}}},Document:{fields:{version:{type:"int32",id:2},note:{type:"Note",id:3}}},Note:{fields:{noteText:{type:"string",id:2},attributeRun:{rule:"repeated",type:"AttributeRun",id:5,options:{packed:!1}}}},MergableDataProto:{fields:{mergableDataObject:{type:"MergableDataObject",id:2}}},MergableDataObject:{fields:{version:{type:"int32",id:2},mergeableDataObjectData:{type:"MergeableDataObjectData",id:3}}},MergeableDataObjectData:{fields:{mergeableDataObjectEntry:{rule:"repeated",type:"MergeableDataObjectEntry",id:3,options:{packed:!1}},mergeableDataObjectKeyItem:{rule:"repeated",type:"string",id:4},mergeableDataObjectTypeItem:{rule:"repeated",type:"string",id:5},mergeableDataObjectUuidItem:{rule:"repeated",type:"bytes",id:6}}},MergeableDataObjectEntry:{fields:{registerLatest:{type:"RegisterLatest",id:1},list:{type:"List",id:5},dictionary:{type:"Dictionary",id:6},unknownMessage:{type:"UnknownMergeableDataObjectEntryMessage",id:9},note:{type:"Note",id:10},customMap:{type:"MergeableDataObjectMap",id:13},orderedSet:{type:"OrderedSet",id:16}}},UnknownMergeableDataObjectEntryMessage:{fields:{unknownEntry:{type:"UnknownMergeableDataObjectEntryMessageEntry",id:1}}},UnknownMergeableDataObjectEntryMessageEntry:{fields:{unknownInt1:{type:"int32",id:1},unknownInt2:{type:"int64",id:2}}},MergeableDataObjectMap:{fields:{type:{type:"int32",id:1},mapEntry:{rule:"repeated",type:"MapEntry",id:3,options:{packed:!1}}}},OrderedSet:{fields:{ordering:{type:"OrderedSetOrdering",id:1},elements:{type:"Dictionary",id:2}}},OrderedSetOrdering:{fields:{array:{type:"OrderedSetOrderingArray",id:1},contents:{type:"Dictionary",id:2}}},OrderedSetOrderingArray:{fields:{contents:{type:"Note",id:1},attachment:{rule:"repeated",type:"OrderedSetOrderingArrayAttachment",id:2,options:{packed:!1}}}},OrderedSetOrderingArrayAttachme
`],{type:"text/javascript"}));n({workerScripts:{inflate:[e],deflate:[e]}})}$l(Oi);var K=tn.Platform.isDesktopApp?window.require("node:original-fs"):null,$e=tn.Platform.isDesktopApp?K.promises:null,nn=tn.Platform.isDesktopApp?window.require("node:os"):null,q=tn.Platform.isDesktopApp?window.require("node:path"):null,ni=tn.Platform.isDesktopApp?window.require("node:url"):null,Bl=tn.Platform.isDesktopApp?window.require("node:zlib"):null;function Ki(n,e=0,t=n.byteLength){return n.buffer.slice(n.byteOffset+e,n.byteOffset+e+t)}var Be=class{constructor(e){this.type="file";this.filepath=e;let t=this.name=q.basename(e);this.fullpath=t;let i=q.extname(t);this.extension=i.substring(1).toLowerCase(),this.basename=q.basename(t,i)}async readText(){return $e.readFile(this.filepath,"utf8")}async read(){let e=await $e.readFile(this.filepath);return Ki(e)}async readZip(e){let t=null;try{t=await $e.open(this.filepath,"r");let i=await t.stat();return await e(new Qt(new Do(t,i.size)))}finally{await(t==null?void 0:t.close())}}createReadStream(){return K.createReadStream(this.filepath)}toString(){return this.filepath}},en=class n{constructor(e){this.type="folder";this.filepath=e,this.name=q.basename(e)}async list(){let{filepath:e}=this,t=await $e.readdir(e,{withFileTypes:!0}),i=[];for(let r of t)r.isFile()?i.push(new Be(q.join(e,r.name))):r.isDirectory()&&i.push(new n(q.join(e,r.name)));return i}toString(){return this.filepath}},Vi=class{constructor(e){this.type="file";this.file=e;let t=this.name=e.name;this.fullpath=t;let{basename:i,extension:r}=oe(t);this.basename=i,this.extension=r}readText(){let{file:e}=this;return e.text?e.text():new Promise((t,i)=>{let r=new FileReader;r.addEventListener("load",()=>t(r.result)),r.addEventListener("error",i),r.readAsText(this.file)})}async read(){let{file:e}=this;return e.arrayBuffer?e.arrayBuffer():new Promise((t,i)=>{let r=new FileReader;r.addEventListener("load",()=>t(r.result)),r.addEventListener("error",i),r.readAsArrayBuffer(this.file)})}async readZip(e){return e(new Qt(new Rt(this.file)))}toString(){return this.file.toString()}};async function Io(n,e){let t=[];for(let i of n)try{i.type==="folder"?t.push(...await Io(await i.list(),e)):i.type==="file"&&(!e||e(i))&&t.push(i)}catch(r){console.log("Skipping path: ",i.name,r)}return t}function oe(n){let e=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\")),t=n,i="";e>=0&&(t=n.substring(e+1),i=n.substring(0,e));let[r,o]=Fo(t);return{parent:i,name:t,basename:r,extension:o}}function Fo(n){let e=n.lastIndexOf("."),t=n,i="";return e>0&&(t=n.substring(0,e),i=n.substring(e+1).toLowerCase()),[t,i]}var Do=class extends vn{constructor(e,t){super(e),this.fd=e,this.size=t}async readUint8Array(e,t){let i=Buffer.alloc(t),r=await this.fd.read(i,0,t,e);return new Uint8Array(Ki(i,0,r.bytesRead))}};var Ul=require("obsidian"),Eh=/[\/\?<>\\:\*\|"]/g,Th=/[\x00-\x1f\x80-\x9f]/g,_h=/^\.+$/,Ah=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,kh=/[\. ]+$/,Nh=/^\./,Sh=/[\[\]#|^]/g;function ze(n){return n.replace(Eh,"").replace(Th,"").replace(_h,"").replace(Ah,"").replace(kh,"").replace(Nh,"").replace(Sh,"")}function Tn(n){let e=[];for(let t=0;t<n;t++)e.push((Math.random()*16|0).toString(16));return e.join("")}function dt(n){return new DOMParser().parseFromString(n,"text/html").documentElement}function Rh(n){return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}function Lo(n){return Rh(new TextEncoder().encode(n))}function Xi(n){return Object.isEmpty(n)?"":`---
`+(0,Ul.stringifyYaml)(n)+`---
`}function ii(n,e,t="..."){return n.length<e?n:n.substring(0,e)+t}var Ce=require("obsidian");var jl=300,ue=class{constructor(e,t){this.files=[];this.outputLocation="";this.notAvailable=!1;this.outputFolder=null;this.app=e,this.vault=e.vault,this.modal=t,this.init()}registerAuthCallback(e){this.modal.plugin.registerAuthCallback(e)}addFileChooserSetting(e,t,i=!1){let r=new Ce.Setting(this.modal.contentEl).setName("Files to import").setDesc("Pick the files that you want to import.").addButton(a=>a.setButtonText(i?"Choose files":"Choose file").onClick(async()=>{if(Ce.Platform.isDesktopApp){let s=["openFile","dontAddToRecent"];i&&s.push("multiSelections");let l=window.electron.remote.dialog.showOpenDialogSync({title:"Pick files to import",properties:s,filters:[{name:e,extensions:t}]});l&&l.length>0&&(this.files=l.map(c=>new Be(c)),o())}else{let s=createEl("input");s.type="file",s.accept=t.map(l=>"."+l.toLowerCase()).join(","),s.addEventListener("change",()=>{if(!s.files)return;let l=Array.from(s.files);l.length>0&&(this.files=l.map(c=>new Vi(c)).filter(c=>t.contains(c.extension)),o())}),s.click()}}));i&&Ce.Platform.isDesktopApp&&r.addButton(a=>a.setButtonText("Choose folders").onClick(async()=>{if(Ce.Platform.isDesktopApp){let s=window.electron.remote.dialog.showOpenDialogSync({title:"Pick folders to import",properties:["openDirectory","multiSelections","dontAddToRecent"]});if(s&&s.length>0){r.setDesc("Reading folders...");let l=s.map(c=>new en(c));this.files=await Io(l,c=>t.contains(c.extension)),o()}}}));let o=()=>{let a=document.createDocumentFragment(),s=this.files.length,l=this.files.map(c=>c.name).join(", ");l.length>jl&&(l=l.substring(0,jl)+"..."),a.createEl("span",{text:`These ${s} files will be imported: `}),a.createEl("br"),a.createEl("span",{cls:"u-pop",text:l}),r.setDesc(a)}}addOutputLocationSetting(e){this.outputLocation=e,new Ce.Setting(this.modal.contentEl).setName("Output folder").setDesc("Choose a folder in the vault to put the imported files. Leave empty to output to vault root.").addText(t=>t.setValue(e).onChange(i=>{this.outputLocation=i,this.outputFolder=null}))}async getOutputFolder(){if(this.outputFolder)return this.outputFolder;let{vault:e}=this.app,t=this.outputLocation;t===""&&(t="/");let i=e.getAbstractFileByPath(t);return(i===null||!(i instanceof Ce.TFolder))&&(await e.createFolder(t),i=e.getAbstractFileByPath(t)),i instanceof Ce.TFolder?(this.outputFolder=i,i):null}async getAvailablePathForAttachment(e,t){let i=await this.getOutputFolder(),r=i?{parent:i}:null,{basename:o,extension:a}=oe(e),s=await this.vault.getAvailablePathForAttachments(o,a,r),l=oe(s),c=l.extension?"."+l.extension:"."+a,p=1,m=s;for(;t.includes(m)||this.vault.getAbstractFileByPath(m);)m=q.join(l.parent,`${l.name} ${p}${c}`),p++;return m}async pause(e,t,i){let r=new Promise(o=>setTimeout(o,e*1e3));if(i){let o=i.statusMessage;i.status(`\u23F8\uFE0F Pausing import for ${e} seconds (${t})`),await r,i.status(o)}else await r}sanitizeFilePath(e){return e.replace(/[:|?<>*\\]/g,"")}async createFolders(e){let t=e.split("/").map(o=>o.replace(/^\.+/,"")).join("/"),i=(0,Ce.normalizePath)(t),r=this.vault.getAbstractFileByPathInsensitive(i);if(r&&r instanceof Ce.TFolder)return r;if(await this.vault.createFolder(i),r=this.vault.getAbstractFileByPathInsensitive(i),!(r instanceof Ce.TFolder))throw new Error(`Failed to create folder at "${e}"`);return r}async saveAsMarkdownFile(e,t,i){let r=ze(t);return await this.app.fileManager.createNewMarkdownFile(e,r,i)}};var Kp=Jr(Up());var Ca=require("obsidian");var jp=n=>{let t=vr.execSync(`${n} --version`).toString().toString().match(/(\d+)\.(\d+).(\d+)/);return(t==null?void 0:t[1])>3||(t==null?void 0:t[2])>32},Hp=n=>{let e=[];if(!n)return e;let t=[],i=0,r=-1,o={};for(;i<n.length;){let a="";if(n[i]==="'")for(i++;i<n.length;)if(n[i]!=="'"){let s=n.indexOf("'",i);a+=n.substring(i,s),i=s}else if(n[i+1]==="'")a+=n[i],i+=2;else{i++;break}else if(n[i]==="N")a=null,i+=4;else{let s=Math.min(...[n.indexOf(",",i),n.indexOf(`
2025-07-05 20:48:33 +08:00
`,i)].filter(l=>l>0),n.length-1);a=parseFloat(n.substring(i,s)),i=s}r==-1?t.push(a):(o[t[r]]=a,r++),(n[i]==`
2025-08-30 08:29:39 +08:00
`||t.length<r)&&(r!==-1&&e.push(o),r=0,o={}),i++}return e};function qp(n){for(var e=n[0],t=1,i=arguments.length;t<i;t++)e+=arguments[t]+n[t];return e}var{isArray:jg}=Array,Er=class extends String{},Wp=(n,...e)=>{let t=[n[0]],i=[t];for(let r=0;r<e.length;r++)e[r]instanceof Er?t[t.length-1]+=e[r]+n[r+1]:(jg(e[r])?(t.push(...e[r].slice(1).map(o=>",")),i.push(...e[r].length?e[r]:[""])):i.push(e[r]),t.push(n[r+1]));return i},Yp=n=>new Er(n);var hi=(n,e)=>{let t="SQLITE_ERROR",i=new Error(t+": "+e);return i.code=t,n(i),""},zp=(...n)=>Yp(qp(...n)),{from:Hg}=Array,qg=/'/g,Wg=n=>n.toString(16).padStart(2,"0"),Yg=n=>`x'${Hg(n,Wg).join("")}'`,zg=n=>{switch(typeof n){case"string":return"'"+n.replace(qg,"''")+"'";case"number":if(!isFinite(n))return;case"boolean":return+n;case"object":case"undefined":switch(!0){case!n:return"NULL";case n instanceof Date:return"'"+n.toISOString()+"'";case n instanceof Buffer:case n instanceof ArrayBuffer:n=new Uint8Array(n);case n instanceof Uint8Array:case n instanceof Uint8ClampedArray:return Yg(n)}}},Sa=(n,e)=>{let[t,...i]=Wp(...e),r=[t[0]];for(let a=0;a<i.length;a++){let s=zg(i[a]);if(s===void 0)return hi(n,"incompatible "+typeof s+"value");r.push(s,t[a+1])}let o=r.join("").trim();return o.length?o:hi(n,"empty query")};var Ra=Ca.Platform.isDesktopApp?window.require("node:crypto"):null,vr=Ca.Platform.isDesktopApp?window.require("node:child_process"):null,Da=Ra==null?void 0:Ra.randomUUID(),Zg=`[{"_":"${Da}"}]
`,Gg=`'_'
2025-07-05 20:48:33 +08:00
'${Da}'
2025-08-30 08:29:39 +08:00
`,{isArray:Vg}=Array,{parse:Gp}=JSON,{defineProperty:Kg}=Object,Xg=()=>{},Jg=(n,e,t,i,r,o)=>{let a=[],{stdout:s,stderr:l}=vr.spawn(i,r,o).on("close",p=>{if(c||p!==0){p!==0&&hi(e,"busy DB or query too slow");return}let m=a.join("").trim();if(t==="query")n(m);else{let g=Gp(m||"[]");n(t==="get"&&Vg(g)?g.shift():g)}});s.on("data",p=>{a.push(p)});let c=!1;l.on("data",p=>{c=!0,hi(e,"".trim.call(p))})},Qg=(n,e,t)=>{let i=jp(n),r=i?Zg:Gg,{stdin:o,stdout:a,stderr:s}=vr.spawn(n,e);i?o.write(`.mode json
2025-07-05 20:48:33 +08:00
`):o.write(`.mode quote
.headers on
`),t&&o.write(`.timeout ${t}
`);let l=Promise.resolve();return(c,p,m,g,b)=>{m==="close"?(o.write(`.quit
2025-08-30 08:29:39 +08:00
`),l=null):l&&(l=l.then(()=>new Promise(v=>{let d="",f=T=>{d+=T;let A=!1;for(;d.endsWith(r);)A=!0,d=d.slice(0,-r.length);if(A){for(E();d.startsWith(r);)d=d.slice(r.length);if(m==="query")c(d);else{let O=i?Gp(d||"[]"):Hp(d);c(m==="get"?O.shift():O)}}},h=T=>{E(),p(new Error(T))},E=()=>{v(),a.removeListener("data",f),s.removeListener("data",h)};a.on("data",f),s.once("data",h),o.write(`${b[b.length-1]};
2025-07-05 20:48:33 +08:00
`),o.write(`SELECT '${Da}' as _;
2025-08-30 08:29:39 +08:00
`)})))}},Oa=(n,e,t,i,r)=>(...o)=>new Promise((a,s)=>{let l=Sa(s,o);l.length&&(n==="get"&&/^SELECT\s+/i.test(l)&&!/\s+LIMIT\s+\d+$/i.test(l)&&(l+=" LIMIT 1"),t(a,s,n,e,i.concat(l),r))}),Zp="";function Ia(n,e={}){n===":memory:"&&(n=Zp||(Zp=q.join(nn.tmpdir(),randomUUID())));let t=e.timeout||0,i=e.bin||"sqlite3",r=[n,"-bail"],o={timeout:t};e.readonly&&r.push("-readonly"),t&&r.push("-cmd",".timeout "+t);let a=r.concat("-json"),s=e.exec||(e.persistent?Qg(i,r,t):Jg);return{transaction(){let l=[];return Kg((...c)=>{l.push(c)},"commit",{value(){return new Promise((c,p)=>{let m=["BEGIN TRANSACTION"];for(let g of l){let b=Sa(p,g);if(!b.length)return;m.push(b)}m.push("COMMIT"),s(c,p,"query",i,r.concat(m.join(";")),o)})}})},query:Oa("query",i,s,r,o),get:Oa("get",i,s,a,o),all:Oa("all",i,s,a,o),close:e.persistent?()=>s(null,null,"close"):Xg,raw:zp}}var Fa="Library/Group Containers/group.com.apple.notes",Vp="NoteStore.sqlite",e0=978307200,Tr=class extends ue{constructor(){super(...arguments);this.owners={};this.resolvedAccounts={};this.resolvedFiles={};this.resolvedFolders={};this.multiAccount=!1;this.noteCount=0;this.parsedNotes=0;this.omitFirstLine=!0;this.importTrashed=!1;this.includeHandwriting=!1;this.trashFolders=[]}init(){if(!lt.Platform.isMacOS||!lt.Platform.isDesktop){this.modal.contentEl.createEl("p",{text:"Due to platform limitations, Apple Notes cannot be exported from this device. Open your vault on a Mac to export from Apple Notes."}),this.notAvailable=!0;return}this.addOutputLocationSetting("Apple Notes"),new lt.Setting(this.modal.contentEl).setName("Import recently deleted notes").setDesc('Import notes in the "Recently Deleted" folder. Unlike in Apple Notes, they will not be automatically removed after a set amount of time.').addToggle(t=>t.setValue(!1).onChange(async i=>this.importTrashed=i)),new lt.Setting(this.modal.contentEl).setName("Omit first line").setDesc("Don't include the first line in the text, since Apple Notes uses it as the title. It will still be used as the note name.").addToggle(t=>t.setValue(!0).onChange(async i=>this.omitFirstLine=i)),new lt.Setting(this.modal.contentEl).setName("Include handwriting text").setDesc("When Apple Notes has detected handwriting in drawings, include it as text before the drawing.").addToggle(t=>t.setValue(!1).onChange(async i=>this.includeHandwriting=i))}async getNotesDatabase(){let t=q.join(nn.homedir(),Fa),i=window.electron.remote.dialog.showOpenDialogSync({defaultPath:t,properties:["openDirectory"],message:'Select the "group.com.apple.notes" folder to allow Obsidian to read Apple Notes data.'});if(!(i!=null&&i.includes(t)))return new lt.Notice("Data import failed. Ensure you have selected the correct Apple Notes data folder."),null;let r=q.join(t,Vp),o=q.join(nn.tmpdir(),Vp);return await $e.copyFile(r,o),await $e.copyFile(r+"-shm",o+"-shm"),await $e.copyFile(r+"-wal",o+"-wal"),new Ia(o,{readonly:!0,persistent:!0})}async import(t){if(this.ctx=t,this.protobufRoot=Kp.Root.fromJSON(fs),this.rootFolder=await this.getOutputFolder(),!this.rootFolder){new lt.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(a=>[a.Z_NAME,a.Z_ENT]));let i=await this.database.all`
2025-07-05 20:48:33 +08:00
SELECT z_pk FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICAccount}
`,r=await this.database.all`
SELECT z_pk, ztitle2 FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICFolder}
`;for(let a of i)await this.resolveAccount(a.Z_PK);for(let a of r)try{await this.resolveFolder(a.Z_PK)}catch(s){this.ctx.reportFailed(a.ZTITLE2,s==null?void 0:s.message),console.error(s)}let o=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=o.length;for(let a of o)try{await this.resolveNote(a.Z_PK)}catch(s){this.ctx.reportFailed(a.ZTITLE1,s==null?void 0:s.message),console.error(s)}this.database.close()}async resolveAccount(t){!this.multiAccount&&Object.keys(this.resolvedAccounts).length&&(this.multiAccount=!0);let i=await this.database.get`
SELECT zname, zidentifier FROM ziccloudsyncingobject
WHERE z_ent = ${this.keys.ICAccount} AND z_pk = ${t}
`;this.resolvedAccounts[t]={name:i.ZNAME,uuid:i.ZIDENTIFIER,path:q.join(nn.homedir(),Fa,"Accounts",i.ZIDENTIFIER)}}async resolveFolder(t){var a;if(t in this.resolvedFiles)return this.resolvedFolders[t];let i=await this.database.get`
SELECT ztitle2, zparent, zidentifier, zfoldertype, zowner
FROM ziccloudsyncingobject
WHERE z_ent = ${this.keys.ICFolder} AND z_pk = ${t}
`,r;if(i.ZFOLDERTYPE==3)return null;if(!this.importTrashed&&i.ZFOLDERTYPE==1)return this.trashFolders.push(t),null;if(i.ZPARENT!==null)r=((a=await this.resolveFolder(i.ZPARENT))==null?void 0:a.path)+"/";else if(this.multiAccount){let s=this.resolvedAccounts[i.ZOWNER].name;r=`${this.rootFolder.path}/${s}/`}else r=`${this.rootFolder.path}/`;i.ZIDENTIFIER.startsWith("DefaultFolder")||(r+=ze(i.ZTITLE2));let o=await this.createFolders(r);return this.resolvedFolders[t]=o,this.owners[t]=i.ZOWNER,o}async resolveNote(t){if(t in this.resolvedFiles)return this.resolvedFiles[t];let i=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 = ${t}
2025-08-30 08:29:39 +08:00
`;if(i.ZISPASSWORDPROTECTED)return this.ctx.reportSkipped(i.ZTITLE1,"note is password protected"),null;let r=this.resolvedFolders[i.ZFOLDER]||this.rootFolder,o=`${i.ZTITLE1}.md`,a=await this.saveAsMarkdownFile(r,o,"");this.ctx.status(`Importing note ${o}`),this.resolvedFiles[t]=a,this.owners[t]=this.owners[i.ZFOLDER];let s=this.decodeData(i.zhexdata,Zt);return this.vault.modify(a,await s.format(!1,a.path),{ctime:this.decodeTime(i.ZCREATIONDATE3||i.ZCREATIONDATE2||i.ZCREATIONDATE1),mtime:this.decodeTime(i.ZMODIFICATIONDATE1)}),this.parsedNotes++,this.ctx.reportProgress(this.parsedNotes,this.noteCount),a}async resolveAttachment(t,i){if(t in this.resolvedFiles)return this.resolvedFiles[t];let r,o,a,s,l;switch(i){case"com.apple.paper.doc.scan":s=await this.database.get`
2025-07-05 20:48:33 +08:00
SELECT
zidentifier, zfallbackpdfgeneration, zcreationdate, zmodificationdate, znote
FROM
(SELECT *, NULL AS zfallbackpdfgeneration FROM ziccloudsyncingobject)
WHERE
z_ent = ${this.keys.ICAttachment}
AND z_pk = ${t}
`,r=q.join("FallbackPDFs",s.ZIDENTIFIER,s.ZFALLBACKPDFGENERATION||"","FallbackPDF.pdf"),o="Scan",a="pdf";break;case"com.apple.notes.gallery":s=await this.database.get`
SELECT
zidentifier, zsizeheight, zsizewidth, zcreationdate, zmodificationdate, znote
FROM ziccloudsyncingobject
WHERE
z_ent = ${this.keys.ICAttachment}
AND z_pk = ${t}
`,r=q.join("Previews",`${s.ZIDENTIFIER}-1-${s.ZSIZEWIDTH}x${s.ZSIZEHEIGHT}-0.jpeg`),o="Scan Page",a="jpg";break;case"com.apple.paper":s=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 = ${t}
`,s.ZFALLBACKIMAGEGENERATION?r=q.join("FallbackImages",s.ZIDENTIFIER,s.ZFALLBACKIMAGEGENERATION,"FallbackImage.png"):r=q.join("FallbackImages",`${s.ZIDENTIFIER}.jpg`),o="Drawing",a="png";break;default:s=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 = ${t}
AND a.z_pk = b.zmedia
2025-08-30 08:29:39 +08:00
`,r=q.join("Media",s.ZIDENTIFIER,s.ZGENERATION1||"",s.ZFILENAME),[o,a]=Fo(s.ZFILENAME);break}try{let c=await this.getAttachmentSource(this.resolvedAccounts[this.owners[s.ZNOTE]],r),p=await this.getAvailablePathForAttachment(`${o}.${a}`,[]);l=await this.vault.createBinary(p,c,{ctime:this.decodeTime(s.ZCREATIONDATE),mtime:this.decodeTime(s.ZMODIFICATIONDATE)})}catch(c){return this.ctx.reportFailed(r),console.error(c),null}return this.resolvedFiles[t]=l,this.ctx.reportAttachmentSuccess(this.resolvedFiles[t].path),l}decodeData(t,i){let r=Bl.gunzipSync(Buffer.from(t,"hex")),o=this.protobufRoot.lookupType(i.protobufType).decode(r);return new i(this,o)}decodeTime(t){return!t||t<1?new Date().getTime():Math.floor((t+e0)*1e3)}async getAttachmentSource(t,i){try{return await $e.readFile(q.join(t.path,i))}catch(r){return await $e.readFile(q.join(nn.homedir(),Fa,i))}}};var On=require("obsidian");var gi=class{constructor(e,t){this.type="file";this.entry=t,this.fullpath=e.fullpath+"/"+t.filename;let{parent:i,name:r,basename:o,extension:a}=oe(t.filename);this.parent=i,this.name=r,this.basename=o,this.extension=a}async readText(){return this.entry.getData(new qi)}async read(){return(await this.entry.getData(new Jn)).arrayBuffer()}get filepath(){return this.entry.filename}get size(){return this.entry.uncompressedSize}get ctime(){return this.entry.creationDate}get mtime(){return this.entry.lastModDate}async readZip(e){return e(new Qt(new Rt(new Blob([await this.read()]))))}};async function yt(n,e){await n.readZip(async t=>{let r=(await t.getEntries()).filter(o=>!o.directory&&!!o.getData).map(o=>new gi(n,o));return e(t,r)})}var _r=class extends ue{constructor(){super(...arguments);this.attachmentMap={}}init(){this.addFileChooserSetting("Bear2bk",["bear2bk"]),this.addOutputLocationSetting("Bear")}async import(t){let{files:i}=this;if(i.length===0){new On.Notice("Please pick at least one file to import.");return}let r=await this.getOutputFolder();if(!r){new On.Notice("Please select a location to export to.");return}let o=r,a=new RegExp("\\[[^\\]]*\\]\\((assets/[^\\)]+)\\)","gm"),s=await this.createFolders(`${r.path}/archive`),l=await this.createFolders(`${r.path}/trash`);for(let c of i){if(t.isCancelled())return;t.status("Processing "+c.name),await yt(c,async(p,m)=>{let g=await this.collectMetadata(t,m);for(let b of m){if(t.isCancelled())return;let{fullpath:v,filepath:d,parent:f,name:h,extension:E}=b;if(!(h==="info.json"||h==="tags.json")){t.status("Processing "+h);try{if(E==="md"||E==="markdown"){let T=oe(f).basename;t.status("Importing note "+T);let A=await b.readText();A=this.removeMarkdownHeader(T,A);let O=[...A.matchAll(a)];if(O.length>0)for(let C of O){let[N,P]=C,L=q.join(f,decodeURI(P)),j=await this.getAttachmentStoragePath(L);j=encodeURI(j);let Y=N.replace(P,j);A=A.replace(N,Y)}let _=(0,On.normalizePath)(T),k=g[f],w=o;k!=null&&k.archived?w=s:k!=null&&k.trashed&&(w=l);let D=await this.saveAsMarkdownFile(w,_,A);k!=null&&k.ctime&&(k!=null&&k.mtime)&&await this.modifFileTimestamps(k,D),t.reportNoteSuccess(T)}else if(d.match(/\/assets\//g)){t.status("Importing asset "+b.name);let T=await this.getAttachmentStoragePath(b.filepath),A=await b.read();await this.vault.createBinary(T,A),t.reportAttachmentSuccess(b.fullpath)}else t.reportSkipped(v,"unknown type of file")}catch(T){t.reportFailed(v,T)}}}})}}async modifFileTimestamps(t,i){let r={ctime:t.ctime,mtime:t.mtime};await this.vault.append(i,"",r)}async collectMetadata(t,i){let r={};for(let o of i){if(t.isCancelled())return r;if(o.name!=="info.json")continue;let a=await o.readText(),l=JSON.parse(a)["net.shinyfrog.bear"],c=Date.parse(l.creationDate),p=Date.parse(l.modificationDate);r[o.parent]={ctime:isNaN(c)?void 0:c,mtime:isNaN(p)?void 0:p,archived:l.archived===1,trashed:l.trashed===1}}return r}async getAttachmentStoragePath(t){let i=(0,On.normalizePath)(t);if(this.attachmentMap[i])return this.attachmentMap[i];let r=Object.values(this.attachmentMap),o=await this.getAvailablePathForAttachment(i,r);return o=o.replace(/:/g,""),this.attachmentMap[i]=o,o}removeMarkdownHeader(t,i){if(!i.startsW
`),o=r>0?i.substring(2,r):i.substring(2);return o=o.trim(),o!==t.trim()&&o!==""?i:r>0?i.substring(r+1):""}};var Ti=require("obsidian");var td=require("obsidian");var Xp=require("obsidian");var Jp=n=>({...n,created:yi(n.created),statusupdated:yi(n.statusupdated),updated:yi(n.updated),duedate:yi(n.duedate),taskflag:n.taskflag==="true",reminderdate:n.reminder?yi(n.reminder.reminderdate):void 0,sortweight:n.sortweight}),yi=n=>n?(0,Xp.moment)(n,"YYYYMMDDThhmmssZ").toDate():void 0;var Fu=Jr(du());var de=n=>{let e={get(t,i){return t[i]}};return new Proxy(n.attributes,e)};var mu="\n```\n",$a=n=>{let e=de(n);return e.style&&e.style.value.indexOf("-en-codeblock:true")>=0},u0=n=>{let e=de(n),t="padding-left:",i=0;return e.style&&e.style.value.indexOf(t)>=0&&(i=Math.floor(e.style.value.split(t)[1].split("px")[0]/20)),i},Ba=n=>n.replace(/\\(.)/g,"$1"),hu=(n,e)=>{let t=u0(e);return n=`${" ".repeat(t)}${n}`,$a(e)?(n=Ba(n),`${mu}${n}${mu}`):e.parentElement&&$a(e.parentElement)&&e.parentElement.firstElementChild===e?`${n}`:e.parentElement&&$a(e.parentElement)?`
2025-07-05 20:48:33 +08:00
${n}`:e.isBlock?`
${n}
2025-08-30 08:29:39 +08:00
`:n};var Ar="\n```\n",f0="-en-codeblock:true",d0=/\b(Courier|Mono|Consolas|Console|Inconsolata|Pitch|Monaco|monospace)\b/,gu=n=>{var o,a;if(n.nodeType!==1)return null;let e=n.childNodes,t=e.length;if(t>1)return"mixed";if(t===1){let s=gu(e[0]);if(s)return s}let i=de(n);if(n.tagName==="FONT")return(o=i.face)==null?void 0:o.value;let r=(a=i.style)==null?void 0:a.value;if(r){let s=r.match(/font-family:([^;]+)/);if(s)return s[1]}return null},bi=n=>{var r;let t=(r=de(n).style)==null?void 0:r.value;if(t&&t.includes(f0))return!0;let i=gu(n);return!!i&&d0.test(i)},yu=(n,e)=>{if(bi(e)){let t=e.previousSibling,i=t&&t.tagName===e.tagName&&bi(t),r=e.nextSibling,o=r&&r.tagName===e.tagName&&bi(r);return i||o?(n=i?`
2025-07-05 20:48:33 +08:00
${n}`:`${Ar}${n}`,n=o?`${n}
`:`${n}${Ar}`,n):(n=Ba(n),n.trim()?`${Ar}${n}${Ar}`:n)}return e.parentElement&&bi(e.parentElement)&&e.parentElement.firstElementChild===e?n:e.parentElement&&bi(e.parentElement)?`
${n}`:e.isBlock?`
${n}
2025-08-30 08:29:39 +08:00
`:n};var Ye=n=>e=>e.nodeName===n||e.nodeName.toLowerCase()===n;var bu={filter:Ye("IMG"),replacement:(n,e)=>{let t=de(e);if(!t.src)return"";let i=t.src.value,r=e.width||"",o=e.height||"",a=i;B.sanitizeResourceNameSpaces?a=a.replace(/ /g,B.replacementChar):B.urlEncodeFileNamesAndLinks&&(a=encodeURI(a));let s=r||o?` =${r}x${o}`:"";if(B.keepImageSize)return s=r||o?`|${r||0}x${o||0}`:"",a.startsWith("./")?`![[${a}${s}]]`:`![${s}](${a})`;if(!i.match(/^[a-z]+:/))return`![[${a}]]`;let l=t.src.value.split("/");return`![${l[l.length-1]}](${a})`}};var ke=class n{constructor(){this.noteIdNameMap={},this.noteIdNameTOCMap={}}static getInstance(){return n.instance||(n.instance=new n),n.instance}addItemToMap(e){this.noteIdNameMap[e.url]={...this.noteIdNameMap[e.url],title:e.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:e.uniqueEnd}}addItemToTOCMap(e){this.noteIdNameTOCMap[e.url]={...this.noteIdNameMap[e.url],title:e.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:e.uniqueEnd}}getNoteIdNameMap(){return this.noteIdNameMap}getNoteIdNameTOCMap(){return this.noteIdNameTOCMap}getAllNoteIdNameMap(){return{...this.noteIdNameMap,...this.noteIdNameTOCMap}}getNoteIdNameMapByNoteTitle(e){return Object.values(this.getAllNoteIdNameMap()).filter(t=>t.title===e)}setCurrentNotebookName(e){this.currentNotebookName=e}getCurrentNotebookName(){return this.currentNotebookName}setCurrentNotebookFullpath(e){this.currentNotebookFullpath=e}setCurrentNoteName(e){this.currentNoteName=e}getCurrentNoteName(){return this.currentNoteName}getCurrentNotePath(){return this.currentNotePath}setCurrentNotePath(e){this.currentNotePath=e}getCurrentNotebookFullpath(){return this.currentNotebookFullpath}};var xu=require("obsidian");var Cn=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var m0={"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
2025-07-05 20:48:33 +08:00
`).replace(/\n/gm,`
2025-08-30 08:29:39 +08:00
${Du}`),l=o>0?a:i(e)?`${Rr} `:r(e)?`${Sr} `:"* ",c=e.parentNode;if(c.nodeName==="OL"){let m=c.getAttribute("start"),g=Array.prototype.indexOf.call(c.children,e);l=`${m?Number(m)+g:g+1}. `}let p;return p=l+s+(e.nextSibling&&!/\n$/.test(s)?`
2025-07-05 20:48:33 +08:00
`:""),p}};var Nr=n=>{let e=new window.TurndownService({br:"",...n.turndownOptions,blankReplacement:(t,i)=>i.isBlock?`
`:"",keepReplacement:(t,i)=>i.isBlock?`
${i.outerHTML}
`:i.outerHTML,defaultReplacement:(t,i)=>i.isBlock?`
${t}
2025-08-30 08:29:39 +08:00
`:t});return e.use(Fu.gfm),e.addRule("span",ku),e.addRule("strikethrough",Nu),e.addRule("evernote task items",Su),e.addRule("wikistyle links",_u),e.addRule("images",bu),e.addRule("list",Iu),e.addRule("italic",Cu),n.keepMDCharactersOfENNotes&&(e.escape=t=>t),e.addRule("divBlock",Ou),n.keepOriginalAmountOfNewlines&&e.addRule("newline",Ru),e};var Lu=n=>{n.replaceWith(...Array.from(n.children))},Pu=n=>{let e=n.parentElement;e.replaceWith(...Array.from(e.childNodes)),e.append(...Array.from(n.childNodes)),n.appendChild(e)},C0=n=>(Array.from(n.querySelectorAll("span>en-todo")).forEach(Pu),Array.from(n.querySelectorAll("a>en-todo")).forEach(Pu),n),D0=n=>{let e=n.replace(/<li>/g,"<li><div>");return e=e.replace(/<\/li>/g,"</div></li>"),e=e.replace(/<li><div>(\s)*<div>/g,"<li><div>"),e=e.replace(/<\/div>(\s)*<\/div><\/li>/g,"</div></li>"),e},I0=n=>{var o;let e=Array.from(n.getElementsByTagName("ul")),t=Array.from(n.getElementsByTagName("ol")),i=e.concat(t);i.forEach(a=>{a.parentElement.tagName==="LI"&&a.parentElement.replaceWith(a),a.previousElementSibling&&a.previousElementSibling.tagName==="LI"&&a.previousElementSibling.appendChild(a)});for(let a of i){let s=a.parentElement;(s==null?void 0:s.tagName)==="DIV"&&((o=s==null?void 0:s.parentElement)==null?void 0:o.tagName)==="UL"&&Lu(s),((s==null?void 0:s.tagName)==="UL"||(s==null?void 0:s.tagName)==="OL")&&(s==null?void 0:s.childNodes.length)===1&&Lu(s)}let r=Array.from(n.getElementsByTagName("li"));for(let a of r){let s=a.firstElementChild;if(s&&s.tagName==="DIV"){let l=Array.from(s.childNodes);s.replaceWith(...l)}}return n},Mu=(n,{htmlContent:e})=>{let t=e.replace(/<!DOCTYPE en-note [^>]*>/,"<!DOCTYPE html>").replace(/(<a [^>]*)\/>/,"$1></a>").replace(/<div[^\/\<]*\/>/g,""),i=new DOMParser().parseFromString(D0(t),"text/html").getElementsByTagName("en-note").item(0),r=Nr(n).turndown(C0(I0(i))),o=new RegExp("<YARLE_NEWLINE_PLACEHOLDER>","g");return r=r.replace(o,""),r&&r!=="undefined"?{content:r}:{content:""}};var Rf=Jr(require("crypto"));var bt=require("obsidian");var $u=(n,e)=>({createdAt:F0(n),updatedAt:L0(n),sourceUrl:P0(n),location:M0(n),reminderTime:$0(n),reminderOrder:B0(n),reminderDoneTime:U0(n),notebookName:e});var F0=n=>!B.skipCreationTime&&n.created?(0,bt.moment)(n.created).format(B.dateFormat):"",L0=n=>!B.skipUpdateTime&&n.updated?(0,bt.moment)(n.updated).format(B.dateFormat):"",P0=n=>!B.skipSourceUrl&&n["note-attributes"]?n["note-attributes"]["source-url"]:"",M0=n=>!B.skipLocation&&n["note-attributes"]&&n["note-attributes"].longitude?`${n["note-attributes"].latitude},${n["note-attributes"].longitude}`:"",$0=n=>!B.skipReminderTime&&n["note-attributes"]&&n["note-attributes"]["reminder-time"]?(0,bt.moment)(n["note-attributes"]["reminder-time"]).format(B.dateFormat):"",B0=n=>!B.skipReminderOrder&&n["note-attributes"]&&n["note-attributes"]["reminder-order"]?n["note-attributes"]["reminder-order"]:"",U0=n=>!B.skipReminderDoneTime&&n["note-attributes"]&&n["note-attributes"]["reminder-done-time"]?(0,bt.moment)(n["note-attributes"]["reminder-done-time"]).format(B.dateFormat):"",Bu=n=>({tags:j0(n)}),j0=n=>{if(!B.skipTags&&n.tag){let e=Array.isArray(n.tag)?n.tag:[n.tag],t=B.nestedTags;return e.map(r=>{let o=r.toString().replace(/^#/,"");t&&(o=o.replace(new RegExp(Cn(t.separatorInEN),"g"),t.replaceSeparatorWith));let a=t&&t.replaceSpaceWith||"-";return o=o.replace(/ /g,a),`${B.useHashTags?"#":""}${o}`}).join(" ")}return""},Ha;try{Ha=window.require("btime")}catch(n){}var Or=(n,e)=>{let t=(0,bt.moment)(e.created).valueOf();t>0&&Ha&&Ha.btime(n,t);let r=(0,bt.moment)(e.updated).valueOf()/1e3;try{K.utimesSync(n,r,r)}catch(o){}},Uu=n=>n["resource-attributes"]&&n["resource-attributes"].timestamp?(0,bt.moment)(n["resource-attributes"].timestamp):(0,bt.moment)();var ju=(n,e,t)=>{let i=n.lastIndexOf(e);return i<0?n:n.substring(0,i)+t+n.substring(i+e.length)};var Ne={mdPath:"",resourcePath:""},Dr=249,Hu=(n,e)=>ja(n,e).replace(/\s/g,"_"),qu=(n,e)=>{if(n.length<=11)throw Error("FATAL: note folder directory path exceeds the OS limitation. Please pick a destination closer to the root folder.");ret
2025-07-05 20:48:33 +08:00
|\r|
2025-08-30 08:29:39 +08:00
))*?(?=${i})${i}`;return n.replace(new RegExp(a,"g"),"")};var Bt=(n,e,t,i)=>({template:n,check:e,startBlockPlaceholder:t.START_BLOCK,endBlockPlaceholder:t.END_BLOCK,valuePlaceholder:t.CONTENT_PLACEHOLDER,value:i});var tf=(n,e,t)=>{let i=Bt(e,t,Ya,n.content);return $t(i)};var wi={};Oe(wi,{CONTENT_PLACEHOLDER:()=>G0,END_BLOCK:()=>K0,START_BLOCK:()=>V0});var G0="{tags}",V0="{tags-block}",K0="{end-tags-block}";var nf=(n,e,t)=>{let i=Bt(e,t,wi,n.tags);return $t(i)};var za={};Oe(za,{CONTENT_PLACEHOLDER:()=>X0,END_BLOCK:()=>Q0,START_BLOCK:()=>J0});var X0="{title}",J0="{title-block}",Q0="{end-title-block}";var rf=(n,e,t)=>{let i=Bt(e,t,za,n.title);return $t(i)};var pn={};Oe(pn,{CONTENT_PLACEHOLDER:()=>ey,END_BLOCK:()=>ny,START_BLOCK:()=>ty});var ey="{created-at}",ty="{created-at-block}",ny="{end-created-at-block}";var Te=(n,e,t)=>n.replace(new RegExp(`${e.CONTENT_PLACEHOLDER}`,"g"),t||"").replace(new RegExp(`${e.START_BLOCK}`,"g"),"").replace(new RegExp(`${e.END_BLOCK}`,"g"),"");var of=(n,e)=>Te(e,pn,n.createdAt);var un={};Oe(un,{CONTENT_PLACEHOLDER:()=>iy,END_BLOCK:()=>oy,START_BLOCK:()=>ry});var iy="{updated-at}",ry="{updated-at-block}",oy="{end-updated-at-block}";var af=(n,e)=>Te(e,un,n.updatedAt);var fn={};Oe(fn,{CONTENT_PLACEHOLDER:()=>ay,END_BLOCK:()=>ly,START_BLOCK:()=>sy});var ay="{source-url}",sy="{source-url-block}",ly="{end-source-url-block}";var sf=(n,e)=>Te(e,fn,n.sourceUrl);var dn={};Oe(dn,{CONTENT_PLACEHOLDER:()=>cy,END_BLOCK:()=>uy,START_BLOCK:()=>py});var cy="{location}",py="{location-block}",uy="{end-location-block}";var lf=(n,e)=>Te(e,dn,n.location);var mn={};Oe(mn,{CONTENT_PLACEHOLDER:()=>fy,END_BLOCK:()=>my,START_BLOCK:()=>dy});var fy="{notebook}",dy="{notebook-block}",my="{end-notebook-block}";var cf=(n,e)=>Te(e,mn,n.notebookName);var In={};Oe(In,{CONTENT_PLACEHOLDER:()=>hy,END_BLOCK:()=>yy,START_BLOCK:()=>gy});var hy="{reminder-time}",gy="{reminder-time-block}",yy="{end-reminder-time-block}";var pf=(n,e)=>Te(e,In,n.reminderTime);var Fn={};Oe(Fn,{CONTENT_PLACEHOLDER:()=>by,END_BLOCK:()=>wy,START_BLOCK:()=>xy});var by="{reminder-order}",xy="{reminder-order-block}",wy="{end-reminder-order-block}";var uf=(n,e)=>Te(e,Fn,n.reminderOrder);var Ln={};Oe(Ln,{CONTENT_PLACEHOLDER:()=>vy,END_BLOCK:()=>Ty,START_BLOCK:()=>Ey});var vy="{reminder-done-time}",Ey="{reminder-done-time-block}",Ty="{end-reminder-done-time-block}";var ff=(n,e)=>Te(e,Ln,n.reminderDoneTime);var vi={};Oe(vi,{CONTENT_PLACEHOLDER:()=>_y,END_BLOCK:()=>ky,START_BLOCK:()=>Ay});var _y="{tags-yaml-list}",Ay="{tags-yaml-list-block}",ky="{end-tags-yaml-list-block}";var df=(n,e,t)=>{let i;n.tags&&(i=`
2025-07-05 20:48:33 +08:00
`+n.tags.split(" ").map(o=>` - ${o.replace(/^#/,"")}`).join(`
2025-08-30 08:29:39 +08:00
`));let r=Bt(e,t,vi,i);return $t(r)};var Za="{metadata-block}",Ga="{end-metadata-block}";var mf=`\r?
?`;var me=(n,e)=>n.replace(new RegExp(`${e.START_BLOCK}(?<=${e.START_BLOCK})(.*)(?=${e.END_BLOCK})${e.END_BLOCK}${mf}`,"g"),"");var hf=n=>me(n,pn);var gf=n=>me(n,un);var yf=n=>me(n,fn);var bf=n=>me(n,mn);var xf=n=>me(n,dn);var Ir={};Oe(Ir,{CONTENT_PLACEHOLDER:()=>Sy,END_BLOCK:()=>Oy,START_BLOCK:()=>Ry});var Sy="{link-to-original}",Ry="{link-to-original-block}",Oy="{end-link-to-original-block}";var wf=n=>me(n,Ir);var vf=n=>me(n,In);var Ef=n=>me(n,Ln);var Tf=n=>me(n,Fn);var _f=(n,e)=>{let t=e.currentTemplate;return t=rf(n,t,()=>n.title),t=nf(n,t,()=>!e.skipTags),t=df(n,t,()=>!e.skipTags),t=tf(n,t,()=>n.content),t=wf(t),t=!e.skipCreationTime&&n.createdAt?of(n,t):hf(t),t=!e.skipUpdateTime&&n.updatedAt?af(n,t):gf(t),t=!e.skipSourceUrl&&n.sourceUrl?sf(n,t):yf(t),t=!e.skipLocation&&n.location?lf(n,t):xf(t),t=e.isNotebookNameNeeded&&n.notebookName?cf(n,t):bf(t),t=!e.skipReminderTime&&n.reminderTime?pf(n,t):vf(t),t=!e.skipReminderOrder&&n.reminderOrder?uf(n,t):Tf(t),t=!e.skipReminderDoneTime&&n.reminderDoneTime?ff(n,t):Ef(t),t=t.replace(Za,"").replace(Ga,""),t};var Af=(n,e,t)=>{try{K.writeFileSync(n,e),Or(n,t)}catch(i){throw console.error("Cannot write file ",i),i}};var kf=(n,e)=>{let t=Wu(e);ke.getInstance().setCurrentNotePath(t),Af(t,n,e),console.log(`Note saved to ${t}`)};var Of=n=>{let e=new RegExp(`\\${q.sep}`,"g"),t=Yu(n).replace(e,B.pathSeparator||"/");return{absoluteResourceWorkDir:qa(n),relativeResourceWorkDir:t}},Cf=n=>{let e={},t=n.content,{absoluteResourceWorkDir:i,relativeResourceWorkDir:r}=Of(n);if(console.log(`relative resource work dir: ${r}`),console.log(`absolute resource work dir: ${i}`),zu(n),Array.isArray(n.resource))for(let o of n.resource)e={...e,...Sf(i,o)};else e={...e,...Sf(i,n.resource)};for(let o of Object.keys(e))t=Cy(t,e,o,r);return t},Cy=(n,e,t,i)=>{let r=`${i}${B.pathSeparator}${e[t].fileName.replace(/ /g," ")}`;console.log(`mediaReference src ${r} added`);let o,a=`<en-media ([^>]*)hash="${t}".([^>]*)>`,s=new RegExp(a,"g"),l=n.match(s),c=l&&l.length>0&&l[0].split("type=");if(c&&c.length>1&&c[1].startsWith('"image')){let p=l[0].match(/width="(\w+)"/),m=p?` width="${p[1]}"`:"",g=l[0].match(/height="(\w+)"/),b=g?` height="${g[1]}"`:"";o=n.replace(s,`<img src="${r}"${m}${b} alt="${e[t].fileName}">`)}else o=n.replace(s,`<a href="${r}" type="file">${e[t].fileName}</a>`);return o},Sf=(n,e)=>{let t={},i=e.data.$text,r=Uu(e),a=wu(n,e).fileName,s=`${n}${q.sep}${a}`;console.log(e),console.log(i);let l=Buffer.from(i,"base64");K.writeFileSync(s,l);let c=r.valueOf()/1e3;try{K.utimesSync(s,c,c)}catch(p){}if(e.recognition&&a){let p=e.recognition.match(/[a-f0-9]{32}/);console.log(`resource ${a} added with hash ${p}`),t[p]={fileName:a,alreadyUsed:!1}}else{let p=Rf.default.createHash("md5");p.update(l);let m=p.digest("hex");t[m]={fileName:a,alreadyUsed:!1}}return t},Df=(n,e)=>{if(e.indexOf('src="data:')<0)return e;let{absoluteResourceWorkDir:t,relativeResourceWorkDir:i}=Of(n);return K.mkdirSync(t,{recursive:!0}),e.replace(/src="data:([^;,]*)(;base64)?,([^"]*)"/g,(r,o,a,s)=>{let l=Dy(o,a===";base64",s,t,n);return`src="${`${i}${B.pathSeparator}${l}`}"`})},Dy=(n,e,t,i,r)=>{let o="embedded",a=Iy(n)||".dat",s=xi(i,o),l=s<1?`${o}.${a}`:`${o}.${s}.${a}`,c=`${i}${q.sep}${l}`;return e||(t=decodeURIComponent(t)),K.writeFileSync(c,t,e?"base64":void 0),Or(c,r),console.log(`data url resource ${l} added`),l},Iy=n=>n.split("/").pop().split("+")[0];var If=(n,e)=>{let t=new Date;ke.getInstance().setCurrentNoteName(n.title),Array.isArray(n.content)&&(n.content=n.content.join(""));let r={title:n.title,content:n.content,htmlContent:n.content,originalContent:n.content};console.log(`Converting for note "${r.title}" started at ${t}...`);try{Qu(n)&&(r.htmlContent=Cf(n)),r.htmlContent=Df(n,r.htmlContent),r={...r,...Mu(B,r)},r={...r,...$u(n,e)},r={...r,...Bu(n)};let o=_f(r,B);kf(o,n)}catch(o){throw console.error(`Failed to convert note: ${r.title}`,o),o}finally{let o=new Date,a=(o.getTime()-t.getTime())/1e3;console.log(`Conversion for note "${r.title}" finished at ${o}. Took ${a} seconds`)}};var Pf=require("obsidian");var Ff=n=>n.taskstatus=
`,$y=`{source-url-block}source: {source-url}{end-source-url-block}
`,By=`{tags-yaml-list-block}
2025-07-05 20:48:33 +08:00
tags: {tags-yaml-list}
2025-08-30 08:29:39 +08:00
{end-tags-yaml-list-block}`,Uy=`{content-block}{content}{end-content-block}
`,zf=Yf+By+$y+Yf+Uy;var nb=td.Platform.isDesktopApp?ed():null,Pr={enexSources:[],currentTemplate:"",outputDir:"./mdNotes",isMetadataNeeded:!1,isNotebookNameNeeded:!1,isZettelkastenNeeded:!1,useZettelIdAsFilename:!1,plainTextNotesOnly:!1,skipWebClips:!1,useHashTags:!0,nestedTags:{separatorInEN:"_",replaceSeparatorWith:"/",replaceSpaceWith:"-"},obsidianTaskTag:"",urlEncodeFileNamesAndLinks:!1,sanitizeResourceNameSpaces:!1,replacementChar:"_",pathSeparator:"/",resourcesDir:"_resources",turndownOptions:{headingStyle:"atx"}},ib="@@@",B={...Pr};function rb(n){return n==null?n:JSON.parse(JSON.stringify(n))}function nd(n,...e){for(let t of e)for(let i of Object.keys(t)){let r=t[i],o=n[i];!Array.isArray(r)&&typeof r=="object"&&!Array.isArray(o)&&typeof o=="object"?n[i]=nd({},o,r):n[i]=rb(r)}return n}var ob=n=>{B=nd({},Pr,n);let e=B.templateFile?K.readFileSync(B.templateFile,"utf-8"):zf;e=B.currentTemplate?B.currentTemplate:e,B.skipCreationTime=!Bf(e),B.skipLocation=!Uf(e),B.skipSourceUrl=!Hf(e),B.skipTags=!qf(e),B.skipUpdateTime=!Wf(e),B.isNotebookNameNeeded=jf(e),B.currentTemplate=e,console.log(`Current config is: ${JSON.stringify(B,null,4)}`),console.log(`Path separator:${q.sep}`)},ab=async(n,e,t)=>{if(!(e instanceof Be))throw new Error("Evernote import currently only works on desktop");let i=ke.getInstance();t.status("Processing "+e.name),console.log(`Getting stream from ${e}`);let r=e.createReadStream(),o={},a=i.getCurrentNotebookName();return new Promise((s,l)=>{let c=g=>(t.reportFailed(i.getCurrentNotebookFullpath(),g),l(g)),p=nb(r),m=null;p.on("tag:note-attributes",g=>{m=g}),p.on("tag:note",g=>{if(t.isCancelled()){r.close();return}if(n.skipWebClips&&ef(g))t.reportSkipped(g.title);else{t.status("Importing note "+g.title),m&&(g["note-attributes"]=m);try{If(g,a),t.reportNoteSuccess(a+"/"+g.title)}catch(v){return t.reportFailed(g.title||e,v),s()}}m=null;let b=i.getCurrentNotePath();if(b)for(let v of Object.keys(o)){let d=`<YARLE-EN-V10-TASK>${v}</YARLE-EN-V10-TASK>`,f=K.readFileSync(b,"utf8"),h=new Map([...o[v]].sort()),E=f.replace(d,[...h.values()].join(`
`));K.writeFileSync(b,E)}}),p.on("tag:task",g=>{let b=Jp(g);o[b.taskgroupnotelevelid]||(o[b.taskgroupnotelevelid]=new Map),o[b.taskgroupnotelevelid].set(b.sortweight,Mf(b,a))}),p.on("end",s),p.on("error",c),r.on("error",c)})};async function id(n,e){ob(n);let t=[],i=n.outputDir;for(let r of n.enexSources){if(e.isCancelled())return;let o,a=ke.getInstance();r.basename.includes(ib)?(n.outputDir=Vu(r,n),o=Gu(r),Xu(o,n),a.setCurrentNotebookName(o.basename),a.setCurrentNotebookFullpath(o.fullpath)):(Ku(r,n),a.setCurrentNotebookName(r.basename),a.setCurrentNotebookFullpath(r.fullpath)),await ab(n,r,e),t.push(Wa()),n.outputDir=i}e.isCancelled()||await $f(n,t)}var Mr=class extends ue{init(){this.addFileChooserSetting("Evernote",["enex"],!0),this.addOutputLocationSetting("Evernote")}async import(e){let{files:t}=this;if(t.length===0){new Ti.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Ti.Notice("Please select a location to export to.");return}let{app:r}=this,o=r.vault.adapter;if(!(o instanceof Ti.FileSystemAdapter))return;let a={...Pr,enexSources:t,outputDir:q.join(o.getBasePath(),i.path)};await id(a,e)}};var Se=require("obsidian");var $r=class extends ue{init(){this.addFileChooserSetting("HTML",["htm","html"],!0),this.addAttachmentSizeLimit(0),this.addMinimumImageSize(65),this.addOutputLocationSetting("HTML import")}addAttachmentSizeLimit(e){this.attachmentSizeLimit=e*10**6,new Se.Setting(this.modal.contentEl).setName("Attachment size limit (MB)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>{i.type="number",i.step="0.1"}).setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(Number.isNaN(r)||r<0){t.setValue((this.attachmentSizeLimit/10**6).toString());return}this.attachmentSizeLimit=r*10**6}))}addMinimumImageSize(e){this.minimumImageSize=e,new Se.Setting(this.modal.contentEl).setName("Minimum image size (px)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>i.type="number").setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(!Number.isInteger(r)||r<0){t.setValue(this.minimumImageSize.toString());return}this.minimumImageSize=r}))}async import(e){let{files:t}=this;if(t.length===0){new Se.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Se.Notice("Please select a location to export to.");return}let r=new Map;e.reportProgress(0,t.length);for(let l=0;l<t.length;l++){if(e.isCancelled())return;let c=t[l],p=await this.processFile(e,i,c);p&&r.set(c instanceof Be?ni.pathToFileURL(c.filepath).href:c.name,{file:c,tFile:p}),e.reportProgress(l+1,t.length)}let{metadataCache:o}=this.app,a,s=new Promise(l=>{a=l});o.onCleanCache(async()=>{for(let[l,{file:c,tFile:p}]of r){if(e.isCancelled())break;try{let m=await this.app.vault.cachedRead(p),g=o.computeMetadataAsync?await o.computeMetadataAsync(Lo(m)):o.getFileCache(p);if(!g)continue;let b=[];if(g.links)for(let{link:v,position:d,displayText:f}of g.links){let{path:h,subpath:E}=(0,Se.parseLinktext)(v),T;if(ni){let O=new URL(encodeURI(h),l);O.hash="",O.search="",T=decodeURIComponent(O.href)}else T=oe(h.replace(/#/gu,"%23")).name;let A=r.get(T);if(A){let O=this.app.fileManager.generateMarkdownLink(A.tFile,p.path,E,f);b.push({from:d.start.offset,to:d.end.offset,text:O})}}b.sort((v,d)=>d.from-v.from);for(let v of b)m=m.substring(0,v.from)+v.text+m.substring(v.to);await this.vault.modify(p,m)}catch(m){e.reportFailed(c.fullpath,m)}}a()}),await s}async processFile(e,t,i){e.status("Processing "+i.name);try{let r=await i.readText(),o=dt(r);sb(o);let a=i instanceof Be?ni.pathToFileURL(i.filepath):void 0,s=new Map,l=new Map;for(let m of o.findAll("img, audio, video")){if(e.isCancelled())return;let g=m.getAttribute("src");if(g)try{let b=new URL(g.startsWith("//")?`https:${g}`:g,a),v=b.href,d=s.get(v);s.has(v)||(e.status("Downloading attachment for "+i.name),d=await this.downloadAttachment(t,m,b),s.set(v,d),d?(l.set(d.path,d),e.reportAttachmentSuccess(d.name)):e.reportSkipped(g)),d&&(m.setAttribute("src",d.path.replace(/
`).filter(p=>p!==r);c.length>0&&(a.aliases=c)}let s=[];if(t.color&&t.color!=="DEFAULT"){let c=t.color.toLowerCase();c=od(c),s.push(`Keep/Color/${c}`)}if(t.isPinned&&s.push("Keep/Pinned"),t.attachments&&s.push("Keep/Attachment"),t.isArchived&&s.push("Keep/Archived"),t.isTrashed&&s.push("Keep/Deleted"),t.labels)for(let c of t.labels)s.push(`Keep/Label/${c.name}`);if(s.length>0&&(a.tags=s.map(c=>Qa(c))),o.push(Xi(a)),t.textContent&&(o.push(`
2025-07-05 20:48:33 +08:00
`),o.push(es(t.textContent))),t.listContent){let c=[];for(let p of t.listContent){if(!p.text)continue;let m=`- [${p.isChecked?"X":" "}] ${p.text}`;c.push(es(m))}o.push(`
`),o.push(c.join(`
`))}if(t.attachments){o.push(`
2025-08-30 08:29:39 +08:00
`);for(let c of t.attachments)o.push(`![[${c.filePath}]]`)}let l=await this.saveAsMarkdownFile(i,r,o.join(""));await this.vault.append(l,"",{ctime:t.createdTimestampUsec/1e3,mtime:t.userEditedTimestampUsec/1e3})}};var wt=require("obsidian");var ts=require("obsidian");function ad({info:n,vault:e,targetFolderPath:t,parentsInSubfolders:i}){let r=e.getAllLoadedFiles(),o=new Set,a=new Set(r.map(s=>s.name));i&&yb(n),gb({info:n,pathDuplicateChecks:o,titleDuplicateChecks:a}),bb({info:n,loadedFiles:r,titleDuplicateChecks:a,targetFolderPath:t})}function gb({info:n,pathDuplicateChecks:e,titleDuplicateChecks:t}){for(let i of Object.values(n.idsToFileInfo)){let r=n.getPathForFile(i);if(e.has(`${r}${i.title}`)){let o=2;for(i.title=i.title+" "+o;e.has(`${r}${i.title}`);)o++,i.title=`${i.title.replace(/ \d+$/,"")} ${o}`}t.has(i.title+".md")&&(i.fullLinkPathNeeded=!0),e.add(`${r}${i.title}`),t.add(i.title+".md")}}function yb(n){let e=new Set(Object.values(n.idsToFileInfo).map(t=>t.parentIds).concat(Object.values(n.pathsToAttachmentInfo).map(t=>t.parentIds)).map(t=>t.length>0?t[t.length-1]:""));for(let t of Object.keys(n.idsToFileInfo))e.has(t)&&n.idsToFileInfo[t].parentIds.push(t)}function bb({info:n,loadedFiles:e,titleDuplicateChecks:t,targetFolderPath:i}){var l;let r=new Set(e.filter(c=>!c.path.endsWith(".md")).map(c=>c.path)),o=n.attachmentPath,a=/^\.\//.test(o),s=(l=o.match(/\.\/(.*)/))==null?void 0:l[1];for(let c of Object.values(n.pathsToAttachmentInfo)){t.has(c.nameWithExtension)&&(c.fullLinkPathNeeded=!0);let p="";if(a?p=(0,ts.normalizePath)(`${i}${n.getPathForFile(c)}${s!=null?s:""}`):p=(0,ts.normalizePath)(o+"/"),p.endsWith("/")||(p+="/"),r.has(p+c.nameWithExtension)){let m=2,{basename:g,extension:b}=oe(c.path);for(;r.has(`${p}${g} ${m}.${b}`);)m++;c.nameWithExtension=`${g} ${m}.${b}`}c.targetParentFolder=p,r.add(p+c.nameWithExtension),t.add(c.nameWithExtension)}}var Bn=require("obsidian");var sd=n=>n.replace(/-/g,"").replace(/[ -]?[a-z0-9]{32}(\.|$)/,"$1"),xt=n=>{var e;return(e=n.replace(/-/g,"").match(/([a-z0-9]{32})(\?|\.|$)/))==null?void 0:e[1]},ns=n=>{let{parent:e}=oe(n);return e.split("/").map(t=>xt(t)).filter(t=>t)};function is(n){return n.hour()===0&&n.minute()===0?n.format("YYYY-MM-DD"):n.format("YYYY-MM-DDTHH:mm")}function ld(n){return n.replace(/^(\.\.\/)+/,"")}function cd(n){let e=/#\d*?(?:[-_/a-z]|[^\x00-\x7F])/gi;if(!e.test(n))return n;let t=n.split(`
2025-07-05 20:48:33 +08:00
`);for(let i=0;i<t.length;i++){let r=t[i].match(e);if(!r)continue;let o=t[i];for(let a of r)new RegExp(`\\[\\[[^\\]]*${a}(?:.*[^\\]])?\\]\\]|\\[[^\\]]*${a}[^\\]]*\\]\\([^\\)]*\\)|\\[[^\\]]*\\]\\([^\\)]*${a}[^\\)]*\\)|\\\\${a}|\`[^\`]*${a}[^\`]*\``).test(o)||(o=o.replace(a,"\\"+a));t[i]=o}return n=t.join(`
2025-08-30 08:29:39 +08:00
`),n}function rs(n){n.replaceWith(...Array.from(n.childNodes))}async function xd(n,e){var p;let t=await e.readText(),i=dt(t),r=i.find("div[class=page-body]");if(r===null)throw new Error("page body was not found");let o=ud(n,r);bd(n,o,!0);let a={},s=i.find("table[class=properties] > tbody");if(s){let m=ud(n,s);bd(n,m,!1),Bb(s);for(let g of Array.from(s.rows)){let b=xb(g);b&&(b.title=="Tags"&&(b.title="tags",typeof b.content=="string"?b.content=b.content.replace(/ /g,"-"):b.content instanceof Array&&(b.content=b.content.map(v=>v.replace(/ /g,"-")))),a[b.title]=b.content)}}Rb(r,["strong","em","mark","del"]),kb(r),vb(r),Lb(r),_b(r),Fb(r),Ed(r),gd(r,"div.indented"),gd(r,"details"),Pb(r),yd(r,"ul"),yd(r,"ol"),Mb(r),$b(r),Ib(r),Nb(r);let l=(0,Bn.htmlToMarkdown)(r.innerHTML);n.singleLineBreaks&&(l=l.replace(/\n\n(?!>)/g,`
`)),l=cd(l),l=wb(l);let c=(p=i.find("p[class*=page-description]"))==null?void 0:p.textContent;return c&&(l=c+`
2025-07-05 20:48:33 +08:00
2025-08-30 08:29:39 +08:00
`+l),Xi(a)+l}var pd={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 xb(n){var a,s,l,c,p,m;let e=(a=n.className.match(/property-row-(.*)/))==null?void 0:a[1];if(!e)throw new Error("property type not found for: "+n);let t=(0,Bn.htmlToMarkdown)((s=n.cells[0].textContent)!=null?s:""),i=n.cells[1],r=Object.keys(pd).find(g=>pd[g].includes(e));if(!r)throw new Error("type not found for: "+i);let o="";switch(r){case"checkbox":o=i.innerHTML.includes("checkbox-on");break;case"number":if(o=Number(i.textContent),isNaN(o))return;break;case"date":Ed(i);let g=i.getElementsByTagName("time");if(g.length===0)o="";else if(g.length===1)o=is((0,Bn.moment)((l=g.item(0))==null?void 0:l.textContent));else{let d=[];for(let f=0;f<g.length;f++)d.push(is((0,Bn.moment)((c=g.item(f))==null?void 0:c.textContent)));o=d.join(" - ")}if(o.length===0)return;break;case"list":let b=i.children,v=[];for(let d=0;d<b.length;d++){let f=(p=b.item(d))==null?void 0:p.textContent;f&&v.push(f)}if(o=v,o.length===0)return;break;case"text":if(o=(m=i.textContent)!=null?m:"",o.length===0)return;break}return{title:t,content:o}}function ud(n,e){var i,r;let t=[];for(let o of e.findAll("a")){let a=ld(decodeURI((i=o.getAttribute("href"))!=null?i:"")),s=xt(a),l=Object.keys(n.pathsToAttachmentInfo).find(c=>c.includes(a));s&&a.endsWith(".html")?t.push({type:"relation",a:o,id:s}):l?t.push({type:"attachment",a:o,path:l}):s&&a.startsWith("#")&&((r=o.parentElement)!=null&&r.classList.contains("table_of_contents-item"))&&t.push({type:"toc-item",a:o,id:s})}return t}function wb(n){let e=/\[\[[^\]]*(\\\\)\|[^\]]*\]\]/,t=n.match(new RegExp(e,"g"));return t==null||t.forEach(i=>{n=n.replace(i,i.replace(/\\\\\|/g,"\\|"))}),n}function vb(n){Sb(n,"style"),wd(n,"span.notion-text-equation-token");let e=n.ownerDocument,t=n.findAll("figure.equation");for(let r of t){let o=r.find("annotation");if(!o)continue;let a=e.createElement("div");a.className="annotation",a.appendText(`$$${fd(o.textContent)}$$`),r.replaceWith(a)}let i=n.findAll("span.notion-text-equation-token");for(let r of i){let o=r.find("annotation");o&&r.replaceWith(`$${fd(o.textContent,!0)}$`)}}function fd(n,e=!1){var i;let t=new RegExp(/^(?:\s|\\\\|\\\s)*(.*?)[\s\\]*$/,"s");return(i=n==null?void 0:n.replace(t,"$1").replace(/[\r\n]+/g,e?" ":`
`))!=null?i:""}function Eb(n){var t;let e=(t=n.match(/^[^\.\?\!\n]*[\.\?\!]?/))==null?void 0:t[0];return e!=null?e:""}function Tb(n){var e;return!!/callout|bookmark/.test((e=n.getAttribute("class"))!=null?e:"")}function _b(n){var t;let e=n.ownerDocument;for(let i of n.findAll("figure.callout")){let r=(t=i.lastElementChild)==null?void 0:t.childNodes;if(!r)continue;let o=e.createElement("blockquote");o.append(...Array.from(r)),Ab(o),i.replaceWith(o)}}function Ab(n){var o,a,s;let e=n.firstChild,t=(o=e==null?void 0:e.nodeName)!=null?o:"",i=n.ownerDocument.createElement("p"),r="";t=="#text"?r=(a=e==null?void 0:e.textContent)!=null?a:"":t=="P"?r=e.innerHTML:["EM","STRONG","DEL","MARK"].includes(t)?r=e.outerHTML:n.prepend(i),r=r.replace(/<br>/g,"&lt;br&gt;"),i.innerHTML=`[!important] ${r}`,(s=n.firstChild)==null||s.replaceWith(i)}function kb(n){var e,t,i;for(let r of n.findAll("a.bookmark.source")){let o=r.getAttribute("href"),a=(e=r.find("div.bookmark-title"))==null?void 0:e.textContent,s=Eb((i=(t=r.find("div.bookmark-description"))==null?void 0:t.textContent)!=null?i:""),l=`> [!info] ${a}
2025-07-05 20:48:33 +08:00
> ${s}
> [${o}](${o})
2025-08-30 08:29:39 +08:00
`;r.nextElementSibling&&Tb(r.nextElementSibling)&&(l+=`
`),r.replaceWith(l)}}function Nb(n){var e,t,i;for(let r of n.findAll("span[class=user]"))r.innerText=(e=r.textContent)!=null?e:"";for(let r of n.findAll("td div[class*=checkbox]")){let o=createSpan();o.setText(r.hasClass("checkbox-on")?"X":""),r.replaceWith(o)}for(let r of n.findAll("table span[class*=selected-value]"))((t=r.parentElement)==null?void 0:t.lastElementChild)!==r&&r.setText(r.textContent+", ");for(let r of n.findAll("a[href]"))if(!/^(https?:\/\/|www\.)/.test(r.href)){let o=createSpan();o.setText((i=r.textContent)!=null?i:""),r.replaceWith(o)}}function Sb(n,e){for(let t of n.findAll(e))t.remove()}function Rb(n,e){for(let t of e)Ob(n,t);for(let t of e)Cb(n,t);for(let t of e)wd(n,t);for(let t of e)Db(n,t)}function Ob(n,e){for(let t of n.findAll(e)){if(!t.parentElement||t.parentElement.tagName===e.toUpperCase())continue;let i=t.find(e);for(;i;)rs(i),i=t.find(e)}}function Cb(n,e){let t=n.findAll(e);if(!t)return;let i=new RegExp(`</${e}>( *)<${e}>`,"g");for(let r of t){if(!r||!r.parentElement)continue;let o=r.parentElement,a=o==null?void 0:o.innerHTML;o.innerHTML=a==null?void 0:a.replace(i,"$1")}}function wd(n,e){let t=n.findAll(e);if(t)for(let i of t){let r=i.previousSibling;(r==null?void 0:r.nodeName)=="BR"&&(r==null||r.remove())}}function Db(n,e){let t=n.innerHTML,i=t.match(new RegExp(`<${e}>.*?</${e}>`,"sg"));if(i){for(let r of i.filter(o=>o.includes("<br>")))t=t.replace(r,r.split("<br>").join(`</${e}><br><${e}>`));n.innerHTML=t}}function dd(n){var e;return Number((e=n==null?void 0:n.classList[1].slice(-1))!=null?e:-1)}function vd(n,e){let t=dd(n),i=dd(e);if(t>i&&e.childElementCount==1){let r=createEl("ul");r.append(n),e.append(r)}else if(t>i&&e.childElementCount==2){let r=e.lastElementChild;r==null||r.append(n)}else if(t==i){let r=e.parentElement;r==null||r.append(n)}else t<i&&(e=e.parentElement.parentElement,vd(n,e))}function md(n){var t;let e=createEl("li");return e.className=n.className,e.append((t=n.firstElementChild)!=null?t:""),e}function Ib(n){let e=n.find(".table_of_contents"),t=e==null?void 0:e.children;if(!e||t.length==0)return;let i=createEl("ul"),r=md(t[0]);i.append(r);let o=r;for(let a=1;a<t.length;a++)r=md(t[a]),vd(r,o),o=r;e.replaceWith(i)}function Fb(n){n.innerHTML=n.innerHTML.replace(/(?:\n|<br ?\/>)/g,"<br>");for(let e of n.findAll("code"))for(let t of e.findAll("br"))t.replaceWith(`
`)}function Lb(n){var e;for(let t of n.findAll("link"))t.innerText=(e=t.textContent)!=null?e:""}function Ed(n){var e,t;for(let i of n.findAll("time"))i.textContent=(t=(e=i.textContent)==null?void 0:e.replace(/@/g,""))!=null?t:""}var hd={"1.875em":"h1","1.5em":"h2","1.25em":"h3"};function Pb(n){var t;let e=n.findAll("summary");for(let i of e){let r=i.getAttribute("style");if(r){for(let o of Object.keys(hd))if(r.includes(o)){i.replaceWith(createEl(hd[o],{text:(t=i.textContent)!=null?t:""}));break}}}}function gd(n,e){let t=n.findAll(e);for(let i of t)rs(i)}function Mb(n){for(let e of n.findAll(".language-Mermaid"))e.removeClass("language-Mermaid"),e.addClass("language-mermaid")}function yd(n,e){for(let t of n.findAll(e)){let i=[],r=[],o=t;for(;o.tagName===e.toUpperCase();){i.push(o);for(let s=0;s<o.children.length;s++)r.push(o.children[s]);if(!o.nextElementSibling||o.getAttribute("class")!==o.nextElementSibling.getAttribute("class"))break;o=o.nextElementSibling}let a=n.createEl(e);for(let s of r)a.appendChild(s);i[0].replaceWith(a),i.slice(1).forEach(s=>s.remove())}}function $b(n){for(let e of n.findAll(".checkbox.checkbox-on"))e.replaceWith("[x] ");for(let e of n.findAll(".checkbox.checkbox-off"))e.replaceWith("[ ] ")}function Bb(n){var t;let e=n.findAll("a");if(e.length===0)return n;for(let i of e){let r=createSpan();r.setText((t=i.getAttribute("href"))!=null?t:""),i.replaceWith(r)}}function bd(n,e,t){var i,r,o;for(let a of e){let s=createSpan(),l="";switch(a.type){case"relation":let c=n.idsToFileInfo[a.id];if(c){let g=a.a.closest("table");l=`[[${c.fullLinkPathNeeded?`${n.getPathForFile(c)}${c.title}${g?"\\":""}|${c.title}`:c.title}]]`}else{console.warn("missing relation data for id: "+a.id);let{basename:g}=oe(decodeURI((i=a.a.getAttribute("href"))!=null?i:""));l=`[[${sd(g)}]]`}break;case"attachment":let p=n.pathsToAttachmentInfo[a.path];if(!p){console.warn("missing attachment data for: "+a.path);continue}l=`${t?"!":""}[[${p.fullLinkPathNeeded?p.targetParentFolder+p.nameWithExtension+"|"+p.nameWithExtension:p.nameWithExtension}]]`;break;case"toc-item":l=(r=a.a.textContent)!=null?r:"";let m=(o=l.endsWith("]"))!=null?o:!1;l=`[[#${l+(m?" ":"")}]]`}s.setText(l),a.a.replaceWith(s)}}var Ur=class{constructor(e,t){this.idsToFileInfo={};this.pathsToAttachmentInfo={};this.attachmentPath=e,this.singleLineBreaks=t}getPathForFile(e){let{idsToFileInfo:t}=this,i=e.path.split("/");return e.parentIds.map(r=>{var o,a,s;return(s=(o=t[r])==null?void 0:o.title)!=null?s:(a=i.find(l=>l.contains(r)))==null?void 0:a.replace(` ${r}`,"")}).filter(r=>r).map(r=>r.replace(/[\. ]+$/,"")).join("/")+"/"}};async function _d(n,e){var i,r;let{filepath:t}=e;if(e.extension==="html"){let o=await e.readText(),a=dt(o),l=a.find("body").children,c;for(let v=0;v<l.length&&(c=xt((i=l[v].getAttr("id"))!=null?i:""),!c);v++);if(!c)throw new Error("no id found for: "+t);let p=Td(a,"property-row-created_time"),m=Td(a,"property-row-last_edited_time"),g=((r=a.find("title"))==null?void 0:r.textContent)||"Untitled",b=Ub(ze(g.replace(/\n/g," ").replace(/[:\/]/g,"-").replace(/#/g,"").trim()));n.idsToFileInfo[c]={path:t,parentIds:ns(t),ctime:p,mtime:m,title:b,fullLinkPathNeeded:!1}}else n.pathsToAttachmentInfo[t]={path:t,parentIds:ns(t),nameWithExtension:ze(decodeURIComponent(e.name)),targetParentFolder:"",fullLinkPathNeeded:!1}}function Ub(n){if(n.length<200)return n;let e=n.split(" "),t=[],i=0,r=0,o=!1;for(;i<200;){if(!e[r]){o=!0;break}t.push(e[r]),i+=e[r].length+1,r++}let a=t.join(" ");return o||(a+="..."),a}function jb(n){let e=n.startsWith("@")?n.substr(1).trim():n.trim(),t=new Date(e);return isNaN(t.getTime())?null:t}function Td(n,e){let t=n.querySelector(`tr.${e}`);if(t){let i=t.querySelector("time");return i&&i.textContent?jb(i.textContent):null}return null}var jr=class extends ue{init(){this.parentsInSubfolders=!0,this.addFileChooserSetting("Exported Notion",["zip"]),this.addOutputLocationSetting("Notion"),new wt.Setting(this.modal.contentEl).setName("Save parent pages in subfolders").setDesc("Places the parent database pages in the same folder as the nested content."
2025-07-05 20:48:33 +08:00
Expected state: ${this.graphData.state}
2025-08-30 08:29:39 +08:00
Returned state: ${t.state}`);await this.updateAccessToken(t.code),await this.setSwitchUser(),await this.showSectionPickerUI()}catch(i){console.error("An error occurred while we were trying to sign you in. Error details: ",i),this.modal.contentEl.createEl("div",{text:"An error occurred while trying to sign you in."}).createEl("details",{text:i}).createEl("summary",{text:"Click here to show error details"})}}async setSwitchUser(){let t=await this.fetchResource("https://graph.microsoft.com/v1.0/me","json");this.switchUserSetting.setDesc(`Signed in as ${t.displayName} (${t.mail}). If that's not the correct account, sign in again.`),this.switchUserSetting.settingEl.show(),this.microsoftAccountSetting.settingEl.hide()}async updateAccessToken(t){let i=new URLSearchParams({client_id:Ad,scope:"offline_access "+kd.join(" "),redirect_uri:qr});if(t)i.set("code",t),i.set("grant_type","authorization_code");else{let o=this.retrieveRefreshToken();if(!o)throw new Error("Missing token required for authentication. Please try logging in again.");i.set("refresh_token",o),i.set("grant_type","refresh_token")}let r=await(0,xe.requestUrl)({method:"POST",url:"https://login.microsoftonline.com/common/oauth2/v2.0/token",contentType:"application/x-www-form-urlencoded",body:i.toString()}).json;if(!r.access_token)throw new Error(`Unexpected data was returned instead of an access token. Error details: ${r}`);r.refresh_token&&this.storeRefreshToken(r.refresh_token),this.graphData.accessToken=r.access_token}storeRefreshToken(t){this.refreshToken=t,this.rememberMe&&localStorage.setItem(as,t)}retrieveRefreshToken(){return this.refreshToken?this.refreshToken:localStorage.getItem(as)}clearStoredRefreshToken(){localStorage.removeItem(as)}async showSectionPickerUI(){var o,a;this.loadingArea.show(),this.selectedIds=[];let t="https://graph.microsoft.com/v1.0/me/onenote/notebooks",i=new URLSearchParams({$expand:"sections($select=id,displayName),sectionGroups($expand=sections,sectionGroups)",$select:"id,displayName,lastModifiedDateTime",$orderby:"lastModifiedDateTime DESC"}),r=`${t}?${i.toString()}`;try{this.notebooks=(await this.fetchResource(r,"json-wrapped")).value,this.contentArea.empty(),this.contentArea.createEl("h4",{text:"Choose data to import"});for(let s of this.notebooks){if(((o=s.sectionGroups)==null?void 0:o.length)!==0)for(let c of s.sectionGroups)await this.fetchNestedSectionGroups(c);let l=this.contentArea.createDiv();new xe.Setting(l).setName(s.displayName).setDesc(`Last edited on: ${xe.moment.utc(s.lastModifiedDateTime).format("Do MMMM YYYY")}. Contains ${(a=s.sections)==null?void 0:a.length} sections.`).addButton(c=>c.setCta().setButtonText("Select all").onClick(()=>{l.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach(p=>p.click())})),this.renderHierarchy(s,l)}}catch(s){this.showContentAreaErrorMessage()}this.loadingArea.hide(),this.contentArea.show()}async fetchNestedSectionGroups(t){if(t.sectionGroups=(await this.fetchResource(t.sectionGroupsUrl+"?$expand=sectionGroups($expand=sections),sections","json-wrapped")).value,t.sectionGroups)for(let i=0;i<t.sectionGroups.length;i++)await this.fetchNestedSectionGroups(t.sectionGroups[i])}renderHierarchy(t,i){if(t.sectionGroups)for(let r of t.sectionGroups){let o=i.createDiv({attr:{style:"padding-inline-start: 1em; padding-top: 8px"}});o.createEl("strong",{text:r.displayName}),this.renderHierarchy(r,o)}if(t.sections){let r=i.createEl("ul",{attr:{style:"padding-inline-start: 1em;"}});for(let o of t.sections){let s=r.createEl("li",{cls:"task-list-item"}).createEl("label"),l=s.createEl("input");l.type="checkbox",s.appendChild(document.createTextNode(o.displayName)),s.createEl("br"),l.addEventListener("change",()=>{if(l.checked)this.selectedIds.push(o.id);else{let c=this.selectedIds.findIndex(p=>p===o.id);c!==-1&&this.selectedIds.splice(c,1)}})}}}showContentAreaErrorMessage(){this.contentArea.empty(),this.contentArea.createEl("p",{text:"Microsoft OneNote has limited how fast notes can be imported. Please try again in 1 hour to continue importing."}),this.contentArea.show(),this.loadingArea.
2025-07-05 20:48:33 +08:00
`,1)[0];t.slice(0,-2);let o=t.split(r);if(o.shift(),o.length===2)for(let a of o){let l=a.split(`
`).find(p=>p.includes("Content-Type")).split(";")[0].split(":")[1].trim(),c=a.split(`
`).slice(2).join(`
2025-08-30 08:29:39 +08:00
`).trim();l==="text/html"?i.html=c:l==="application/inkml+xml"&&(i.inkml=c)}else throw new Error("The input string is incorrect and may be missing data. Inputted string: "+t);return i}convertTags(t){var r,o;let i=Array.from(t.querySelectorAll("[data-tag]"));for(let a of i)if((r=a.getAttribute("data-tag"))!=null&&r.contains("to-do")){let l=a.getAttribute("data-tag")==="to-do:completed"?"[x]":"[ ]";a.innerHTML=`- ${l} ${a.innerHTML}`}else{let s=(o=a.getAttribute("data-tag"))==null?void 0:o.split(",");s==null||s.forEach(l=>{a.innerHTML=a.innerHTML+` #${l.replace(":","-")} `})}return t.outerHTML}convertInternalLinks(t){let i=t.findAll("a");for(let r of i)if(r.href.startsWith("onenote:")){let o=r.href.indexOf("#")+1,a=r.href.indexOf("&",o);r.href=r.href.slice(o,a)}return t}getEntityPathNoParent(t,i){for(let r of this.notebooks){let o=this.getEntityPath(t,`${i}/${r.displayName}`,r);if(o)return o}return null}getEntityPath(t,i,r){let o=null;if("sectionGroups"in r&&r.sectionGroups){let a=this.searchSectionGroups(t,i,r.sectionGroups);a!==null&&(o=a)}if("sections"in r&&r.sections){let a=this.searchSectionGroups(t,i,r.sections);a!==null&&(o=a)}if("pages"in r&&r.pages){let a=this.searchPages(t,i,r);a!==null&&(o=a)}return o&&(o=this.sanitizeFilePath(o)),o}searchPages(t,i,r){var a;let o=null;for(let s=0;s<r.pages.length;s++){let l=r.pages[s],c=(a=l.contentUrl.split("page-id=")[1])==null?void 0:a.split("}")[0];if(l.id===t||c===t){if(l.level===0)r.pages[s+1]&&r.pages[s+1].level!==0?o=`${i}/${l.title}`:o=i;else{o=i;for(let p=r.pages.indexOf(l)-1;p>=0;p--)if(r.pages[p].level===l.level-1){o+="/"+r.pages[p].title;break}}break}}return o}searchSectionGroups(t,i,r){let o=null;for(let a of r)if(a.id===t)o=`${i}/${a.displayName}`;else{let s=this.getEntityPath(t,`${i}/${a.displayName}`,a);if(s){o=s;break}}return o}sanitizeOCRText(t){return t=t.replace(/[^\w\d\s]/g,""),t=t.replace(/\s+/g," ").trim(),t.length>50&&(t=t.substring(0,50)+"..."),t}async getAllAttachments(t,i){var l,c,p,m;let r=dt(i.replace(Hb,"<$1$2></$1>")),o=r.findAll("object"),a=r.findAll("img"),s=r.findAll("iframe");for(let g of o){for(;g.firstChild;)(l=g.parentNode)==null||l.insertBefore(g.firstChild,g.nextSibling);let b=g.getAttribute("data-attachment").split("."),v=b[b.length-1];if(!(!$n.contains(v)&&!this.importIncompatibleAttachments)){let d=g.getAttribute("data-attachment"),f=g.getAttribute("data"),h=await this.fetchAttachment(t,d,f),E=document.createElement("p");E.innerText=`![[${h}]]`,(c=g.parentNode)==null||c.replaceChild(E,g)}}for(let g=0;g<a.length;g++){let b=a[g],d=b.getAttribute("data-fullres-src-type").split("/")[1],h=`Exported image ${(0,xe.moment)().format("YYYYMMDDHHmmss")}-${g}.${d}`,E=b.getAttribute("data-fullres-src"),T=await this.fetchAttachment(t,h,E);T&&(b.src=encodeURI(T),!b.alt||Wb.test(b.alt)?b.alt="Exported image":b.alt=this.sanitizeOCRText(b.alt)||"Exported image")}for(let g of s)if(g.src.contains("youtube.com")||g.src.contains("youtu.be")){let b=document.createTextNode(`![Embedded YouTube video](${g.src})`);(p=g.parentNode)==null||p.replaceChild(b,g)}else{let b=document.createElement("a");b.href=g.src,(m=g.parentNode)==null||m.replaceChild(b,g)}return r}async fetchAttachment(t,i,r){this.attachmentDownloadPauseCounter===7&&await new Promise(o=>{t.status("Pausing attachment download to avoid rate limiting."),this.attachmentDownloadPauseCounter=0,setTimeout(o,3e3)}),this.attachmentDownloadPauseCounter++,t.status("Downloading attachment "+i);try{let o=await this.getAvailablePathForAttachment(i,[]),a=await this.fetchResource(r,"file",t);return await this.app.vault.createBinary(o,a),t.reportAttachmentSuccess(i),o}catch(o){t.reportFailed(i),console.error(o)}}styledElementToHTML(t){let i={"font-weight:bold":"b","font-style:italic":"i","text-decoration:underline":"u","text-decoration:line-through":"s","background-color":"mark"};t.findAll("cite").forEach(l=>l.innerHTML="> "+l.innerHTML+"<br>");let o=!1,a=document.createElement("pre");return t.querySelectorAll("*").forEach(l=>{let c=l.getAttribute("style")||"",p=Object.keys(i).find(m=>c.includes(m));if(c!=null&&c.c
`),k=_.findIndex(w=>w.contains("* "+E));k!==-1&&(_[k]=_[k].replace(E,T)),b.set(A,_.join(`
`))}}let{vault:v}=this,d=b.size,f=1;for(let[h,E]of b.entries()){if(t.isCancelled())return;try{let{parent:T}=oe(h);await this.createFolders(T);let A=v.getAbstractFileByPath(h);A?await v.modify(A,E):await v.create(h,E),t.reportNoteSuccess(h),t.reportProgress(f,d)}catch(T){console.error("Error saving Markdown to file:",h,T),t.reportFailed(h)}f++}}}getUserDNPFormat(){let t=this.app.internalPlugins.getPluginById("daily-notes").instance;return t?t.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(t){let i=new Map,r=new Map,o=this.userDNPFormat;function a(s,l){if(l.uid){let c=new Date(s.uid);if(!isNaN(c.getTime())){let g=Yr(s.title,o);s.title=g}let p={pageName:Wr(s.title),blockString:l.string};/.*?(\(\(.*?\)\)).*?/g.test(l.string)&&r.set(l.uid,p),i.set(l.uid,p)}if(l.children)for(let c of l.children)a(s,c)}for(let s of t)if(s.children)for(let l of s.children)a(s,l);return[i,r]}async roamMarkupScrubber(t,i,r,o=!1){return r=r.replace(i1,""),r.substring(0,8)==":hiccup "&&r.includes(":hr")?"---":(r=r.replace(/\[\[(.*?)\]\]/g,(a,s)=>`[[${Yr(Wr(s),this.userDNPFormat)}]]`),r=r.replace(/\[\[(.*\/.*)\]\]/g,(a,s)=>`[[${t}/${s}|${s}]]`),r=r.replace(/\[.+?\]\((\(.+?\)\))\)/g,"$1"),r=r.replace(/\[(.+?)\]\(\[\[(.+?)\]\]\)/g,"[[$2|$1]]"),r=r.replace(/\[\[>\]\]/g,">"),r=r.replace(/{{TODO}}|{{\[\[TODO\]\]}}/g,"[ ]"),r=r.replace(/{{DONE}}|{{\[\[DONE\]\]}}/g,"[x]"),r=r.replace("::",":"),r=r.replace(/{{.*?\bvideo\b.*?(\bhttp.*?\byoutu.*?)}}/g,"![]($1)"),r=r.replace(/(https?:\/\/twitter\.com\/(?:#!\/)?\w+\/status\/\d+(?:\?[\w=&-]+)?)/g,"![]($1)"),r=r.replace(/\_\_(.+?)\_\_/g,"*$1*"),r=r.replace(/\^\^(.+?)\^\^/g,"==$1=="),r=r.replace(/{{\[{0,2}embed.*?(\(\(.*?\)\)).*?}}/g,"$1"),r=r.replace(/{{\[{0,2}embed.*?(\[\[.*?\]\]).*?}}/g,"$1"),this.downloadAttachments&&!o&&r.includes("firebasestorage")&&(r=await this.downloadFirebaseFile(r,i)),r)}async jsonToMarkdown(t,i,r,o="",a=!1,s,l,c){let p=[],m=[],g=r["edit-time"],b=r["create-time"];if(this.newestTimestamp<this.oldestTimestamp&&(this.oldestTimestamp=this.newestTimestamp),this.newestTimestamp=!g||c>g?c:g,b!==void 0?l>10?this.oldestTimestamp=Math.min(l,b):this.oldestTimestamp=b:this.oldestTimestamp=l,"string"in r&&r.string){let v=r.heading?"#".repeat(r.heading)+" ":"",d=await this.roamMarkupScrubber(t,i,r.string);p.push(`${a?o+"* ":o}${v}${d}`)}if(r.children)for(let v of r.children)p.push(await this.jsonToMarkdown(t,i,v,o+" ",!0,"",this.oldestTimestamp,this.newestTimestamp));if((this.fileDateYAML||this.titleYAML)&&!a){let v=this.oldestTimestamp;if(m.push("---"),this.titleYAML&&m.push(`title: "${s}"`),this.fileDateYAML){let d="YYYY-MM-DD HH:mm:ss",f=this.newestTimestamp?(0,zr.moment)(this.newestTimestamp).format(d):(0,zr.moment)(new Date).format(d),h=v?(0,zr.moment)(v).format(d):f;m.push("created: "+h),m.push("updated: "+f)}m.push("---"),p.unshift(m.join(`
2025-07-05 20:48:33 +08:00
`))}return p.join(`
`)}async modifySourceBlockString(t,i,r,o){if(!i.blockString.endsWith("^"+o)){let a=`${r}/${i.pageName}.md`,s=t.get(a);if(s){let l=s.split(`
`),c=l.findIndex(p=>p.contains("* "+i.blockString));if(c!==-1){let p=i.blockString+" ^"+o;l[c]=l[c].replace(i.blockString,p),i.blockString=i.blockString+" ^"+o}t.set(a,l.join(`
2025-08-30 08:29:39 +08:00
`))}}}async extractAndProcessBlockReferences(t,i,r,o){let a=o.match(a1);if(!a)return o;let s=[];for(let p of a)try{let m=i.get(p);if(!m){s.push(p);continue}let g=m.blockString.replace(/\[\[|\]\]/g,""),b=`[[${r}/${m.pageName}#^${p}|${g}]]`;await this.modifySourceBlockString(t,m,r,p),s.push(b)}catch(m){s.push(p)}let l=0;return o.replace(/\(\(\b.*?\b\)\)/g,()=>s[l++])}async downloadFirebaseFile(t,i){let{progress:r,vault:o}=this,a="";try{let s,l;if(r1.test(t)?(s=t.match(/https:\/\/firebasestorage(.*?)\?alt(.*?)\}/),l=t.match(/{{.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):Rd.test(t)?(s=t.match(Rd),l=t.match(/!\[.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):(s=t.match(o1),l=t.match(/https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)),s&&l){let c="https://firebasestorage"+s[1],p=decodeURIComponent(c.split("/").last()||"");if(p){let d=p.split("/");d.length>1&&(d.splice(-1,1),this.createFolders(`${i}/${d.join("/")}`))}else{let d=Math.floor(Date.now()/1e3),f=c.slice(-5).match(/(.*?)\.(.+)/);if(!f)return r.reportSkipped(s[1],"Unexpected file extension"),t;p=`${d}.${f[2]}`}let m=`${i}/${p}`;if(o.getAbstractFileByPath(m))return r.reportSkipped(s[1],"File already exists"),t;a=s[0].slice(0,-1);let v=await(await fetch(a,{})).arrayBuffer();return await o.createBinary(m,v),r.reportAttachmentSuccess(a),t.replace(l[0],`![[${m}]]`)}}catch(s){console.error(s),r.reportFailed(a,s)}return t}};var qt=require("obsidian");var Od=/!\[\]\(assets\/([^)]*)\)/g,Gr=class extends ue{init(){qt.Platform.isMacOS||this.modal.contentEl.createEl("p",{text:"Due to platform limitations, only textpack and zip files can be imported from this device. Open your vault on a Mac to import textbundle files."});let e=qt.Platform.isMacOS?["textbundle","textpack","zip"]:["textpack","zip"];this.addFileChooserSetting("Textbundle",e,!0),this.addOutputLocationSetting("Textbundle")}async import(e){let{files:t}=this;if(t.length===0){new qt.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new qt.Notice("Please select a location to export to.");return}this.attachmentsFolderPath=await this.createFolders(`${i.path}/assets`);for(let r of t)if(r.extension==="textpack")await yt(r,async(o,a)=>{await this.process(e,r.name,a)});else if(r.extension==="zip")await yt(r,async(o,a)=>{let s=this.groupFilesByTextbundle(r.name,a);for(let l of s)await this.process(e,r.name,l)});else{let a=await new en(`${r.toString()}/`).list();await this.process(e,r.name,a)}}groupFilesByTextbundle(e,t){let i={},r=e+"/",o=".textbundle";for(let a of t){if(!a.fullpath.startsWith(r)){console.log("Skipping",a.fullpath);continue}let s=a.fullpath.slice(r.length);if(s.startsWith("._")||s.startsWith("__MACOSX")){console.log("Skipping",a.fullpath);continue}let l=s.indexOf(o);if(l===-1){console.log("Skipping",a.fullpath);continue}let c=s.slice(0,l)+".textbundle";if(s.slice(l+o.length+1).startsWith("._")){console.log("Skipping",a.fullpath);continue}c in i?i[c].push(a):i[c]=[a]}return Object.values(i)}async process(e,t,i){let r=i.find(o=>o.name==="info.json");if(r){let o=await r.readText(),a=JSON.parse(o);if(a.hasOwnProperty("type")&&a.type!=="net.daringfireball.markdown"){e.reportSkipped(t,"The textbundle does not contain markdown");return}}for(let o of i)if(!o.name.startsWith("._"))try{if(o.type==="file"&&(o.extension==="md"||o.extension==="markdown")){let a="parent"in o?o.parent:t;a=a.replace(/.textbundle$/,"");let s=await o.readText();s.match(Od)&&(s=s.replace(Od,`![[${this.attachmentsFolderPath.path}/$1]]`));let l=(0,qt.normalizePath)(a),c=await this.getOutputFolder();await this.saveAsMarkdownFile(c,l,s),e.reportNoteSuccess(a)}else if(o.type==="file"&&o.fullpath.contains("assets/"))await this.importAsset(e,o);else if(o.type==="folder"){let{basename:a}=oe(o.toString());if(a!=="assets")continue;let l=await new en(`${o.toString()}/`).list();for(let c of l)await this.importAsset(e,c)}else o.name!=="info.json"&&e.reportSkipped(o.name,"the file is not a media or markdown file.")}catch(a){e.reportFailed(o.name,a)}}async importAsset(e,t){if(t.type==="folder"
2025-07-05 20:48:33 +08:00
/*! Bundled license information:
sax/lib/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
*/
/* nosourcemap */