mirror of
https://github.com/logseq/logseq.git
synced 2026-05-16 17:02:34 +00:00
32 lines
114 KiB
JavaScript
32 lines
114 KiB
JavaScript
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports):typeof define==`function`&&define.amd?define([`exports`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.LSPlugin={}))})(this,function(e){var t=globalThis,n=globalThis.process||{env:{},platform:`browser`,cwd:()=>`/`,noDeprecation:!1,throwDeprecation:!1,traceDeprecation:!1,pid:0};n.env||={},n.cwd||=function(){return`/`},n.platform||=`browser`,n.noDeprecation||=!1,n.throwDeprecation||=!1,n.traceDeprecation||=!1,n.pid||=0,Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),u=(e,t)=>{let n={};for(var r in e)i(n,r,{get:e[r],enumerable:!0});return t||i(n,Symbol.toStringTag,{value:`Module`}),n},d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var s=o(t),l=0,u=s.length,d;l<u;l++)d=s[l],!c.call(e,d)&&d!==n&&i(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=a(t,d))||r.enumerable});return e},f=(e,t,n)=>(n=e==null?{}:r(s(e)),d(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)),p=f(l(((e,t)=>{var n=Object.prototype.hasOwnProperty,r=`~`;function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function a(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(e,t,n,i,o){if(typeof n!=`function`)throw TypeError(`The listener must be a function`);var s=new a(n,i||e,o),c=r?r+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function s(e,t){--e._eventsCount===0?e._events=new i:delete e._events[t]}function c(){this._events=new i,this._eventsCount=0}c.prototype.eventNames=function(){var e=[],t,i;if(this._eventsCount===0)return e;for(i in t=this._events)n.call(t,i)&&e.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e},c.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,a=n.length,o=Array(a);i<a;i++)o[i]=n[i].fn;return o},c.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},c.prototype.emit=function(e,t,n,i,a,o){var s=r?r+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,i),!0;case 5:return c.fn.call(c.context,t,n,i,a),!0;case 6:return c.fn.call(c.context,t,n,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,n);break;case 4:c[d].fn.call(c[d].context,t,n,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},c.prototype.on=function(e,t,n){return o(this,e,t,n,!1)},c.prototype.once=function(e,t,n){return o(this,e,t,n,!0)},c.prototype.removeListener=function(e,t,n,i){var a=r?r+e:e;if(!this._events[a])return this;if(!t)return s(this,a),this;var o=this._events[a];if(o.fn)o.fn===t&&(!i||o.once)&&(!n||o.context===n)&&s(this,a);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==t||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[a]=l.length===1?l[0]:l:s(this,a)}return this},c.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&s(this,t)):(this._events=new i,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=r,c.EventEmitter=c,t!==void 0&&(t.exports=c)}))(),1),m=p.default,h=l(((e,t)=>{t.exports=function(e){return e&&typeof e==`object`&&typeof e.copy==`function`&&typeof e.fill==`function`&&typeof e.readUInt8==`function`}})),g=l(((e,t)=>{typeof Object.create==`function`?t.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:t.exports=function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}})),_=l((e=>{var t=/%[sdj%]/g;e.format=function(e){if(!x(e)){for(var n=[],r=0;r<arguments.length;r++)n.push(i(arguments[r]));return n.join(` `)}for(var r=1,a=arguments,o=a.length,s=String(e).replace(t,function(e){if(e===`%%`)return`%`;if(r>=o)return e;switch(e){case`%s`:return String(a[r++]);case`%d`:return Number(a[r++]);case`%j`:try{return JSON.stringify(a[r++])}catch{return`[Circular]`}default:return e}}),c=a[r];r<o;c=a[++r])v(c)||!w(c)?s+=` `+c:s+=` `+i(c);return s},e.deprecate=function(t,n){if(S({env:{},platform:`browser`,cwd:()=>`/`,noDeprecation:!1,throwDeprecation:!1,traceDeprecation:!1,pid:0}))return function(){return e.deprecate(t,n).apply(this,arguments)};var r=!1;function i(){return r||=(console.error(n),!0),t.apply(this,arguments)}return i};var n={},r;e.debuglog=function(t){if(S(r)&&(r=``),t=t.toUpperCase(),!n[t])if(RegExp(`\\b`+t+`\\b`,`i`).test(r)){var i=0;n[t]=function(){var n=e.format.apply(e,arguments);console.error(`%s %d: %s`,t,i,n)}}else n[t]=function(){};return n[t]};function i(t,n){var r={seen:[],stylize:o};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),_(n)?r.showHidden=n:n&&e._extend(r,n),S(r.showHidden)&&(r.showHidden=!1),S(r.depth)&&(r.depth=2),S(r.colors)&&(r.colors=!1),S(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=a),c(r,t,r.depth)}e.inspect=i,i.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},i.styles={special:`cyan`,number:`yellow`,boolean:`yellow`,undefined:`grey`,null:`bold`,string:`green`,date:`magenta`,regexp:`red`};function a(e,t){var n=i.styles[t];return n?`\x1B[`+i.colors[n][0]+`m`+e+`\x1B[`+i.colors[n][1]+`m`:e}function o(e,t){return e}function s(e){var t={};return e.forEach(function(e,n){t[e]=!0}),t}function c(t,n,r){if(t.customInspect&&n&&re(n.inspect)&&n.inspect!==e.inspect&&!(n.constructor&&n.constructor.prototype===n)){var i=n.inspect(r,t);return x(i)||(i=c(t,i,r)),i}var a=l(t,n);if(a)return a;var o=Object.keys(n),h=s(o);if(t.showHidden&&(o=Object.getOwnPropertyNames(n)),ne(n)&&(o.indexOf(`message`)>=0||o.indexOf(`description`)>=0))return u(n);if(o.length===0){if(re(n)){var g=n.name?`: `+n.name:``;return t.stylize(`[Function`+g+`]`,`special`)}if(C(n))return t.stylize(RegExp.prototype.toString.call(n),`regexp`);if(te(n))return t.stylize(Date.prototype.toString.call(n),`date`);if(ne(n))return u(n)}var _=``,v=!1,y=[`{`,`}`];if(m(n)&&(v=!0,y=[`[`,`]`]),re(n)&&(_=` [Function`+(n.name?`: `+n.name:``)+`]`),C(n)&&(_=` `+RegExp.prototype.toString.call(n)),te(n)&&(_=` `+Date.prototype.toUTCString.call(n)),ne(n)&&(_=` `+u(n)),o.length===0&&(!v||n.length==0))return y[0]+_+y[1];if(r<0)return C(n)?t.stylize(RegExp.prototype.toString.call(n),`regexp`):t.stylize(`[Object]`,`special`);t.seen.push(n);var b=v?d(t,n,r,h,o):o.map(function(e){return f(t,n,r,h,e,v)});return t.seen.pop(),p(b,_,y)}function l(e,t){if(S(t))return e.stylize(`undefined`,`undefined`);if(x(t)){var n=`'`+JSON.stringify(t).replace(/^"|"$/g,``).replace(/'/g,`\\'`).replace(/\\"/g,`"`)+`'`;return e.stylize(n,`string`)}if(b(t))return e.stylize(``+t,`number`);if(_(t))return e.stylize(``+t,`boolean`);if(v(t))return e.stylize(`null`,`null`)}function u(e){return`[`+Error.prototype.toString.call(e)+`]`}function d(e,t,n,r,i){for(var a=[],o=0,s=t.length;o<s;++o)le(t,String(o))?a.push(f(e,t,n,r,String(o),!0)):a.push(``);return i.forEach(function(i){i.match(/^\d+$/)||a.push(f(e,t,n,r,i,!0))}),a}function f(e,t,n,r,i,a){var o,s,l=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]};if(l.get?s=l.set?e.stylize(`[Getter/Setter]`,`special`):e.stylize(`[Getter]`,`special`):l.set&&(s=e.stylize(`[Setter]`,`special`)),le(r,i)||(o=`[`+i+`]`),s||(e.seen.indexOf(l.value)<0?(s=v(n)?c(e,l.value,null):c(e,l.value,n-1),s.indexOf(`
|
|
`)>-1&&(s=a?s.split(`
|
|
`).map(function(e){return` `+e}).join(`
|
|
`).substr(2):`
|
|
`+s.split(`
|
|
`).map(function(e){return` `+e}).join(`
|
|
`))):s=e.stylize(`[Circular]`,`special`)),S(o)){if(a&&i.match(/^\d+$/))return s;o=JSON.stringify(``+i),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,`name`)):(o=o.replace(/'/g,`\\'`).replace(/\\"/g,`"`).replace(/(^"|"$)/g,`'`),o=e.stylize(o,`string`))}return o+`: `+s}function p(e,t,n){var r=0;return e.reduce(function(e,t){return r++,t.indexOf(`
|
|
`)>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,``).length+1},0)>60?n[0]+(t===``?``:t+`
|
|
`)+` `+e.join(`,
|
|
`)+` `+n[1]:n[0]+t+` `+e.join(`, `)+` `+n[1]}function m(e){return Array.isArray(e)}e.isArray=m;function _(e){return typeof e==`boolean`}e.isBoolean=_;function v(e){return e===null}e.isNull=v;function y(e){return e==null}e.isNullOrUndefined=y;function b(e){return typeof e==`number`}e.isNumber=b;function x(e){return typeof e==`string`}e.isString=x;function ee(e){return typeof e==`symbol`}e.isSymbol=ee;function S(e){return e===void 0}e.isUndefined=S;function C(e){return w(e)&&ae(e)===`[object RegExp]`}e.isRegExp=C;function w(e){return typeof e==`object`&&!!e}e.isObject=w;function te(e){return w(e)&&ae(e)===`[object Date]`}e.isDate=te;function ne(e){return w(e)&&(ae(e)===`[object Error]`||e instanceof Error)}e.isError=ne;function re(e){return typeof e==`function`}e.isFunction=re;function ie(e){return e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`||typeof e==`symbol`||e===void 0}e.isPrimitive=ie,e.isBuffer=h();function ae(e){return Object.prototype.toString.call(e)}function oe(e){return e<10?`0`+e.toString(10):e.toString(10)}var se=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function ce(){var e=new Date,t=[oe(e.getHours()),oe(e.getMinutes()),oe(e.getSeconds())].join(`:`);return[e.getDate(),se[e.getMonth()],t].join(` `)}e.log=function(){console.log(`%s - %s`,ce(),e.format.apply(e,arguments))},e.inherits=g(),e._extend=function(e,t){if(!t||!w(t))return e;for(var n=Object.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e};function le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}})),v=f(l(((e,t)=>{var r=!1,i=_();function a(e,t){for(var n=[],r=0;r<e.length;r++){var i=e[r];!i||i===`.`||(i===`..`?n.length&&n[n.length-1]!==`..`?n.pop():t&&n.push(`..`):n.push(i))}return n}function o(e){for(var t=e.length-1,n=0;n<=t&&!e[n];n++);for(var r=t;r>=0&&!e[r];r--);return n===0&&r===t?e:n>r?[]:e.slice(n,r+1)}var s=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,c=/^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/,l={};function u(e){var t=s.exec(e),n=(t[1]||``)+(t[2]||``),r=t[3]||``,i=c.exec(r);return[n,i[1],i[2],i[3]]}function d(e){var t=s.exec(e),n=t[1]||``,r=!!n&&n[1]!==`:`;return{device:n,isUnc:r,isAbsolute:r||!!t[2],tail:t[3]}}function f(e){return`\\\\`+e.replace(/^[\\\/]+/,``).replace(/[\\\/]+/g,`\\`)}l.resolve=function(){for(var e=``,t=``,r=!1,o=arguments.length-1;o>=-1;o--){var s;if(o>=0?s=arguments[o]:e?(s=n.env[`=`+e],(!s||s.substr(0,3).toLowerCase()!==e.toLowerCase()+`\\`)&&(s=e+`\\`)):s=`/`,!i.isString(s))throw TypeError(`Arguments to path.resolve must be strings`);if(s){var c=d(s),l=c.device,u=c.isUnc,p=c.isAbsolute,m=c.tail;if(!(l&&e&&l.toLowerCase()!==e.toLowerCase())&&(e||=l,r||=(t=m+`\\`+t,p),e&&r))break}}return u&&(e=f(e)),t=a(t.split(/[\\\/]+/),!r).join(`\\`),e+(r?`\\`:``)+t||`.`},l.normalize=function(e){var t=d(e),n=t.device,r=t.isUnc,i=t.isAbsolute,o=t.tail,s=/[\\\/]$/.test(o);return o=a(o.split(/[\\\/]+/),!i).join(`\\`),!o&&!i&&(o=`.`),o&&s&&(o+=`\\`),r&&(n=f(n)),n+(i?`\\`:``)+o},l.isAbsolute=function(e){return d(e).isAbsolute},l.join=function(){for(var e=[],t=0;t<arguments.length;t++){var n=arguments[t];if(!i.isString(n))throw TypeError(`Arguments to path.join must be strings`);n&&e.push(n)}var r=e.join(`\\`);return/^[\\\/]{2}[^\\\/]/.test(e[0])||(r=r.replace(/^[\\\/]{2,}/,`\\`)),l.normalize(r)},l.relative=function(e,t){e=l.resolve(e),t=l.resolve(t);for(var n=e.toLowerCase(),r=t.toLowerCase(),i=o(t.split(`\\`)),a=o(n.split(`\\`)),s=o(r.split(`\\`)),c=Math.min(a.length,s.length),u=c,d=0;d<c;d++)if(a[d]!==s[d]){u=d;break}if(u==0)return t;for(var f=[],d=u;d<a.length;d++)f.push(`..`);return f=f.concat(i.slice(u)),f.join(`\\`)},l._makeLong=function(e){if(!i.isString(e))return e;if(!e)return``;var t=l.resolve(e);return/^[a-zA-Z]\:\\/.test(t)?`\\\\?\\`+t:/^\\\\[^?.]/.test(t)?`\\\\?\\UNC\\`+t.substring(2):e},l.dirname=function(e){var t=u(e),n=t[0],r=t[1];return!n&&!r?`.`:(r&&=r.substr(0,r.length-1),n+r)},l.basename=function(e,t){var n=u(e)[2];return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},l.extname=function(e){return u(e)[3]},l.format=function(e){if(!i.isObject(e))throw TypeError(`Parameter 'pathObject' must be an object, not `+typeof e);var t=e.root||``;if(!i.isString(t))throw TypeError(`'pathObject.root' must be a string or undefined, not `+typeof e.root);var n=e.dir,r=e.base||``;return n?n[n.length-1]===l.sep?n+r:n+l.sep+r:r},l.parse=function(e){if(!i.isString(e))throw TypeError(`Parameter 'pathString' must be a string, not `+typeof e);var t=u(e);if(!t||t.length!==4)throw TypeError(`Invalid path '`+e+`'`);return{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},l.sep=`\\`,l.delimiter=`;`;var p=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,m={};function h(e){return p.exec(e).slice(1)}m.resolve=function(){for(var e=``,t=!1,n=arguments.length-1;n>=-1&&!t;n--){var r=n>=0?arguments[n]:`/`;if(!i.isString(r))throw TypeError(`Arguments to path.resolve must be strings`);r&&(e=r+`/`+e,t=r[0]===`/`)}return e=a(e.split(`/`),!t).join(`/`),(t?`/`:``)+e||`.`},m.normalize=function(e){var t=m.isAbsolute(e),n=e&&e[e.length-1]===`/`;return e=a(e.split(`/`),!t).join(`/`),!e&&!t&&(e=`.`),e&&n&&(e+=`/`),(t?`/`:``)+e},m.isAbsolute=function(e){return e.charAt(0)===`/`},m.join=function(){for(var e=``,t=0;t<arguments.length;t++){var n=arguments[t];if(!i.isString(n))throw TypeError(`Arguments to path.join must be strings`);n&&(e?e+=`/`+n:e+=n)}return m.normalize(e)},m.relative=function(e,t){e=m.resolve(e).substr(1),t=m.resolve(t).substr(1);for(var n=o(e.split(`/`)),r=o(t.split(`/`)),i=Math.min(n.length,r.length),a=i,s=0;s<i;s++)if(n[s]!==r[s]){a=s;break}for(var c=[],s=a;s<n.length;s++)c.push(`..`);return c=c.concat(r.slice(a)),c.join(`/`)},m._makeLong=function(e){return e},m.dirname=function(e){var t=h(e),n=t[0],r=t[1];return!n&&!r?`.`:(r&&=r.substr(0,r.length-1),n+r)},m.basename=function(e,t){var n=h(e)[2];return t&&n.substr(-1*t.length)===t&&(n=n.substr(0,n.length-t.length)),n},m.extname=function(e){return h(e)[3]},m.format=function(e){if(!i.isObject(e))throw TypeError(`Parameter 'pathObject' must be an object, not `+typeof e);var t=e.root||``;if(!i.isString(t))throw TypeError(`'pathObject.root' must be a string or undefined, not `+typeof e.root);return(e.dir?e.dir+m.sep:``)+(e.base||``)},m.parse=function(e){if(!i.isString(e))throw TypeError(`Parameter 'pathString' must be a string, not `+typeof e);var t=h(e);if(!t||t.length!==4)throw TypeError(`Invalid path '`+e+`'`);return t[1]=t[1]||``,t[2]=t[2]||``,t[3]=t[3]||``,{root:t[0],dir:t[0]+t[1].slice(0,-1),base:t[2],ext:t[3],name:t[2].slice(0,t[2].length-t[3].length)}},m.sep=`/`,m.delimiter=`:`,r?t.exports=l:t.exports=m,t.exports.posix=m,t.exports.win32=l}))()),{entries:y,setPrototypeOf:b,isFrozen:x,getPrototypeOf:ee,getOwnPropertyDescriptor:S}=Object,{freeze:C,seal:w,create:te}=Object,{apply:ne,construct:re}=typeof Reflect<`u`&&Reflect;C||=function(e){return e},w||=function(e){return e},ne||=function(e,t){for(var n=arguments.length,r=Array(n>2?n-2:0),i=2;i<n;i++)r[i-2]=arguments[i];return e.apply(t,r)},re||=function(e){for(var t=arguments.length,n=Array(t>1?t-1:0),r=1;r<t;r++)n[r-1]=arguments[r];return new e(...n)};var ie=D(Array.prototype.forEach),ae=D(Array.prototype.lastIndexOf),oe=D(Array.prototype.pop),se=D(Array.prototype.push),ce=D(Array.prototype.splice),le=D(String.prototype.toLowerCase),ue=D(String.prototype.toString),de=D(String.prototype.match),fe=D(String.prototype.replace),pe=D(String.prototype.indexOf),me=D(String.prototype.trim),T=D(Object.prototype.hasOwnProperty),E=D(RegExp.prototype.test),he=O(TypeError);function D(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,r=Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];return ne(e,t,r)}}function O(e){return function(){for(var t=arguments.length,n=Array(t),r=0;r<t;r++)n[r]=arguments[r];return re(e,n)}}function k(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:le;b&&b(e,null);let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(x(t)||(t[r]=e),i=e)}e[i]=!0}return e}function ge(e){for(let t=0;t<e.length;t++)T(e,t)||(e[t]=null);return e}function A(e){let t=te(null);for(let[n,r]of y(e))T(e,n)&&(Array.isArray(r)?t[n]=ge(r):r&&typeof r==`object`&&r.constructor===Object?t[n]=A(r):t[n]=r);return t}function _e(e,t){for(;e!==null;){let n=S(e,t);if(n){if(n.get)return D(n.get);if(typeof n.value==`function`)return D(n.value)}e=ee(e)}function n(){return null}return n}var ve=C(`a.abbr.acronym.address.area.article.aside.audio.b.bdi.bdo.big.blink.blockquote.body.br.button.canvas.caption.center.cite.code.col.colgroup.content.data.datalist.dd.decorator.del.details.dfn.dialog.dir.div.dl.dt.element.em.fieldset.figcaption.figure.font.footer.form.h1.h2.h3.h4.h5.h6.head.header.hgroup.hr.html.i.img.input.ins.kbd.label.legend.li.main.map.mark.marquee.menu.menuitem.meter.nav.nobr.ol.optgroup.option.output.p.picture.pre.progress.q.rp.rt.ruby.s.samp.search.section.select.shadow.slot.small.source.spacer.span.strike.strong.style.sub.summary.sup.table.tbody.td.template.textarea.tfoot.th.thead.time.tr.track.tt.u.ul.var.video.wbr`.split(`.`)),ye=C(`svg.a.altglyph.altglyphdef.altglyphitem.animatecolor.animatemotion.animatetransform.circle.clippath.defs.desc.ellipse.enterkeyhint.exportparts.filter.font.g.glyph.glyphref.hkern.image.inputmode.line.lineargradient.marker.mask.metadata.mpath.part.path.pattern.polygon.polyline.radialgradient.rect.stop.style.switch.symbol.text.textpath.title.tref.tspan.view.vkern`.split(`.`)),be=C([`feBlend`,`feColorMatrix`,`feComponentTransfer`,`feComposite`,`feConvolveMatrix`,`feDiffuseLighting`,`feDisplacementMap`,`feDistantLight`,`feDropShadow`,`feFlood`,`feFuncA`,`feFuncB`,`feFuncG`,`feFuncR`,`feGaussianBlur`,`feImage`,`feMerge`,`feMergeNode`,`feMorphology`,`feOffset`,`fePointLight`,`feSpecularLighting`,`feSpotLight`,`feTile`,`feTurbulence`]),xe=C([`animate`,`color-profile`,`cursor`,`discard`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`foreignobject`,`hatch`,`hatchpath`,`mesh`,`meshgradient`,`meshpatch`,`meshrow`,`missing-glyph`,`script`,`set`,`solidcolor`,`unknown`,`use`]),Se=C(`math.menclose.merror.mfenced.mfrac.mglyph.mi.mlabeledtr.mmultiscripts.mn.mo.mover.mpadded.mphantom.mroot.mrow.ms.mspace.msqrt.mstyle.msub.msup.msubsup.mtable.mtd.mtext.mtr.munder.munderover.mprescripts`.split(`.`)),Ce=C([`maction`,`maligngroup`,`malignmark`,`mlongdiv`,`mscarries`,`mscarry`,`msgroup`,`mstack`,`msline`,`msrow`,`semantics`,`annotation`,`annotation-xml`,`mprescripts`,`none`]),we=C([`#text`]),Te=C(`accept.action.align.alt.autocapitalize.autocomplete.autopictureinpicture.autoplay.background.bgcolor.border.capture.cellpadding.cellspacing.checked.cite.class.clear.color.cols.colspan.controls.controlslist.coords.crossorigin.datetime.decoding.default.dir.disabled.disablepictureinpicture.disableremoteplayback.download.draggable.enctype.enterkeyhint.exportparts.face.for.headers.height.hidden.high.href.hreflang.id.inert.inputmode.integrity.ismap.kind.label.lang.list.loading.loop.low.max.maxlength.media.method.min.minlength.multiple.muted.name.nonce.noshade.novalidate.nowrap.open.optimum.part.pattern.placeholder.playsinline.popover.popovertarget.popovertargetaction.poster.preload.pubdate.radiogroup.readonly.rel.required.rev.reversed.role.rows.rowspan.spellcheck.scope.selected.shape.size.sizes.slot.span.srclang.start.src.srcset.step.style.summary.tabindex.title.translate.type.usemap.valign.value.width.wrap.xmlns.slot`.split(`.`)),Ee=C(`accent-height.accumulate.additive.alignment-baseline.amplitude.ascent.attributename.attributetype.azimuth.basefrequency.baseline-shift.begin.bias.by.class.clip.clippathunits.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.cx.cy.d.dx.dy.diffuseconstant.direction.display.divisor.dur.edgemode.elevation.end.exponent.fill.fill-opacity.fill-rule.filter.filterunits.flood-color.flood-opacity.font-family.font-size.font-size-adjust.font-stretch.font-style.font-variant.font-weight.fx.fy.g1.g2.glyph-name.glyphref.gradientunits.gradienttransform.height.href.id.image-rendering.in.in2.intercept.k.k1.k2.k3.k4.kerning.keypoints.keysplines.keytimes.lang.lengthadjust.letter-spacing.kernelmatrix.kernelunitlength.lighting-color.local.marker-end.marker-mid.marker-start.markerheight.markerunits.markerwidth.maskcontentunits.maskunits.max.mask.mask-type.media.method.mode.min.name.numoctaves.offset.operator.opacity.order.orient.orientation.origin.overflow.paint-order.path.pathlength.patterncontentunits.patterntransform.patternunits.points.preservealpha.preserveaspectratio.primitiveunits.r.rx.ry.radius.refx.refy.repeatcount.repeatdur.restart.result.rotate.scale.seed.shape-rendering.slope.specularconstant.specularexponent.spreadmethod.startoffset.stddeviation.stitchtiles.stop-color.stop-opacity.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke.stroke-width.style.surfacescale.systemlanguage.tabindex.tablevalues.targetx.targety.transform.transform-origin.text-anchor.text-decoration.text-rendering.textlength.type.u1.u2.unicode.values.viewbox.visibility.version.vert-adv-y.vert-origin-x.vert-origin-y.width.word-spacing.wrap.writing-mode.xchannelselector.ychannelselector.x.x1.x2.xmlns.y.y1.y2.z.zoomandpan`.split(`.`)),De=C(`accent.accentunder.align.bevelled.close.columnsalign.columnlines.columnspan.denomalign.depth.dir.display.displaystyle.encoding.fence.frame.height.href.id.largeop.length.linethickness.lspace.lquote.mathbackground.mathcolor.mathsize.mathvariant.maxsize.minsize.movablelimits.notation.numalign.open.rowalign.rowlines.rowspacing.rowspan.rspace.rquote.scriptlevel.scriptminsize.scriptsizemultiplier.selection.separator.separators.stretchy.subscriptshift.supscriptshift.symmetric.voffset.width.xmlns`.split(`.`)),Oe=C([`xlink:href`,`xml:id`,`xlink:title`,`xml:space`,`xmlns:xlink`]),ke=w(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ae=w(/<%[\w\W]*|[\w\W]*%>/gm),je=w(/\$\{[\w\W]*/gm),Me=w(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ne=w(/^aria-[\-\w]+$/),Pe=w(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Fe=w(/^(?:\w+script|data):/i),Ie=w(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Le=w(/^html$/i),Re=w(/^[a-z][.\w]*(-[.\w]+)+$/i),ze=Object.freeze({__proto__:null,ARIA_ATTR:Ne,ATTR_WHITESPACE:Ie,CUSTOM_ELEMENT:Re,DATA_ATTR:Me,DOCTYPE_NAME:Le,ERB_EXPR:Ae,IS_ALLOWED_URI:Pe,IS_SCRIPT_OR_DATA:Fe,MUSTACHE_EXPR:ke,TMPLIT_EXPR:je}),Be={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ve=function(){return typeof window>`u`?null:window},He=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch{return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Ue=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function We(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Ve(),t=e=>We(e);if(t.version=`3.3.3`,t.removed=[],!e||!e.document||e.document.nodeType!==Be.document||!e.Element)return t.isSupported=!1,t;let{document:n}=e,r=n,i=r.currentScript,{DocumentFragment:a,HTMLTemplateElement:o,Node:s,Element:c,NodeFilter:l,NamedNodeMap:u=e.NamedNodeMap||e.MozNamedAttrMap,HTMLFormElement:d,DOMParser:f,trustedTypes:p}=e,m=c.prototype,h=_e(m,`cloneNode`),g=_e(m,`remove`),_=_e(m,`nextSibling`),v=_e(m,`childNodes`),b=_e(m,`parentNode`);if(typeof o==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let x,ee=``,{implementation:S,createNodeIterator:w,createDocumentFragment:ne,getElementsByTagName:re}=n,{importNode:D}=r,O=Ue();t.isSupported=typeof y==`function`&&typeof b==`function`&&S&&S.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:ge,ERB_EXPR:ke,TMPLIT_EXPR:Ae,DATA_ATTR:je,ARIA_ATTR:Me,IS_SCRIPT_OR_DATA:Ne,ATTR_WHITESPACE:Fe,CUSTOM_ELEMENT:Ie}=ze,{IS_ALLOWED_URI:Re}=ze,j=null,Ge=k({},[...ve,...ye,...be,...Se,...we]),M=null,Ke=k({},[...Te,...Ee,...De,...Oe]),N=Object.seal(te(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),qe=null,Je=null,P=Object.seal(te(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Ye=!0,Xe=!0,Ze=!1,Qe=!0,$e=!1,et=!0,tt=!1,nt=!1,rt=!1,F=!1,it=!1,at=!1,ot=!0,st=!1,I=!0,ct=!1,lt={},L=null,R=k({},[`annotation-xml`,`audio`,`colgroup`,`desc`,`foreignobject`,`head`,`iframe`,`math`,`mi`,`mn`,`mo`,`ms`,`mtext`,`noembed`,`noframes`,`noscript`,`plaintext`,`script`,`style`,`svg`,`template`,`thead`,`title`,`video`,`xmp`]),ut=null,dt=k({},[`audio`,`video`,`img`,`source`,`image`,`track`]),ft=null,pt=k({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),mt=`http://www.w3.org/1998/Math/MathML`,z=`http://www.w3.org/2000/svg`,B=`http://www.w3.org/1999/xhtml`,ht=B,gt=!1,_t=null,vt=k({},[mt,z,B],ue),V=k({},[`mi`,`mo`,`mn`,`ms`,`mtext`]),yt=k({},[`annotation-xml`]),bt=k({},[`title`,`style`,`font`,`a`,`script`]),xt=null,St=[`application/xhtml+xml`,`text/html`],H=null,Ct=null,wt=n.createElement(`form`),Tt=function(e){return e instanceof RegExp||e instanceof Function},Et=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(Ct&&Ct===e)){if((!e||typeof e!=`object`)&&(e={}),e=A(e),xt=St.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,H=xt===`application/xhtml+xml`?ue:le,j=T(e,`ALLOWED_TAGS`)?k({},e.ALLOWED_TAGS,H):Ge,M=T(e,`ALLOWED_ATTR`)?k({},e.ALLOWED_ATTR,H):Ke,_t=T(e,`ALLOWED_NAMESPACES`)?k({},e.ALLOWED_NAMESPACES,ue):vt,ft=T(e,`ADD_URI_SAFE_ATTR`)?k(A(pt),e.ADD_URI_SAFE_ATTR,H):pt,ut=T(e,`ADD_DATA_URI_TAGS`)?k(A(dt),e.ADD_DATA_URI_TAGS,H):dt,L=T(e,`FORBID_CONTENTS`)?k({},e.FORBID_CONTENTS,H):R,qe=T(e,`FORBID_TAGS`)?k({},e.FORBID_TAGS,H):A({}),Je=T(e,`FORBID_ATTR`)?k({},e.FORBID_ATTR,H):A({}),lt=T(e,`USE_PROFILES`)?e.USE_PROFILES:!1,Ye=e.ALLOW_ARIA_ATTR!==!1,Xe=e.ALLOW_DATA_ATTR!==!1,Ze=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Qe=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,$e=e.SAFE_FOR_TEMPLATES||!1,et=e.SAFE_FOR_XML!==!1,tt=e.WHOLE_DOCUMENT||!1,F=e.RETURN_DOM||!1,it=e.RETURN_DOM_FRAGMENT||!1,at=e.RETURN_TRUSTED_TYPE||!1,rt=e.FORCE_BODY||!1,ot=e.SANITIZE_DOM!==!1,st=e.SANITIZE_NAMED_PROPS||!1,I=e.KEEP_CONTENT!==!1,ct=e.IN_PLACE||!1,Re=e.ALLOWED_URI_REGEXP||Pe,ht=e.NAMESPACE||B,V=e.MATHML_TEXT_INTEGRATION_POINTS||V,yt=e.HTML_INTEGRATION_POINTS||yt,N=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Tt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(N.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Tt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(N.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements==`boolean`&&(N.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),$e&&(Xe=!1),it&&(F=!0),lt&&(j=k({},we),M=te(null),lt.html===!0&&(k(j,ve),k(M,Te)),lt.svg===!0&&(k(j,ye),k(M,Ee),k(M,Oe)),lt.svgFilters===!0&&(k(j,be),k(M,Ee),k(M,Oe)),lt.mathMl===!0&&(k(j,Se),k(M,De),k(M,Oe))),T(e,`ADD_TAGS`)||(P.tagCheck=null),T(e,`ADD_ATTR`)||(P.attributeCheck=null),e.ADD_TAGS&&(typeof e.ADD_TAGS==`function`?P.tagCheck=e.ADD_TAGS:(j===Ge&&(j=A(j)),k(j,e.ADD_TAGS,H))),e.ADD_ATTR&&(typeof e.ADD_ATTR==`function`?P.attributeCheck=e.ADD_ATTR:(M===Ke&&(M=A(M)),k(M,e.ADD_ATTR,H))),e.ADD_URI_SAFE_ATTR&&k(ft,e.ADD_URI_SAFE_ATTR,H),e.FORBID_CONTENTS&&(L===R&&(L=A(L)),k(L,e.FORBID_CONTENTS,H)),e.ADD_FORBID_CONTENTS&&(L===R&&(L=A(L)),k(L,e.ADD_FORBID_CONTENTS,H)),I&&(j[`#text`]=!0),tt&&k(j,[`html`,`head`,`body`]),j.table&&(k(j,[`tbody`]),delete qe.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw he(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw he(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);x=e.TRUSTED_TYPES_POLICY,ee=x.createHTML(``)}else x===void 0&&(x=He(p,i)),x!==null&&typeof ee==`string`&&(ee=x.createHTML(``));C&&C(e),Ct=e}},Dt=k({},[...ye,...be,...xe]),Ot=k({},[...Se,...Ce]),kt=function(e){let t=b(e);(!t||!t.tagName)&&(t={namespaceURI:ht,tagName:`template`});let n=le(e.tagName),r=le(t.tagName);return _t[e.namespaceURI]?e.namespaceURI===z?t.namespaceURI===B?n===`svg`:t.namespaceURI===mt?n===`svg`&&(r===`annotation-xml`||V[r]):!!Dt[n]:e.namespaceURI===mt?t.namespaceURI===B?n===`math`:t.namespaceURI===z?n===`math`&&yt[r]:!!Ot[n]:e.namespaceURI===B?t.namespaceURI===z&&!yt[r]||t.namespaceURI===mt&&!V[r]?!1:!Ot[n]&&(bt[n]||!Dt[n]):!!(xt===`application/xhtml+xml`&&_t[e.namespaceURI]):!1},U=function(e){se(t.removed,{element:e});try{b(e).removeChild(e)}catch{g(e)}},W=function(e,n){try{se(t.removed,{attribute:n.getAttributeNode(e),from:n})}catch{se(t.removed,{attribute:null,from:n})}if(n.removeAttribute(e),e===`is`)if(F||it)try{U(n)}catch{}else try{n.setAttribute(e,``)}catch{}},At=function(e){let t=null,r=null;if(rt)e=`<remove></remove>`+e;else{let t=de(e,/^[\r\n\t ]+/);r=t&&t[0]}xt===`application/xhtml+xml`&&ht===B&&(e=`<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>`+e+`</body></html>`);let i=x?x.createHTML(e):e;if(ht===B)try{t=new f().parseFromString(i,xt)}catch{}if(!t||!t.documentElement){t=S.createDocument(ht,`template`,null);try{t.documentElement.innerHTML=gt?ee:i}catch{}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),ht===B?re.call(t,tt?`html`:`body`)[0]:tt?t.documentElement:a},jt=function(e){return w.call(e.ownerDocument||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Mt=function(e){return e instanceof d&&(typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||!(e.attributes instanceof u)||typeof e.removeAttribute!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`)},Nt=function(e){return typeof s==`function`&&e instanceof s};function G(e,n,r){ie(e,e=>{e.call(t,n,r,Ct)})}let Pt=function(e){let n=null;if(G(O.beforeSanitizeElements,e,null),Mt(e))return U(e),!0;let r=H(e.nodeName);if(G(O.uponSanitizeElement,e,{tagName:r,allowedTags:j}),et&&e.hasChildNodes()&&!Nt(e.firstElementChild)&&E(/<[/\w!]/g,e.innerHTML)&&E(/<[/\w!]/g,e.textContent)||e.nodeType===Be.progressingInstruction||et&&e.nodeType===Be.comment&&E(/<[/\w]/g,e.data))return U(e),!0;if(!(P.tagCheck instanceof Function&&P.tagCheck(r))&&(!j[r]||qe[r])){if(!qe[r]&&It(r)&&(N.tagNameCheck instanceof RegExp&&E(N.tagNameCheck,r)||N.tagNameCheck instanceof Function&&N.tagNameCheck(r)))return!1;if(I&&!L[r]){let t=b(e)||e.parentNode,n=v(e)||e.childNodes;if(n&&t){let r=n.length;for(let i=r-1;i>=0;--i){let r=h(n[i],!0);r.__removalCount=(e.__removalCount||0)+1,t.insertBefore(r,_(e))}}}return U(e),!0}return e instanceof c&&!kt(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&E(/<\/no(script|embed|frames)/i,e.innerHTML)?(U(e),!0):($e&&e.nodeType===Be.text&&(n=e.textContent,ie([ge,ke,Ae],e=>{n=fe(n,e,` `)}),e.textContent!==n&&(se(t.removed,{element:e.cloneNode()}),e.textContent=n)),G(O.afterSanitizeElements,e,null),!1)},Ft=function(e,t,r){if(Je[t]||ot&&(t===`id`||t===`name`)&&(r in n||r in wt))return!1;if(!(Xe&&!Je[t]&&E(je,t))&&!(Ye&&E(Me,t))&&!(P.attributeCheck instanceof Function&&P.attributeCheck(t,e))){if(!M[t]||Je[t]){if(!(It(e)&&(N.tagNameCheck instanceof RegExp&&E(N.tagNameCheck,e)||N.tagNameCheck instanceof Function&&N.tagNameCheck(e))&&(N.attributeNameCheck instanceof RegExp&&E(N.attributeNameCheck,t)||N.attributeNameCheck instanceof Function&&N.attributeNameCheck(t,e))||t===`is`&&N.allowCustomizedBuiltInElements&&(N.tagNameCheck instanceof RegExp&&E(N.tagNameCheck,r)||N.tagNameCheck instanceof Function&&N.tagNameCheck(r))))return!1}else if(!ft[t]&&!E(Re,fe(r,Fe,``))&&!((t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&pe(r,`data:`)===0&&ut[e])&&!(Ze&&!E(Ne,fe(r,Fe,``)))&&r)return!1}return!0},It=function(e){return e!==`annotation-xml`&&de(e,Ie)},Lt=function(e){G(O.beforeSanitizeAttributes,e,null);let{attributes:n}=e;if(!n||Mt(e))return;let r={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:M,forceKeepAttr:void 0},i=n.length;for(;i--;){let{name:a,namespaceURI:o,value:s}=n[i],c=H(a),l=s,u=a===`value`?l:me(l);if(r.attrName=c,r.attrValue=u,r.keepAttr=!0,r.forceKeepAttr=void 0,G(O.uponSanitizeAttribute,e,r),u=r.attrValue,st&&(c===`id`||c===`name`)&&(W(a,e),u=`user-content-`+u),et&&E(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,u)){W(a,e);continue}if(c===`attributename`&&de(u,`href`)){W(a,e);continue}if(r.forceKeepAttr)continue;if(!r.keepAttr){W(a,e);continue}if(!Qe&&E(/\/>/i,u)){W(a,e);continue}$e&&ie([ge,ke,Ae],e=>{u=fe(u,e,` `)});let d=H(e.nodeName);if(!Ft(d,c,u)){W(a,e);continue}if(x&&typeof p==`object`&&typeof p.getAttributeType==`function`&&!o)switch(p.getAttributeType(d,c)){case`TrustedHTML`:u=x.createHTML(u);break;case`TrustedScriptURL`:u=x.createScriptURL(u);break}if(u!==l)try{o?e.setAttributeNS(o,a,u):e.setAttribute(a,u),Mt(e)?U(e):oe(t.removed)}catch{W(a,e)}}G(O.afterSanitizeAttributes,e,null)},Rt=function e(t){let n=null,r=jt(t);for(G(O.beforeSanitizeShadowDOM,t,null);n=r.nextNode();)G(O.uponSanitizeShadowNode,n,null),Pt(n),Lt(n),n.content instanceof a&&e(n.content);G(O.afterSanitizeShadowDOM,t,null)};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,o=null,c=null,l=null;if(gt=!e,gt&&(e=`<!-->`),typeof e!=`string`&&!Nt(e))if(typeof e.toString==`function`){if(e=e.toString(),typeof e!=`string`)throw he(`dirty is not a string, aborting`)}else throw he(`toString is not a function`);if(!t.isSupported)return e;if(nt||Et(n),t.removed=[],typeof e==`string`&&(ct=!1),ct){if(e.nodeName){let t=H(e.nodeName);if(!j[t]||qe[t])throw he(`root node is forbidden and cannot be sanitized in-place`)}}else if(e instanceof s)i=At(`<!---->`),o=i.ownerDocument.importNode(e,!0),o.nodeType===Be.element&&o.nodeName===`BODY`||o.nodeName===`HTML`?i=o:i.appendChild(o);else{if(!F&&!$e&&!tt&&e.indexOf(`<`)===-1)return x&&at?x.createHTML(e):e;if(i=At(e),!i)return F?null:at?ee:``}i&&rt&&U(i.firstChild);let u=jt(ct?e:i);for(;c=u.nextNode();)Pt(c),Lt(c),c.content instanceof a&&Rt(c.content);if(ct)return e;if(F){if(it)for(l=ne.call(i.ownerDocument);i.firstChild;)l.appendChild(i.firstChild);else l=i;return(M.shadowroot||M.shadowrootmode)&&(l=D.call(r,l,!0)),l}let d=tt?i.outerHTML:i.innerHTML;return tt&&j[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&E(Le,i.ownerDocument.doctype.name)&&(d=`<!DOCTYPE `+i.ownerDocument.doctype.name+`>
|
|
`+d),$e&&ie([ge,ke,Ae],e=>{d=fe(d,e,` `)}),x&&at?x.createHTML(d):d},t.setConfig=function(){Et(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}),nt=!0},t.clearConfig=function(){Ct=null,nt=!1},t.isValidAttribute=function(e,t,n){return Ct||Et({}),Ft(H(e),H(t),n)},t.addHook=function(e,t){typeof t==`function`&&se(O[e],t)},t.removeHook=function(e,t){if(t!==void 0){let n=ae(O[e],t);return n===-1?void 0:ce(O[e],n,1)[0]}return oe(O[e])},t.removeHooks=function(e){O[e]=[]},t.removeAllHooks=function(){O=Ue()},t}var j=We(),Ge=f(l(((e,t)=>{var n=function(e){return r(e)&&!i(e)};function r(e){return!!e&&typeof e==`object`}function i(e){var t=Object.prototype.toString.call(e);return t===`[object RegExp]`||t===`[object Date]`||o(e)}var a=typeof Symbol==`function`&&Symbol.for?Symbol.for(`react.element`):60103;function o(e){return e.$$typeof===a}function s(e){return Array.isArray(e)?[]:{}}function c(e,t){return t.clone!==!1&&t.isMergeableObject(e)?g(s(e),e,t):e}function l(e,t,n){return e.concat(t).map(function(e){return c(e,n)})}function u(e,t){if(!t.customMerge)return g;var n=t.customMerge(e);return typeof n==`function`?n:g}function d(e){return Object.getOwnPropertySymbols?Object.getOwnPropertySymbols(e).filter(function(t){return Object.propertyIsEnumerable.call(e,t)}):[]}function f(e){return Object.keys(e).concat(d(e))}function p(e,t){try{return t in e}catch{return!1}}function m(e,t){return p(e,t)&&!(Object.hasOwnProperty.call(e,t)&&Object.propertyIsEnumerable.call(e,t))}function h(e,t,n){var r={};return n.isMergeableObject(e)&&f(e).forEach(function(t){r[t]=c(e[t],n)}),f(t).forEach(function(i){m(e,i)||(p(e,i)&&n.isMergeableObject(t[i])?r[i]=u(i,n)(e[i],t[i],n):r[i]=c(t[i],n))}),r}function g(e,t,r){r||={},r.arrayMerge=r.arrayMerge||l,r.isMergeableObject=r.isMergeableObject||n,r.cloneUnlessOtherwiseSpecified=c;var i=Array.isArray(t);return i===Array.isArray(e)?i?r.arrayMerge(e,t,r):h(e,t,r):c(t,r)}g.all=function(e,t){if(!Array.isArray(e))throw Error(`first argument should be an array`);return e.reduce(function(e,n){return g(e,n,t)},{})},t.exports=g}))()),M=/([\p{Ll}\d])(\p{Lu})/gu,Ke=/(\p{Lu})([\p{Lu}][\p{Ll}])/gu,N=/(\d)\p{Ll}|(\p{L})\d/u,qe=/[^\p{L}\d]+/giu,Je=`$1\0$2`,P=``;function Ye(e){let t=e.trim();t=t.replace(M,Je).replace(Ke,Je),t=t.replace(qe,`\0`);let n=0,r=t.length;for(;t.charAt(n)===`\0`;)n++;if(n===r)return[];for(;t.charAt(r-1)===`\0`;)r--;return t.slice(n,r).split(/\0/g)}function Xe(e){let t=Ye(e);for(let e=0;e<t.length;e++){let n=t[e],r=N.exec(n);if(r){let i=r.index+(r[1]??r[2]).length;t.splice(e,1,n.slice(0,i),n.slice(i))}}return t}function Ze(e,t){let[n,r,i]=et(e,t);return n+r.map($e(t?.locale)).join(t?.delimiter??` `)+i}function Qe(e,t){return Ze(e,{delimiter:`_`,...t})}function $e(e){return e===!1?e=>e.toLowerCase():t=>t.toLocaleLowerCase(e)}function et(e,t={}){let n=t.split??(t.separateNumbers?Xe:Ye),r=t.prefixCharacters??P,i=t.suffixCharacters??P,a=0,o=e.length;for(;a<e.length;){let t=e.charAt(a);if(!r.includes(t))break;a++}for(;o>a;){let t=o-1,n=e.charAt(t);if(!i.includes(n))break;o=t}return[e.slice(0,a),n(e.slice(a,o)),e.slice(o)]}var tt=u({setSDKMetadata:()=>nt});function nt(e){this?.sdk&&e&&(this.sdk=Object.assign({},this.sdk,e))}var rt=u({IS_DEV:()=>!1,PROTOCOL_FILE:()=>it,PROTOCOL_LSP:()=>at,PluginLogger:()=>pt,URL_LSP:()=>ot,cleanInjectedScripts:()=>H,cleanInjectedUI:()=>St,deepMerge:()=>R,deferred:()=>vt,genID:()=>z,getAppPathRoot:()=>ct,getSDKPathRoot:()=>lt,injectTheme:()=>wt,invokeHostExportedApi:()=>V,isObject:()=>L,isValidUUID:()=>mt,mergeSettingsWithSchema:()=>Tt,normalizeKeyStr:()=>Et,path:()=>F,safeSnakeCase:()=>I,safetyPathJoin:()=>gt,safetyPathNormalize:()=>_t,setupInjectedStyle:()=>yt,setupInjectedUI:()=>xt,transformableEvent:()=>Ct,ucFirst:()=>B,withFileProtocol:()=>ht}),F=navigator.platform.toLowerCase()===`win32`?v.win32:v.posix,it=`file://`,at=`lsp://`,ot=at+`logseq.io/`,st,I=Qe;async function ct(){return st||=await V(`_callApplication`,`getAppPath`)}async function lt(){return gt(await ct(),`js`)}function L(e){return e===Object(e)&&!Array.isArray(e)}function R(e,t){return(0,Ge.default)(e,t,{arrayMerge:(e,t)=>t})}var ut={DEBUG:10,INFO:20,WARN:30,ERROR:40},dt=500;function ft(e){if(e==null)return String(e);if(e instanceof Error)return`${e.message}${e.stack?`
|
|
`+e.stack:``}`;if(typeof e==`string`)return e;if(typeof e==`object`)try{let t=new WeakSet;return JSON.stringify(e,(e,n)=>{if(typeof n==`object`&&n){if(t.has(n))return`[Circular]`;t.add(n)}return n})}catch{try{return String(e)}catch{return`[Unserializable]`}}try{return String(e)}catch{return`[Unserializable]`}}var pt=class extends m{_logs=[];_maxSize;_level;constructor(e,t){super(),this._tag=e,this._opts=t,this._maxSize=Math.max(50,t?.maxSize??dt),this._level=t?.level??`DEBUG`}write(e,t,n){Array.isArray(t)&&t.length&&t[t.length-1]===!0&&(n=!0,t=t.slice(0,-1));let r=typeof e==`string`?e.toUpperCase():e,i=r in ut?r:`INFO`;if(ut[i]<ut[this._level])return;let a=(t||[]).map(ft).join(` `),o={ts:Date.now(),level:i,tag:this._tag||``,message:a};if(this._logs.push(o),this._logs.length>this._maxSize&&this._logs.splice(0,this._logs.length-this._maxSize),n||this._opts?.console){let e=i===`ERROR`?`error`:i===`WARN`?`warn`:i===`DEBUG`?`debug`:`info`;try{console[e](`[${o.tag}][${new Date(o.ts).toLocaleTimeString()}] ${i}: ${a}`)}catch{}}this.emit(`append`,o),this.emit(`change`)}clear(){this._logs=[],this.emit(`clear`),this.emit(`change`)}debug(...e){this.write(`DEBUG`,e)}info(...e){this.write(`INFO`,e)}warn(...e){this.write(`WARN`,e)}error(...e){this.write(`ERROR`,e)}setTag(e){this._tag=e}getTag(){return this._tag}setLevel(e){e in ut&&(this._level=e)}getLevel(){return this._level}setMaxSize(e){this._maxSize=Math.max(50,e|0),this._logs.length>this._maxSize&&(this._logs.splice(0,this._logs.length-this._maxSize),this.emit(`change`))}getEntries(){return this._logs.slice()}toJSON(){return this._logs.map(e=>[e.level,`[${e.tag}][${new Date(e.ts).toLocaleTimeString()}] ${e.message}`])}};function mt(e){return typeof e==`string`&&e.length===36&&/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi.test(e)}function z(){return`_`+Math.random().toString(36).substr(2,9)}function B(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ht(e){return e?(/^(http|file|lsp)/.test(e)||(e=it+e),e):``}function gt(e,...t){try{let n=new URL(e);if(!n.origin)throw Error(null);let r=F.join(e.substr(n.origin.length),...t);return n.origin+r}catch{return F.join(e,...t)}}function _t(e){return e?.match(/^(http?|lsp|assets):/)||(e=F.normalize(e)),e}function vt(e,t){let n,r,i=!1,a=t=>n=>{e&&clearTimeout(e),t(n),i=!0},o=new Promise((i,o)=>{n=a(i),r=a(o),e&&=setTimeout(()=>r(Error(`[deferred timeout] ${t}`)),e)});return{created:Date.now(),setTag:e=>t=e,resolve:n,reject:r,promise:o,get settled(){return i}}}function V(e,...t){e=e?.startsWith(`_call`)?e:e?.replace(/^[_$]+/,``);let n=I(e),r=window.logseq?.sdk,i=r&&Object.keys(r),a={},o=n?.split(`_`)?.[0];o&&i.includes(o)&&(n=n.replace(RegExp(`^${o}_`),``),a=r?.[o]);let s=Object.assign({},window.logseq?.api,a,tt),c=s[n]||window.apis[n]||s[e]||window.apis[e];if(!c)throw Error(`Not existed method #${e}`);return typeof c==`function`?c.apply(this,t):c}function yt(e,t){let n=t[`data-injected-style`],r=n&&document.querySelector(`[data-injected-style=${n}]`);if(r){r.textContent=e;return}return r=document.createElement(`style`),r.textContent=e,t&&Object.entries(t).forEach(([e,t])=>{r.setAttribute(e,t)}),document.head.append(r),()=>{document.head.removeChild(r)}}var bt=new Map;window.__injectedUIEffects=bt;function xt(e,t,n){let r=``,i,a,o=this;`slot`in e?(r=e.slot,i=`#${r}`):`path`in e?i=e.path:a=!0;let s=`${o.id}--${e.key||z()}`,c=s,l=a?document.body:i&&document.querySelector(i);if(!l)return console.error(`${this.debugTag} can not resolve selector target ${i}`),!1;if(e.template)e.template=j.sanitize(e.template,{ADD_TAGS:[`iframe`],ALLOW_UNKNOWN_PROTOCOLS:!0,ADD_ATTR:[`allow`,`src`,`allowfullscreen`,`frameborder`,`scrolling`,`target`]});else{bt.get(s)?.call(null);return}let u=document.querySelector(`#${s}`),d=a?u?.querySelector(`.ls-ui-float-content`):u;if(d){d.innerHTML=e.template,t&&Object.entries(t).forEach(([e,t])=>{u.setAttribute(e,t)});let n=u.dataset.dx!=null;e.style&&Object.entries(e.style).forEach(([e,t])=>{n&&[`left`,`top`,`bottom`,`right`,`width`,`height`].includes(e)||(u.style[e]=t)});return}u=document.createElement(`div`),u.id=s,u.dataset.injectedUi=c||``,a?(d=document.createElement(`div`),d.classList.add(`ls-ui-float-content`),u.appendChild(d)):d=u,d.innerHTML=e.template,t&&Object.entries(t).forEach(([e,t])=>{u.setAttribute(e,t)}),e.style&&Object.entries(e.style).forEach(([e,t])=>{u.style[e]=t});let f,p;return a&&(u.setAttribute(`draggable`,`true`),u.setAttribute(`resizable`,`true`),e.close&&(u.dataset.close=e.close),u.classList.add(`lsp-ui-float-container`,`visible`),p=(o._setupResizableContainer(u,c),o._setupDraggableContainer(u,{key:c,close:()=>f(),title:t?.title}))),r&&e.reset&&Array.from(l.querySelectorAll(`[data-injected-ui]`)).map(e=>e.id)?.forEach(e=>{bt.get(e)?.call(null)}),l.appendChild(u),[`click`,`focus`,`focusin`,`focusout`,`blur`,`dblclick`,`keyup`,`keypress`,`keydown`,`change`,`input`,`contextmenu`].forEach(e=>{u.addEventListener(e,t=>{let n=t.target.closest(`[data-on-${e}]`);if(!n)return;let{preventDefault:r}=n.dataset,i=n.dataset[`on${B(e)}`];i&&o.caller?.callUserModel(i,Ct(n,t)),r?.toLowerCase()===`true`&&t.preventDefault()},!1)}),n?.({el:u,float:a}),f=()=>{p?.(),bt.delete(s),l.removeChild(u)},bt.set(s,f),f}function St(e){if(!bt.has(e))return;let t=bt.get(e);try{t()}catch(t){console.warn(`[CLEAN Injected UI] `,e,t)}}function H(){document.head.querySelectorAll(`script[data-ref=${this.id}]`)?.forEach(e=>e.remove())}function Ct(e,t){let n={};if(e){n.type=t.type;let r=e.dataset,i=`rect`;[`value`,`id`,`className`,`dataset`,i].forEach(t=>{let a;switch(t){case i:if(!r.hasOwnProperty(i))return;a=e.getBoundingClientRect().toJSON();break;default:a=e[t]}typeof a==`object`&&(a={...a}),n[t]=a})}return n}function wt(e){let t=document.createElement(`link`);return t.rel=`stylesheet`,t.href=e,document.head.appendChild(t),()=>{try{document.head.removeChild(t)}catch(e){console.error(e)}}}function Tt(e,t){let n=(t||[]).reduce((e,t)=>(`default`in t&&(e[t.key]=t.default),e),{});return Object.assign(n,e)}function Et(e){if(typeof e==`string`)return e.trim().replace(/\s/g,`_`).toLowerCase()}var Dt=l(((e,t)=>{var n=1e3,r=n*60,i=r*60,a=i*24,o=a*7,s=a*365.25;t.exports=function(e,t){t||={};var n=typeof e;if(n===`string`&&e.length>0)return c(e);if(n===`number`&&isFinite(e))return t.long?u(e):l(e);throw Error(`val is not a non-empty string or a valid number. val=`+JSON.stringify(e))};function c(e){if(e=String(e),!(e.length>100)){var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(t){var c=parseFloat(t[1]);switch((t[2]||`ms`).toLowerCase()){case`years`:case`year`:case`yrs`:case`yr`:case`y`:return c*s;case`weeks`:case`week`:case`w`:return c*o;case`days`:case`day`:case`d`:return c*a;case`hours`:case`hour`:case`hrs`:case`hr`:case`h`:return c*i;case`minutes`:case`minute`:case`mins`:case`min`:case`m`:return c*r;case`seconds`:case`second`:case`secs`:case`sec`:case`s`:return c*n;case`milliseconds`:case`millisecond`:case`msecs`:case`msec`:case`ms`:return c;default:return}}}}function l(e){var t=Math.abs(e);return t>=a?Math.round(e/a)+`d`:t>=i?Math.round(e/i)+`h`:t>=r?Math.round(e/r)+`m`:t>=n?Math.round(e/n)+`s`:e+`ms`}function u(e){var t=Math.abs(e);return t>=a?d(e,t,a,`day`):t>=i?d(e,t,i,`hour`):t>=r?d(e,t,r,`minute`):t>=n?d(e,t,n,`second`):e+` ms`}function d(e,t,n,r){var i=t>=n*1.5;return Math.round(e/n)+` `+r+(i?`s`:``)}})),Ot=l(((e,t)=>{function n(e){n.debug=n,n.default=n,n.coerce=c,n.disable=o,n.enable=i,n.enabled=s,n.humanize=Dt(),n.destroy=l,Object.keys(e).forEach(t=>{n[t]=e[t]}),n.names=[],n.skips=[],n.formatters={};function t(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return n.colors[Math.abs(t)%n.colors.length]}n.selectColor=t;function n(e){let t,i=null,a,o;function s(...e){if(!s.enabled)return;let r=s,i=Number(new Date);r.diff=i-(t||i),r.prev=t,r.curr=i,t=i,e[0]=n.coerce(e[0]),typeof e[0]!=`string`&&e.unshift(`%O`);let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,i)=>{if(t===`%%`)return`%`;a++;let o=n.formatters[i];if(typeof o==`function`){let n=e[a];t=o.call(r,n),e.splice(a,1),a--}return t}),n.formatArgs.call(r,e),(r.log||n.log).apply(r,e)}return s.namespace=e,s.useColors=n.useColors(),s.color=n.selectColor(e),s.extend=r,s.destroy=n.destroy,Object.defineProperty(s,`enabled`,{enumerable:!0,configurable:!1,get:()=>i===null?(a!==n.namespaces&&(a=n.namespaces,o=n.enabled(e)),o):i,set:e=>{i=e}}),typeof n.init==`function`&&n.init(s),s}function r(e,t){let r=n(this.namespace+(t===void 0?`:`:t)+e);return r.log=this.log,r}function i(e){n.save(e),n.namespaces=e,n.names=[],n.skips=[];let t=(typeof e==`string`?e:``).trim().replace(/\s+/g,`,`).split(`,`).filter(Boolean);for(let e of t)e[0]===`-`?n.skips.push(e.slice(1)):n.names.push(e)}function a(e,t){let n=0,r=0,i=-1,a=0;for(;n<e.length;)if(r<t.length&&(t[r]===e[n]||t[r]===`*`))t[r]===`*`?(i=r,a=n,r++):(n++,r++);else if(i!==-1)r=i+1,a++,n=a;else return!1;for(;r<t.length&&t[r]===`*`;)r++;return r===t.length}function o(){let e=[...n.names,...n.skips.map(e=>`-`+e)].join(`,`);return n.enable(``),e}function s(e){for(let t of n.skips)if(a(e,t))return!1;for(let t of n.names)if(a(e,t))return!0;return!1}function c(e){return e instanceof Error?e.stack||e.message:e}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return n.enable(n.load()),n}t.exports=n})),kt=f(l(((e,t)=>{e.formatArgs=i,e.save=a,e.load=o,e.useColors=r,e.storage=s(),e.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=`#0000CC.#0000FF.#0033CC.#0033FF.#0066CC.#0066FF.#0099CC.#0099FF.#00CC00.#00CC33.#00CC66.#00CC99.#00CCCC.#00CCFF.#3300CC.#3300FF.#3333CC.#3333FF.#3366CC.#3366FF.#3399CC.#3399FF.#33CC00.#33CC33.#33CC66.#33CC99.#33CCCC.#33CCFF.#6600CC.#6600FF.#6633CC.#6633FF.#66CC00.#66CC33.#9900CC.#9900FF.#9933CC.#9933FF.#99CC00.#99CC33.#CC0000.#CC0033.#CC0066.#CC0099.#CC00CC.#CC00FF.#CC3300.#CC3333.#CC3366.#CC3399.#CC33CC.#CC33FF.#CC6600.#CC6633.#CC9900.#CC9933.#CCCC00.#CCCC33.#FF0000.#FF0033.#FF0066.#FF0099.#FF00CC.#FF00FF.#FF3300.#FF3333.#FF3366.#FF3399.#FF33CC.#FF33FF.#FF6600.#FF6633.#FF9900.#FF9933.#FFCC00.#FFCC33`.split(`.`);function r(){if(typeof window<`u`&&window.process&&(window.process.type===`renderer`||window.process.__nwjs))return!0;if(typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return typeof document<`u`&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<`u`&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<`u`&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||typeof navigator<`u`&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function i(e){if(e[0]=(this.useColors?`%c`:``)+this.namespace+(this.useColors?` %c`:` `)+e[0]+(this.useColors?`%c `:` `)+`+`+t.exports.humanize(this.diff),!this.useColors)return;let n=`color: `+this.color;e.splice(1,0,n,`color: inherit`);let r=0,i=0;e[0].replace(/%[a-zA-Z%]/g,e=>{e!==`%%`&&(r++,e===`%c`&&(i=r))}),e.splice(i,0,n)}e.log=console.debug||console.log||(()=>{});function a(t){try{t?e.storage.setItem(`debug`,t):e.storage.removeItem(`debug`)}catch{}}function o(){let t;try{t=e.storage.getItem(`debug`)||e.storage.getItem(`DEBUG`)}catch{}return!t&&n!==void 0&&`env`in n&&(t=n.env.DEBUG),t}function s(){try{return localStorage}catch{}}t.exports=Ot()(e);var{formatters:c}=t.exports;c.j=function(e){try{return JSON.stringify(e)}catch(e){return`[UnexpectedJSONParseError]: `+e.message}}}))()),U=`application/x-postmate-v1+json`,W=1e4,At=0,jt=()=>++At,Mt=e=>{let t=document.createElement(`a`);if(t.href=e,t.protocol===`file:`)return`*`;let n=t.protocol.length>4?t.protocol:window.location.protocol,r=t.host.length?t.port===`80`||t.port===`443`?t.hostname:t.host:window.location.host;return t.origin||`${n}//${r}`},Nt={handshake:1,"handshake-reply":1,call:1,emit:1,reply:1,request:1},G=(e,t)=>!(typeof t==`string`&&t!==`*`&&e.origin!==t||!e.data||typeof e.data==`object`&&!(`postmate`in e.data)||e.data.type!==`application/x-postmate-v1+json`||!Nt[e.data.postmate]),Pt=(e,t,n)=>{let r=typeof e[t]==`function`?e[t].apply(null,n):e[t];return Promise.resolve(r)},Ft=class{parent;frame;child;events={};childOrigin;listener;messagePort;addTransportListener(e){this.messagePort?(console.debug(`[DEBUG] Using MessagePort for communication:`,this.frame.src),this.messagePort.addEventListener(`message`,e),this.messagePort.start?.()):(console.debug(`[DEBUG] Using postMessage for communication:`,this.frame.src),this.parent.addEventListener(`message`,e,!1))}removeTransportListener(e){this.messagePort?this.messagePort.removeEventListener(`message`,e):this.parent.removeEventListener(`message`,e,!1)}postToChild(e){if(this.messagePort){this.messagePort.postMessage(e);return}this.child.postMessage(e,this.childOrigin)}constructor(e){this.parent=e.parent,this.frame=e.frame,this.child=e.child,this.childOrigin=e.childOrigin,this.messagePort=e.messagePort,this.listener=e=>{if(this.messagePort){if(!e?.data||typeof e.data==`object`&&!(`postmate`in e.data)||e.data.type!==`application/x-postmate-v1+json`||!Nt[e.data.postmate])return!1}else if(!G(e,this.childOrigin))return!1;let{data:t,name:n}=((e||{}).data||{}).value||{};e.data.postmate===`emit`&&n in this.events&&this.events[n].forEach(e=>{e.call(this,t)})},this.addTransportListener(this.listener)}get(e,...t){return new Promise((n,r)=>{let i=jt(),a=typeof Lt.requestTimeout==`number`?Lt.requestTimeout:W,o,s=e=>{e?.data?.uid===i&&e.data.postmate===`reply`&&(this.removeTransportListener(s),o&&clearTimeout(o),e.data.error?r(e.data.error):n(e.data.value))};this.addTransportListener(s),a>0&&(o=setTimeout(()=>{this.removeTransportListener(s),r(Error(`Postmate: request timeout (${a}ms)`))},a)),this.postToChild({postmate:`request`,type:U,property:e,args:t,uid:i})})}call(e,t){this.postToChild({postmate:`call`,type:U,property:e,data:t})}on(e,t){this.events[e]||(this.events[e]=[]),this.events[e].push(t)}destroy(){this.removeTransportListener(this.listener);try{this.messagePort?.close()}catch{}this.frame.parentNode.removeChild(this.frame)}},It=class{model;parent;parentOrigin;child;messagePort;listener;addTransportListener(e){this.messagePort?(this.messagePort.addEventListener(`message`,e),this.messagePort.start?.()):this.child.addEventListener(`message`,e,!1)}postToParent(e,t){if(this.messagePort){this.messagePort.postMessage(e);return}if(t?.source){let n=t.origin===`null`?`*`:t.origin;t.source.postMessage(e,n)}else this.parent.postMessage(e,this.parentOrigin)}constructor(e){if(this.model=e.model,this.parent=e.parent,this.parentOrigin=e.parentOrigin,this.child=e.child,this.messagePort=e.messagePort,this.listener=e=>{if(this.messagePort){if(!e?.data||typeof e.data==`object`&&!(`postmate`in e.data)||e.data.type!==`application/x-postmate-v1+json`||!Nt[e.data.postmate])return}else if(!G(e,this.parentOrigin))return;let{property:t,uid:n,data:r,args:i}=e.data;if(e.data.postmate===`call`){t in this.model&&typeof this.model[t]==`function`&&this.model[t](r);return}Pt(this.model,t,i).then(r=>{this.postToParent({property:t,postmate:`reply`,type:U,uid:n,value:r},e)}).catch(r=>{this.postToParent({property:t,postmate:`reply`,type:U,uid:n,error:r},e)})},this.addTransportListener(this.listener),!this.messagePort){let e=t=>{let n=t.detail?.port;n&&(this.child.removeEventListener(`message`,this.listener,!1),this.messagePort=n,this.messagePort.addEventListener(`message`,this.listener),this.messagePort.start?.(),this.child.removeEventListener(`postmate:channel-ready`,e))};this.child.addEventListener(`postmate:channel-ready`,e)}}emit(e,t){this.postToParent({postmate:`emit`,type:U,value:{name:e,data:t}})}},Lt=class{static debug=!1;static requestTimeout=W;container;parent;frame;child;childOrigin;url;model;static Model;messagePort;enableMessageChannel;constructor(e){this.container=e.container,this.url=e.url,this.parent=window,this.frame=document.createElement(`iframe`),e.id&&(this.frame.id=e.id),e.name&&(this.frame.name=e.name),e.allow&&(this.frame.allow=e.allow),this.frame.classList.add.apply(this.frame.classList,e.classListArray||[]),this.container.appendChild(this.frame),this.child=this.frame.contentWindow,this.model=e.model||{},this.enableMessageChannel=!!e.enableMessageChannel}sendHandshake(e){e||=this.url;let t=Mt(e),n=0,r;return new Promise((i,a)=>{let o=typeof MessageChannel<`u`&&typeof MessageChannel==`function`,s=this.enableMessageChannel&&o,c=e=>{if(!G(e,t))return!1;if(e.data.postmate===`handshake-reply`){if(clearInterval(r),this.parent.removeEventListener(`message`,c,!1),this.childOrigin=e.origin,s){if(e?.ports?.length){let t=e.ports[0];t&&(this.messagePort=t,this.messagePort.start?.())}else if(e.data.acceptsMessageChannel){let e=new MessageChannel;this.messagePort=e.port1,this.messagePort.start?.(),this.child.postMessage({postmate:`setup-channel`,type:U},t,[e.port2])}}return i(new Ft(this))}return a(`Failed handshake`)};this.parent.addEventListener(`message`,c,!1);let l=()=>{n++;let e={postmate:`handshake`,type:U,model:this.model,enableMessageChannel:+!!s};this.child.postMessage(e,t),n===5&&clearInterval(r)};this.frame.addEventListener(`load`,()=>{l(),r=setInterval(l,500)}),this.frame.src=e})}destroy(){try{this.messagePort?.close()}catch{}this.frame.parentNode.removeChild(this.frame)}},Rt=class{child;model;parent;parentOrigin;messagePort;enableMessageChannel;constructor(e){this.child=window,this.model=e,this.parent=this.child.parent,this.enableMessageChannel=!1}sendHandshakeReply(){return new Promise((e,t)=>{let n=r=>{if(r.data.postmate){if(r.data.postmate===`handshake`){this.child.removeEventListener(`message`,n,!1),this.enableMessageChannel=!!r.data?.enableMessageChannel,this.parentOrigin=r.origin;let t=typeof MessageChannel<`u`&&typeof MessageChannel==`function`;r.source.postMessage({postmate:`handshake-reply`,type:U,acceptsMessageChannel:this.enableMessageChannel&&t?1:0},r.origin===`null`?`*`:r.origin);let i=r.data.model;if(i&&Object.keys(i).forEach(e=>{this.model[e]=i[e]}),this.enableMessageChannel&&t){let e=t=>{if(t.data?.postmate===`setup-channel`&&t.data?.type===`application/x-postmate-v1+json`&&t.origin===this.parentOrigin){let n=t?.ports?.[0];n&&(this.messagePort=n,this.messagePort.start?.(),this.child.dispatchEvent(new CustomEvent(`postmate:channel-ready`,{detail:{port:this.messagePort}}))),this.child.removeEventListener(`message`,e,!1)}};this.child.addEventListener(`message`,e,!1)}return e(new It(this))}return t(`Handshake Reply Failed`)}};this.child.addEventListener(`message`,n,!1)})}},zt=class{constructor(e,t){this.ctx=e,this.opts=t}get ctxId(){return this.ctx.baseInfo.id}setItem(e,t){return this.ctx.caller.callAsync(`api:call`,{method:`write-plugin-storage-file`,args:[this.ctxId,e,t,this.opts?.assets]})}getItem(e){return this.ctx.caller.callAsync(`api:call`,{method:`read-plugin-storage-file`,args:[this.ctxId,e,this.opts?.assets]})}removeItem(e){return this.ctx.caller.call(`api:call`,{method:`unlink-plugin-storage-file`,args:[this.ctxId,e,this.opts?.assets]})}allKeys(){return this.ctx.caller.callAsync(`api:call`,{method:`list-plugin-storage-files`,args:[this.ctxId,this.opts?.assets]})}clear(){return this.ctx.caller.call(`api:call`,{method:`clear-plugin-storage-files`,args:[this.ctxId,this.opts?.assets]})}hasItem(e){return this.ctx.caller.callAsync(`api:call`,{method:`exist-plugin-storage-file`,args:[this.ctxId,e,this.opts?.assets]})}},Bt=class{constructor(e){this.ctx=e}get React(){return this.ensureHostScope().React}get ReactDOM(){return this.ensureHostScope().ReactDOM}get Components(){return{Editor:this.ensureHostScope().logseq.sdk.experiments.cp_page_editor}}get Utils(){let e=this.ensureHostScope().logseq.sdk.utils,t=t=>e[I(t)];return{toClj:t(`toClj`),jsxToClj:t(`jsxToClj`),toJs:t(`toJs`),toKeyword:t(`toKeyword`),toSymbol:t(`toSymbol`)}}get pluginLocal(){return this.ensureHostScope().LSPluginCore.ensurePlugin(this.ctx.baseInfo.id)}invokeExperMethod(e,...t){let n=this.ensureHostScope();return e=I(e)?.toLowerCase(),(n.logseq.api[`exper_`+e]||n.logseq.sdk.experiments[e])?.apply(n,t)}async loadScripts(...e){e=e.map(e=>e?.startsWith(`http`)?e:this.ctx.resolveResourceFullUrl(e)),e.unshift(this.ctx.baseInfo.id),await this.invokeExperMethod(`loadScripts`,...e)}registerFencedCodeRenderer(e,t){return this.invokeExperMethod(`registerFencedCodeRenderer`,this.ctx.baseInfo.id,e,t)}registerDaemonRenderer(e,t){return this.invokeExperMethod(`registerDaemonRenderer`,this.ctx.baseInfo.id,e,t)}registerHostedRenderer(e,t){return this.invokeExperMethod(`registerHostedRenderer`,this.ctx.baseInfo.id,e,t)}registerSidebarRenderer(e,t){return e=`_sidebar.${e}`,t.type=`sidebar`,this.registerHostedRenderer(e,t)}registerRouteRenderer(e,t){return this.invokeExperMethod(`registerRouteRenderer`,this.ctx.baseInfo.id,e,t)}registerBlockPropertiesRenderer(e,t){return this.invokeExperMethod(`registerBlockPropertiesRenderer`,this.ctx.baseInfo.id,e,t)}registerBlockRenderer(e,t){return this.invokeExperMethod(`registerBlockRenderer`,this.ctx.baseInfo.id,e,t)}registerExtensionsEnhancer(e,t){let n=this.ensureHostScope();switch(e){case`katex`:n.katex&&t(n.katex).catch(console.error);break;default:}return this.invokeExperMethod(`registerExtensionsEnhancer`,this.ctx.baseInfo.id,e,t)}ensureHostScope(){try{window.top?.document}catch{console.error(`Can not access host scope!`)}return window.top}},Vt=`#lsp#request#callback`,Ht=e=>`task_callback_${e}`,Ut=class{_promise;_aborted=!1;constructor(e,t,n={}){this._client=e,this._requestId=t,this._requestOptions=n,this._promise=new Promise((e,t)=>{if(!this._requestId)return t(null);this._client.once(Ht(this._requestId),n=>{n&&n instanceof Error?t(n):e(n)})});let{success:r,fail:i,final:a}=this._requestOptions;this._promise.then(e=>{r?.(e)}).catch(e=>{i?.(e)}).finally(()=>{a?.()})}abort(){!this._requestOptions.abortable||this._aborted||(this._client.ctx._execCallableAPI(`http_request_abort`,this._requestId),this._aborted=!0)}get promise(){return this._promise}get client(){return this._client}get requestId(){return this._requestId}},Wt=class e extends p.default{constructor(e){super(),this._ctx=e,this.ctx.caller.on(Vt,e=>{let t=e?.requestId;t&&this.emit(Ht(t),e?.payload)})}static createRequestTask(e,t,n){return new Ut(e,t,n)}async _request(t){let n=this.ctx.baseInfo.id,{success:r,fail:i,final:a,...o}=t,s=this.ctx.Experiments.invokeExperMethod(`request`,n,o),c=e.createRequestTask(this.ctx.Request,s,t);return o.abortable?c:c.promise}get ctx(){return this._ctx}},Gt=typeof t==`object`&&t&&t.Object===Object&&t,Kt=typeof self==`object`&&self&&self.Object===Object&&self,K=Gt||Kt||Function(`return this`)(),qt=K.Symbol,Jt=Object.prototype,Yt=Jt.hasOwnProperty,Xt=Jt.toString,Zt=qt?qt.toStringTag:void 0;function Qt(e){var t=Yt.call(e,Zt),n=e[Zt];try{e[Zt]=void 0;var r=!0}catch{}var i=Xt.call(e);return r&&(t?e[Zt]=n:delete e[Zt]),i}var $t=Object.prototype.toString;function en(e){return $t.call(e)}var tn=`[object Null]`,nn=`[object Undefined]`,rn=qt?qt.toStringTag:void 0;function an(e){return e==null?e===void 0?nn:tn:rn&&rn in Object(e)?Qt(e):en(e)}function on(e){return typeof e==`object`&&!!e}var sn=`[object Symbol]`;function cn(e){return typeof e==`symbol`||on(e)&&an(e)==sn}function ln(e,t){for(var n=-1,r=e==null?0:e.length,i=Array(r);++n<r;)i[n]=t(e[n],n,e);return i}var q=Array.isArray,un=1/0,dn=qt?qt.prototype:void 0,fn=dn?dn.toString:void 0;function pn(e){if(typeof e==`string`)return e;if(q(e))return ln(e,pn)+``;if(cn(e))return fn?fn.call(e):``;var t=e+``;return t==`0`&&1/e==-un?`-0`:t}function mn(e){var t=typeof e;return e!=null&&(t==`object`||t==`function`)}function hn(e){return e}var gn=`[object AsyncFunction]`,_n=`[object Function]`,vn=`[object GeneratorFunction]`,yn=`[object Proxy]`;function bn(e){if(!mn(e))return!1;var t=an(e);return t==_n||t==vn||t==gn||t==yn}var xn=K[`__core-js_shared__`],Sn=function(){var e=/[^.]+$/.exec(xn&&xn.keys&&xn.keys.IE_PROTO||``);return e?`Symbol(src)_1.`+e:``}();function Cn(e){return!!Sn&&Sn in e}var wn=Function.prototype.toString;function Tn(e){if(e!=null){try{return wn.call(e)}catch{}try{return e+``}catch{}}return``}var En=/[\\^$.*+?()[\]{}|]/g,Dn=/^\[object .+?Constructor\]$/,On=Function.prototype,kn=Object.prototype,An=On.toString,jn=kn.hasOwnProperty,Mn=RegExp(`^`+An.call(jn).replace(En,`\\$&`).replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,`$1.*?`)+`$`);function Nn(e){return!mn(e)||Cn(e)?!1:(bn(e)?Mn:Dn).test(Tn(e))}function Pn(e,t){return e?.[t]}function Fn(e,t){var n=Pn(e,t);return Nn(n)?n:void 0}var In=Fn(K,`WeakMap`),Ln=function(){try{var e=Fn(Object,`defineProperty`);return e({},``,{}),e}catch{}}(),Rn=9007199254740991,zn=/^(?:0|[1-9]\d*)$/;function Bn(e,t){var n=typeof e;return t??=Rn,!!t&&(n==`number`||n!=`symbol`&&zn.test(e))&&e>-1&&e%1==0&&e<t}function Vn(e,t,n){t==`__proto__`&&Ln?Ln(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):e[t]=n}function Hn(e,t){return e===t||e!==e&&t!==t}var Un=9007199254740991;function Wn(e){return typeof e==`number`&&e>-1&&e%1==0&&e<=Un}function Gn(e){return e!=null&&Wn(e.length)&&!bn(e)}var Kn=Object.prototype;function qn(e){var t=e&&e.constructor;return e===(typeof t==`function`&&t.prototype||Kn)}function Jn(e,t){for(var n=-1,r=Array(e);++n<e;)r[n]=t(n);return r}var Yn=`[object Arguments]`;function Xn(e){return on(e)&&an(e)==Yn}var Zn=Object.prototype,Qn=Zn.hasOwnProperty,$n=Zn.propertyIsEnumerable,er=Xn(function(){return arguments}())?Xn:function(e){return on(e)&&Qn.call(e,`callee`)&&!$n.call(e,`callee`)};function tr(){return!1}var nr=typeof e==`object`&&e&&!e.nodeType&&e,rr=nr&&typeof module==`object`&&module&&!module.nodeType&&module,ir=rr&&rr.exports===nr?K.Buffer:void 0,ar=(ir?ir.isBuffer:void 0)||tr,or=`[object Arguments]`,sr=`[object Array]`,cr=`[object Boolean]`,lr=`[object Date]`,ur=`[object Error]`,dr=`[object Function]`,fr=`[object Map]`,pr=`[object Number]`,mr=`[object Object]`,hr=`[object RegExp]`,gr=`[object Set]`,_r=`[object String]`,vr=`[object WeakMap]`,yr=`[object ArrayBuffer]`,br=`[object DataView]`,xr=`[object Float32Array]`,Sr=`[object Float64Array]`,Cr=`[object Int8Array]`,wr=`[object Int16Array]`,Tr=`[object Int32Array]`,Er=`[object Uint8Array]`,Dr=`[object Uint8ClampedArray]`,Or=`[object Uint16Array]`,kr=`[object Uint32Array]`,J={};J[xr]=J[Sr]=J[Cr]=J[wr]=J[Tr]=J[Er]=J[Dr]=J[Or]=J[kr]=!0,J[or]=J[sr]=J[yr]=J[cr]=J[br]=J[lr]=J[ur]=J[dr]=J[fr]=J[pr]=J[mr]=J[hr]=J[gr]=J[_r]=J[vr]=!1;function Ar(e){return on(e)&&Wn(e.length)&&!!J[an(e)]}function jr(e){return function(t){return e(t)}}var Mr=typeof e==`object`&&e&&!e.nodeType&&e,Nr=Mr&&typeof module==`object`&&module&&!module.nodeType&&module,Pr=Nr&&Nr.exports===Mr&&Gt.process,Fr=function(){try{return Nr&&Nr.require&&Nr.require(`util`).types||Pr&&Pr.binding&&Pr.binding(`util`)}catch{}}(),Ir=Fr&&Fr.isTypedArray,Lr=Ir?jr(Ir):Ar,Rr=Object.prototype.hasOwnProperty;function zr(e,t){var n=q(e),r=!n&&er(e),i=!n&&!r&&ar(e),a=!n&&!r&&!i&&Lr(e),o=n||r||i||a,s=o?Jn(e.length,String):[],c=s.length;for(var l in e)(t||Rr.call(e,l))&&!(o&&(l==`length`||i&&(l==`offset`||l==`parent`)||a&&(l==`buffer`||l==`byteLength`||l==`byteOffset`)||Bn(l,c)))&&s.push(l);return s}function Br(e,t){return function(n){return e(t(n))}}var Vr=Br(Object.keys,Object),Hr=Object.prototype.hasOwnProperty;function Ur(e){if(!qn(e))return Vr(e);var t=[];for(var n in Object(e))Hr.call(e,n)&&n!=`constructor`&&t.push(n);return t}function Wr(e){return Gn(e)?zr(e):Ur(e)}var Gr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Kr=/^\w*$/;function qr(e,t){if(q(e))return!1;var n=typeof e;return n==`number`||n==`symbol`||n==`boolean`||e==null||cn(e)?!0:Kr.test(e)||!Gr.test(e)||t!=null&&e in Object(t)}var Jr=Fn(Object,`create`);function Yr(){this.__data__=Jr?Jr(null):{},this.size=0}function Xr(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=+!!t,t}var Zr=`__lodash_hash_undefined__`,Qr=Object.prototype.hasOwnProperty;function $r(e){var t=this.__data__;if(Jr){var n=t[e];return n===Zr?void 0:n}return Qr.call(t,e)?t[e]:void 0}var ei=Object.prototype.hasOwnProperty;function ti(e){var t=this.__data__;return Jr?t[e]!==void 0:ei.call(t,e)}var ni=`__lodash_hash_undefined__`;function ri(e,t){var n=this.__data__;return this.size+=+!this.has(e),n[e]=Jr&&t===void 0?ni:t,this}function ii(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}ii.prototype.clear=Yr,ii.prototype.delete=Xr,ii.prototype.get=$r,ii.prototype.has=ti,ii.prototype.set=ri;function ai(){this.__data__=[],this.size=0}function oi(e,t){for(var n=e.length;n--;)if(Hn(e[n][0],t))return n;return-1}var si=Array.prototype.splice;function ci(e){var t=this.__data__,n=oi(t,e);return n<0?!1:(n==t.length-1?t.pop():si.call(t,n,1),--this.size,!0)}function li(e){var t=this.__data__,n=oi(t,e);return n<0?void 0:t[n][1]}function ui(e){return oi(this.__data__,e)>-1}function di(e,t){var n=this.__data__,r=oi(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}function Y(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}Y.prototype.clear=ai,Y.prototype.delete=ci,Y.prototype.get=li,Y.prototype.has=ui,Y.prototype.set=di;var fi=Fn(K,`Map`);function pi(){this.size=0,this.__data__={hash:new ii,map:new(fi||Y),string:new ii}}function mi(e){var t=typeof e;return t==`string`||t==`number`||t==`symbol`||t==`boolean`?e!==`__proto__`:e===null}function hi(e,t){var n=e.__data__;return mi(t)?n[typeof t==`string`?`string`:`hash`]:n.map}function gi(e){var t=hi(this,e).delete(e);return this.size-=+!!t,t}function _i(e){return hi(this,e).get(e)}function vi(e){return hi(this,e).has(e)}function yi(e,t){var n=hi(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}function X(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}X.prototype.clear=pi,X.prototype.delete=gi,X.prototype.get=_i,X.prototype.has=vi,X.prototype.set=yi;var bi=`Expected a function`;function xi(e,t){if(typeof e!=`function`||t!=null&&typeof t!=`function`)throw TypeError(bi);var n=function(){var r=arguments,i=t?t.apply(this,r):r[0],a=n.cache;if(a.has(i))return a.get(i);var o=e.apply(this,r);return n.cache=a.set(i,o)||a,o};return n.cache=new(xi.Cache||X),n}xi.Cache=X;var Si=500;function Ci(e){var t=xi(e,function(e){return n.size===Si&&n.clear(),e}),n=t.cache;return t}var wi=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Ti=/\\(\\)?/g,Ei=Ci(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(``),e.replace(wi,function(e,n,r,i){t.push(r?i.replace(Ti,`$1`):n||e)}),t});function Di(e){return e==null?``:pn(e)}function Oi(e,t){return q(e)?e:qr(e,t)?[e]:Ei(Di(e))}var ki=1/0;function Ai(e){if(typeof e==`string`||cn(e))return e;var t=e+``;return t==`0`&&1/e==-ki?`-0`:t}function ji(e,t){t=Oi(t,e);for(var n=0,r=t.length;e!=null&&n<r;)e=e[Ai(t[n++])];return n&&n==r?e:void 0}function Mi(e,t,n){var r=e==null?void 0:ji(e,t);return r===void 0?n:r}function Ni(e,t){for(var n=-1,r=t.length,i=e.length;++n<r;)e[i+n]=t[n];return e}function Pi(){this.__data__=new Y,this.size=0}function Fi(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}function Ii(e){return this.__data__.get(e)}function Li(e){return this.__data__.has(e)}var Ri=200;function zi(e,t){var n=this.__data__;if(n instanceof Y){var r=n.__data__;if(!fi||r.length<Ri-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new X(r)}return n.set(e,t),this.size=n.size,this}function Z(e){var t=this.__data__=new Y(e);this.size=t.size}Z.prototype.clear=Pi,Z.prototype.delete=Fi,Z.prototype.get=Ii,Z.prototype.has=Li,Z.prototype.set=zi;function Bi(e,t){for(var n=-1,r=e==null?0:e.length,i=0,a=[];++n<r;){var o=e[n];t(o,n,e)&&(a[i++]=o)}return a}function Vi(){return[]}var Hi=Object.prototype.propertyIsEnumerable,Ui=Object.getOwnPropertySymbols,Wi=Ui?function(e){return e==null?[]:(e=Object(e),Bi(Ui(e),function(t){return Hi.call(e,t)}))}:Vi;function Gi(e,t,n){var r=t(e);return q(e)?r:Ni(r,n(e))}function Ki(e){return Gi(e,Wr,Wi)}var qi=Fn(K,`DataView`),Ji=Fn(K,`Promise`),Yi=Fn(K,`Set`),Xi=`[object Map]`,Zi=`[object Object]`,Qi=`[object Promise]`,$i=`[object Set]`,ea=`[object WeakMap]`,ta=`[object DataView]`,na=Tn(qi),ra=Tn(fi),ia=Tn(Ji),aa=Tn(Yi),oa=Tn(In),sa=an;(qi&&sa(new qi(new ArrayBuffer(1)))!=ta||fi&&sa(new fi)!=Xi||Ji&&sa(Ji.resolve())!=Qi||Yi&&sa(new Yi)!=$i||In&&sa(new In)!=ea)&&(sa=function(e){var t=an(e),n=t==Zi?e.constructor:void 0,r=n?Tn(n):``;if(r)switch(r){case na:return ta;case ra:return Xi;case ia:return Qi;case aa:return $i;case oa:return ea}return t});var ca=sa,la=K.Uint8Array,ua=`__lodash_hash_undefined__`;function da(e){return this.__data__.set(e,ua),this}function fa(e){return this.__data__.has(e)}function pa(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new X;++t<n;)this.add(e[t])}pa.prototype.add=pa.prototype.push=da,pa.prototype.has=fa;function ma(e,t){for(var n=-1,r=e==null?0:e.length;++n<r;)if(t(e[n],n,e))return!0;return!1}function ha(e,t){return e.has(t)}var ga=1,_a=2;function va(e,t,n,r,i,a){var o=n&ga,s=e.length,c=t.length;if(s!=c&&!(o&&c>s))return!1;var l=a.get(e),u=a.get(t);if(l&&u)return l==t&&u==e;var d=-1,f=!0,p=n&_a?new pa:void 0;for(a.set(e,t),a.set(t,e);++d<s;){var m=e[d],h=t[d];if(r)var g=o?r(h,m,d,t,e,a):r(m,h,d,e,t,a);if(g!==void 0){if(g)continue;f=!1;break}if(p){if(!ma(t,function(e,t){if(!ha(p,t)&&(m===e||i(m,e,n,r,a)))return p.push(t)})){f=!1;break}}else if(!(m===h||i(m,h,n,r,a))){f=!1;break}}return a.delete(e),a.delete(t),f}function ya(e){var t=-1,n=Array(e.size);return e.forEach(function(e,r){n[++t]=[r,e]}),n}function ba(e){var t=-1,n=Array(e.size);return e.forEach(function(e){n[++t]=e}),n}var xa=1,Sa=2,Ca=`[object Boolean]`,wa=`[object Date]`,Ta=`[object Error]`,Ea=`[object Map]`,Da=`[object Number]`,Oa=`[object RegExp]`,ka=`[object Set]`,Aa=`[object String]`,ja=`[object Symbol]`,Ma=`[object ArrayBuffer]`,Na=`[object DataView]`,Pa=qt?qt.prototype:void 0,Fa=Pa?Pa.valueOf:void 0;function Ia(e,t,n,r,i,a,o){switch(n){case Na:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case Ma:return!(e.byteLength!=t.byteLength||!a(new la(e),new la(t)));case Ca:case wa:case Da:return Hn(+e,+t);case Ta:return e.name==t.name&&e.message==t.message;case Oa:case Aa:return e==t+``;case Ea:var s=ya;case ka:var c=r&xa;if(s||=ba,e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;r|=Sa,o.set(e,t);var u=va(s(e),s(t),r,i,a,o);return o.delete(e),u;case ja:if(Fa)return Fa.call(e)==Fa.call(t)}return!1}var La=1,Ra=Object.prototype.hasOwnProperty;function za(e,t,n,r,i,a){var o=n&La,s=Ki(e),c=s.length;if(c!=Ki(t).length&&!o)return!1;for(var l=c;l--;){var u=s[l];if(!(o?u in t:Ra.call(t,u)))return!1}var d=a.get(e),f=a.get(t);if(d&&f)return d==t&&f==e;var p=!0;a.set(e,t),a.set(t,e);for(var m=o;++l<c;){u=s[l];var h=e[u],g=t[u];if(r)var _=o?r(g,h,u,t,e,a):r(h,g,u,e,t,a);if(!(_===void 0?h===g||i(h,g,n,r,a):_)){p=!1;break}m||=u==`constructor`}if(p&&!m){var v=e.constructor,y=t.constructor;v!=y&&`constructor`in e&&`constructor`in t&&!(typeof v==`function`&&v instanceof v&&typeof y==`function`&&y instanceof y)&&(p=!1)}return a.delete(e),a.delete(t),p}var Ba=1,Va=`[object Arguments]`,Ha=`[object Array]`,Ua=`[object Object]`,Wa=Object.prototype.hasOwnProperty;function Ga(e,t,n,r,i,a){var o=q(e),s=q(t),c=o?Ha:ca(e),l=s?Ha:ca(t);c=c==Va?Ua:c,l=l==Va?Ua:l;var u=c==Ua,d=l==Ua,f=c==l;if(f&&ar(e)){if(!ar(t))return!1;o=!0,u=!1}if(f&&!u)return a||=new Z,o||Lr(e)?va(e,t,n,r,i,a):Ia(e,t,c,n,r,i,a);if(!(n&Ba)){var p=u&&Wa.call(e,`__wrapped__`),m=d&&Wa.call(t,`__wrapped__`);if(p||m){var h=p?e.value():e,g=m?t.value():t;return a||=new Z,i(h,g,n,r,a)}}return f?(a||=new Z,za(e,t,n,r,i,a)):!1}function Ka(e,t,n,r,i){return e===t?!0:e==null||t==null||!on(e)&&!on(t)?e!==e&&t!==t:Ga(e,t,n,r,Ka,i)}var qa=1,Ja=2;function Ya(e,t,n,r){var i=n.length,a=i,o=!r;if(e==null)return!a;for(e=Object(e);i--;){var s=n[i];if(o&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++i<a;){s=n[i];var c=s[0],l=e[c],u=s[1];if(o&&s[2]){if(l===void 0&&!(c in e))return!1}else{var d=new Z;if(r)var f=r(l,u,c,e,t,d);if(!(f===void 0?Ka(u,l,qa|Ja,r,d):f))return!1}}return!0}function Xa(e){return e===e&&!mn(e)}function Za(e){for(var t=Wr(e),n=t.length;n--;){var r=t[n],i=e[r];t[n]=[r,i,Xa(i)]}return t}function Qa(e,t){return function(n){return n==null?!1:n[e]===t&&(t!==void 0||e in Object(n))}}function $a(e){var t=Za(e);return t.length==1&&t[0][2]?Qa(t[0][0],t[0][1]):function(n){return n===e||Ya(n,e,t)}}function eo(e,t){return e!=null&&t in Object(e)}function to(e,t,n){t=Oi(t,e);for(var r=-1,i=t.length,a=!1;++r<i;){var o=Ai(t[r]);if(!(a=e!=null&&n(e,o)))break;e=e[o]}return a||++r!=i?a:(i=e==null?0:e.length,!!i&&Wn(i)&&Bn(o,i)&&(q(e)||er(e)))}function no(e,t){return e!=null&&to(e,t,eo)}var ro=1,io=2;function ao(e,t){return qr(e)&&Xa(t)?Qa(Ai(e),t):function(n){var r=Mi(n,e);return r===void 0&&r===t?no(n,e):Ka(t,r,ro|io)}}function oo(e){return function(t){return t?.[e]}}function so(e){return function(t){return ji(t,e)}}function co(e){return qr(e)?oo(Ai(e)):so(e)}function lo(e){return typeof e==`function`?e:e==null?hn:typeof e==`object`?q(e)?ao(e[0],e[1]):$a(e):co(e)}function uo(e){return function(t,n,r){for(var i=-1,a=Object(t),o=r(t),s=o.length;s--;){var c=o[e?s:++i];if(n(a[c],c,a)===!1)break}return t}}var fo=uo();function po(e,t){return e&&fo(e,t,Wr)}function mo(e,t){var n={};return t=lo(t,3),po(e,function(e,r,i){Vn(n,t(e,r,i),e)}),n}var ho=class{constructor(e,t){this.ctx=e,this.serviceHooks=t,e._execCallableAPI(`register-search-service`,e.baseInfo.id,t.name,t.options);let n=e=>`service:search:${e}:${t.name}`;Object.entries({query:{f:`onQuery`,args:[`graph`,`q`,!0],reply:!0,transformOutput:e=>(q(e?.blocks)&&(e.blocks=e.blocks.map(e=>e&&mo(e,(e,t)=>`block/${t}`))),e)},rebuildBlocksIndice:{f:`onIndiceInit`,args:[`graph`,`blocks`]},transactBlocks:{f:`onBlocksChanged`,args:[`graph`,`data`]},truncateBlocks:{f:`onIndiceReset`,args:[`graph`]},removeDb:{f:`onGraph`,args:[`graph`]}}).forEach(([r,i])=>{let a=n(r);e.caller.on(a,async n=>{if(bn(t?.[i.f])){let r=null;try{r=await t[i.f].apply(t,(i.args||[]).map(e=>{if(n){if(e===!0)return n;if(n.hasOwnProperty(e)){let t=n[e];return delete n[e],t}}})),i.transformOutput&&(r=i.transformOutput(r))}catch(e){console.error(`[SearchService] `,e),r=e}finally{i.reply&&e.caller.call(`${a}:reply`,r)}}})})}},go=Symbol.for(`proxy-continue`),_o=(0,kt.default)(`LSPlugin:user`),vo=new pt(``,{console:!0});function yo(e,t,n){let{key:r,label:i,desc:a,palette:o,keybinding:s,extras:c}=t;if(typeof n!=`function`)return this.logger.error(`${r||i}: command action should be function.`),!1;let l=Et(r);if(!l)return this.logger.error(`${i}: command key is required.`),!1;let u=`SimpleCommandHook${l}${++To}`;this.Editor[`on`+u](n),this.caller?.call(`api:call`,{method:`register-plugin-simple-command`,args:[this.baseInfo.id,[{key:l,label:i,type:e,desc:a,keybinding:s,extras:c},[`editor/hook`,u]],o]})}function bo(e){return mt(e)?!0:(vo.error(`#${e} is not a valid UUID string.`),!1)}function xo(e){return e&&(e.baseInfo?.effect||!e.baseInfo?.iir)}var So=null,Co=new Map,wo={async getInfo(e){return So||=await this._execCallableAPIAsync(`get-app-info`),typeof e==`string`?So[e]:So},registerCommand:yo,registerSearchService(e){if(Co.has(e.name))throw Error(`SearchService: #${e.name} has registered!`);Co.set(e.name,new ho(this,e))},registerCommandPalette(e,t){let{key:n,label:r,keybinding:i}=e;return yo.call(this,`$palette$`,{key:n,label:r,palette:!0,keybinding:i},t)},registerCommandShortcut(e,t,n={}){typeof e==`string`&&(e={mode:`global`,binding:e});let{binding:r}=e,i=`$shortcut$`,a=n.key||i+I(r?.toString());return yo.call(this,i,{...n,key:a,palette:!1,keybinding:e},t)},registerUIItem(e,t){let n=this.baseInfo.id;this.caller?.call(`api:call`,{method:`register-plugin-ui-item`,args:[n,e,t]})},registerPageMenuItem(e,t){if(typeof t!=`function`)return!1;let n=e+`_`+this.baseInfo.id,r=e;yo.call(this,`page-menu-item`,{key:n,label:r},t)},onBlockRendererSlotted(e,t){if(!bo(e))return;let n=this.baseInfo.id,r=`hook:editor:${I(`slot:${e}`)}`;return this.caller.on(r,t),this.App._installPluginHook(n,r),()=>{this.caller.off(r,t),this.App._uninstallPluginHook(n,r)}},invokeExternalPlugin(e,...t){if(e=e?.trim(),!e)return;let[n,r]=e.split(`.`);if(![`models`,`commands`].includes(r?.toLowerCase()))throw Error(`Type only support '.models' or '.commands' currently.`);let i=e.replace(`${n}.${r}.`,``);if(!n||!r||!i)throw Error(`Illegal type of #${e} to invoke external plugin.`);return this._execCallableAPIAsync(`invoke_external_plugin_cmd`,n,r.toLowerCase(),i,t)},setFullScreen(e){let t=(...e)=>this._callWin(`setFullScreen`,...e);e===`toggle`?this._callWin(`isFullScreen`).then(e=>{e?t():t(!0)}):e?t(!0):t()}},To=0,Eo={newBlockUUID(){return this._execCallableAPIAsync(`new_block_uuid`)},isPageBlock(e){return e.uuid&&e.hasOwnProperty(`name`)},registerSlashCommand(e,t){_o(`Register slash command #`,this.baseInfo.id,e,t),typeof t==`function`&&(t=[[`editor/clear-current-slash`,!1],[`editor/restore-saved-cursor`],[`editor/hook`,t]]),t=t.map(e=>{let[t,...n]=e;switch(t){case`editor/hook`:let r=n[0],i=()=>{this.caller?.callUserModel(r)};typeof r==`function`&&(i=r);let a=`SlashCommandHook${t}${++To}`;e[1]=a,this.Editor[`on`+a](i);break;default:}return e}),this.caller?.call(`api:call`,{method:`register-plugin-slash-command`,args:[this.baseInfo.id,[e,t]]})},registerBlockContextMenuItem(e,t){if(typeof t!=`function`)return!1;let n=e+`_`+this.baseInfo.id;yo.call(this,`block-context-menu-item`,{key:n,label:e},t)},registerHighlightContextMenuItem(e,t,n){if(typeof t!=`function`)return!1;let r=e+`_`+this.baseInfo.id;yo.call(this,`highlight-context-menu-item`,{key:r,label:e,extras:n},t)},scrollToBlockInPage(e,t,n){let r=`block-content-`+t;n?.replaceState?this.App.replaceState(`page`,{name:e},{anchor:r}):this.App.pushState(`page`,{name:e},{anchor:r})}},Do={onBlockChanged(e,t){if(!bo(e))return;let n=this.baseInfo.id,r=`hook:db:${I(`block:${e}`)}`,i=({block:n,txData:r,txMeta:i})=>{n.uuid===e&&t(n,r,i)};return this.caller.on(r,i),this.App._installPluginHook(n,r),()=>{this.caller.off(r,i),this.App._uninstallPluginHook(n,r)}},datascriptQuery(e,...t){return t.pop(),t?.some(e=>typeof e==`function`)?this.Experiments.ensureHostScope().logseq.api.datascript_query(e,...t):this._execCallableAPIAsync(`datascript_query`,e,...t)}},Oo={},ko={},Ao={},jo={makeSandboxStorage(){return new zt(this,{assets:!0})}},Mo=0,No=class extends m{_version=`0.3.3`;_debugTag=``;_settingsSchema;_connected=!1;_ui=new Map;_mFileStorage;_mRequest;_mExperiments;_beforeunloadCallback;constructor(e,t){super(),this._baseInfo=e,this._caller=t,t.on(`sys:ui:visible`,e=>{e?.toggle&&this.toggleMainUI()}),t.on(`settings:changed`,e=>{let t={...this.settings||{}},n={...e||{}};this._baseInfo={...this._baseInfo,settings:n},this.emit(`settings:changed`,n,t)}),t.on(`beforeunload`,async e=>{let{actor:t,...n}=e,r=this._beforeunloadCallback;try{r&&await r(n),t?.resolve(null)}catch(e){this.logger.error(`[beforeunload] `,e),t?.reject(e)}})}async ready(e,t){if(!this._connected)try{typeof e==`function`&&(t=e,e={});let n=await this._caller.connectToParent(e),r=n?.settings;this._connected=!0,n=R(this._baseInfo,n),r!==void 0&&(n.settings=r),this._baseInfo=n,n?.id&&(this._debugTag=this._caller.debugTag=`#${n.id} [${n.name}]`,this.logger.setTag(this._debugTag)),this._settingsSchema&&(n.settings=Tt(n.settings,this._settingsSchema),await this.useSettingsSchema(this._settingsSchema));try{await this._execCallableAPIAsync(`setSDKMetadata`,{version:this._version,runtime:`js`})}catch(e){console.warn(e)}t&&t.call(this,n)}catch(e){console.error(`${this._debugTag} [Ready Error]`,e)}}ensureConnected(){if(!this._connected)throw Error(`not connected`)}beforeunload(e){typeof e==`function`&&(this._beforeunloadCallback=e)}provideModel(e){return this.caller._extendUserModel(e),this}provideTheme(e){return this.caller.call(`provider:theme`,e),this}provideStyle(e){return this.caller.call(`provider:style`,e),this}provideUI(e){return this.caller.call(`provider:ui`,e),this}useSettingsSchema(e){return this.connected&&this.caller.call(`settings:schema`,{schema:e,isSync:!0}),this._settingsSchema=e,this}updateSettings(e){this.caller.call(`settings:update`,e)}onSettingsChanged(e){let t=`settings:changed`;return this.on(t,e),()=>this.off(t,e)}showSettingsUI(){this.caller.call(`settings:visible:changed`,{visible:!0})}hideSettingsUI(){this.caller.call(`settings:visible:changed`,{visible:!1})}setMainUIAttrs(e){this.caller.call(`main-ui:attrs`,e)}setMainUIInlineStyle(e){this.caller.call(`main-ui:style`,e)}hideMainUI(e){let t={key:Mo,visible:!1,cursor:e?.restoreEditingCursor};this.caller.call(`main-ui:visible`,t),this.emit(`ui:visible:changed`,t),this._ui.set(t.key,t)}showMainUI(e){let t={key:Mo,visible:!0,autoFocus:e?.autoFocus};this.caller.call(`main-ui:visible`,t),this.emit(`ui:visible:changed`,t),this._ui.set(t.key,t)}toggleMainUI(){let e={key:Mo,toggle:!0},t=this._ui.get(e.key);t&&t.visible?this.hideMainUI():this.showMainUI()}get version(){return this._version}get isMainUIVisible(){let e=this._ui.get(Mo);return!!(e&&e.visible)}get connected(){return this._connected}get baseInfo(){return this._baseInfo}get effect(){return xo(this)}get logger(){return vo}get settings(){return this.baseInfo?.settings}get caller(){return this._caller}resolveResourceFullUrl(e){if(this.ensureConnected(),e)return e=e.replace(/^[.\\/]+/,``),gt(this._baseInfo.lsr,e)}_makeUserProxy(e,t){let n=this,r=this.caller;return new Proxy(e,{get(e,i,a){let o=e[i];return function(...e){if(o){e?.length!==0&&e.push(t);let r=o.apply(n,e);if(r!==go)return r}if(t){let a=i.toString().match(/^(once|off|on)/i);if(a!=null){let i=a[0].toLowerCase(),o=a.input,s=i===`off`,c=n.baseInfo.id,l=o.slice(i.length),u=e[0],d=e[1];typeof u==`string`&&typeof d==`function`&&(u=u.replace(/^logseq./,`:`),l=`${l}${u}`,u=d,d=e[2]),l=`hook:${t}:${I(l)}`,r[i](l,u);let f=()=>{r.off(l,u),r.listenerCount(l)||n.App._uninstallPluginHook(c,l)};if(!s)n.App._installPluginHook(c,l,d);else{f();return}return f}}let a=i;return[`git`,`ui`,`assets`,`utils`].includes(t)&&(a=t+`_`+a),r.callAsync(`api:call`,{tag:t,method:a,args:e})}}})}_execCallableAPIAsync(e,...t){return this._caller.callAsync(`api:call`,{method:e,args:t})}_execCallableAPI(e,...t){this._caller.call(`api:call`,{method:e,args:t})}_callWin(...e){return this._execCallableAPIAsync(`_callMainWin`,...e)}#e;#t;#n;#r;#i;get App(){return this.#e?this.#e:this.#e=this._makeUserProxy(wo,`app`)}get Editor(){return this.#t?this.#t:this.#t=this._makeUserProxy(Eo,`editor`)}get DB(){return this.#n?this.#n:this.#n=this._makeUserProxy(Do,`db`)}get UI(){return this.#r?this.#r:this.#r=this._makeUserProxy(ko,`ui`)}get Utils(){return this.#i?this.#i:this.#i=this._makeUserProxy(Ao,`utils`)}get Git(){return this._makeUserProxy(Oo,`git`)}get Assets(){return this._makeUserProxy(jo,`assets`)}get FileStorage(){let e=this._mFileStorage;return e||=this._mFileStorage=new zt(this),e}get Request(){let e=this._mRequest;return e||=this._mRequest=new Wt(this),e}get Experiments(){let e=this._mExperiments;return e||=this._mExperiments=new Bt(this),e}};function Po(e,t){return new No(e,t)}if(window.__LSP__HOST__==null){let e=new Zo(null);window.logseq=Po({},e)}var{importHTML:Fo,createSandboxContainer:Io}=window.QSandbox||{};function Lo(e,t){return e.startsWith(`http`)?fetch(e,t):(e=e.replace(`file://`,``),new Promise(async(t,n)=>{try{let n=await window.apis.doAction([`readFile`,e]);t({text(){return n}})}catch(e){console.error(e),n(e)}}))}var Ro=class extends m{_frame;_root;_loaded=!1;_unmountFns=[];constructor(e){super(),this._pluginLocal=e,e._dispose(()=>{this._unmount()})}async load(){let{name:e,entry:t}=this._pluginLocal.options;if(this.loaded||!t)return;let{template:n,execScripts:r}=await Fo(t,{fetch:Lo});this._mount(n,document.body);let i=Io(e,{elementGetter:()=>this._root?.firstChild}).instance.proxy;i.__shadow_mode__=!0,i.LSPluginLocal=this._pluginLocal,i.LSPluginShadow=this,i.LSPluginUser=i.logseq=new No(this._pluginLocal.toJSON(),this._pluginLocal.caller);let a=await r(i,!0);this._unmountFns.push(a.unmount),this._loaded=!0}_mount(e,t){let n=this._frame=document.createElement(`div`);n.classList.add(`lsp-shadow-sandbox`),n.id=this._pluginLocal.id,this._root=n.attachShadow({mode:`open`}),this._root.innerHTML=`<div>${e}</div>`,t.appendChild(n),this.emit(`mounted`)}_unmount(){for(let e of this._unmountFns)e&&e.call(null)}destroy(){this.frame?.parentNode?.removeChild(this.frame)}get loaded(){return this._loaded}get document(){return this._root?.firstChild}get frame(){return this._frame}},zo=(0,kt.default)(`LSPlugin:caller`),Bo=`#await#response#`,Vo=`#lspmsg#`,Ho=`#lspmsg#error#`,Uo=`#lspmsg#settings#`,Wo=`#lspmsg#beforeunload#`,Go=`#lspmsg#reply#`,Ko=`#lspmsg#ready#`,qo=e=>`${Vo}${e}`,Jo=e=>`${Bo}${e}`,Yo=45,Xo=99,Zo=class extends m{_connected=!1;_parent;_child;_shadow;_status;_userModel={};_syncGCTimer=null;_call;_callUserModel;_debugTag=``;constructor(e){super(),this._pluginLocal=e,e&&(this._debugTag=e.debugTag)}async connectToChild(){if(this._connected)return;let{shadow:e}=this._pluginLocal;e?await this._setupShadowSandbox():await this._setupIframeSandbox()}async connectToParent(e={}){if(this._connected)return;let t=this,n=this._pluginLocal!=null,r=0,i=new Map,a=vt(1e3*60),o=this._extendUserModel({[Ko]:async e=>{o[qo(e?.pid)]=({type:e,payload:n})=>{zo(`[host (_call) -> *user] ${this._debugTag}`,e,n),t.emit(e,n)},await a.resolve()},[Wo]:async e=>{let n=vt(10*1e3);t.emit(`beforeunload`,Object.assign({actor:n},e)),await n.promise},[Uo]:async({payload:e})=>{t.emit(`settings:changed`,e)},[Vo]:async({ns:e,type:n,payload:r})=>{if(zo(`[host (async) -> *user] ${this._debugTag} ns=${e} type=${n}`,r),e&&e.startsWith(`hook`)){t.emit(`${e}:${n}`,r);return}t.emit(n,r)},[Go]:({_sync:e,result:t})=>{if(zo(`[sync host -> *user] #${e}`,t),i.has(e)){let n=i.get(e);n&&(t?.hasOwnProperty(`#lspmsg#error#`)?n.reject(t[Ho]):n.resolve(t),i.delete(e))}},...e});if(n)return await a.promise,JSON.parse(JSON.stringify(this._pluginLocal?.toJSON()));let s=new Rt(o).sendHandshakeReply();return this._status=`pending`,await s.then(e=>{this._child=e,this._connected=!0,this._call=async(t,n={},a)=>{if(a){let e=++r;i.set(e,a),n._sync=e,a.setTag(`async call #${e}`),zo(`async call #${e}`)}return e.emit(qo(o.baseInfo.id),{type:t,payload:n}),a?.promise},this._callUserModel=async(e,t)=>{try{o[e](t)}catch{zo(`call user model(${e}) not exist. #${this._debugTag}`)}},this._syncGCTimer=setInterval(()=>{if(i.size>100)for(let[e,t]of i)t.settled&&i.delete(e)},1e3*60*30)}).finally(()=>{this._status=void 0}),await a.promise,o.baseInfo}async call(e,t={}){return this._call?.call(this,e,t)}async callAsync(e,t={}){let n=vt(1e3*10);return this._call?.call(this,e,t,n)}async callUserModel(e,...t){return this._callUserModel?.apply(this,[e,...t])}async callUserModelAsync(e,...t){return e=Jo(e),this._callUserModel?.apply(this,[e,...t])}_calcLayoutPosition(e,t,n=0){let r=Math.max(e,n);return typeof t==`number`?`${Math.min(r*100/t,Xo)}%`:`${r}px`}async _applyContainerLayout(e){let t=(await this._pluginLocal?._loadLayoutsData())?.$$0;if(!t)return;let{width:n,height:r,left:i,top:a,vw:o,vh:s}=t;e.dataset.inited_layout=`true`,Object.assign(e.style,{width:`${n}px`,height:`${r}px`,left:this._calcLayoutPosition(i,o),top:this._calcLayoutPosition(a,s,Yo)})}async _setupIframeSandbox(){let e=this._pluginLocal,t=e.id,n=`${t}_lsp_main`,r=new URL(e.options.entry);r.searchParams.set(`__v__`,e.options.version),document.querySelector(`#${n}`)?.remove();let i=document.createElement(`div`);i.classList.add(`lsp-iframe-sandbox-container`),i.id=n,i.dataset.pid=t;try{await this._applyContainerLayout(i)}catch(e){console.error(`[Restore Layout Error]`,e)}document.body.appendChild(i);let a=new Lt({id:t+`_iframe`,container:i,url:r.href,classListArray:[`lsp-iframe-sandbox`],model:{baseInfo:JSON.parse(JSON.stringify(e.toJSON()))},allow:e.options.allow,enableMessageChannel:!0});this._status=`pending`;let o,s=new Promise((e,t)=>{o=setTimeout(()=>{a.destroy(),t(Error(`handshake Timeout`))},8e3)});try{let t=await Promise.race([a.sendHandshake(),s]);this._parent=t,this._connected=!0,this.emit(`connected`),t.on(qo(e.id),({type:e,payload:t})=>{zo(`[user -> *host] `,e,t),this._pluginLocal?.emit(e,t||{}),this._pluginLocal?.caller.emit(e,t||{})}),this._call=async(...n)=>{t.call(qo(e.id),{type:n[0],payload:Object.assign(n[1]||{},{$$pid:e.id})})},this._callUserModel=async(e,...n)=>{if(e.startsWith(`#await#response#`))return await t.get(e.replace(Bo,``),...n);t.call(e,n?.[0])}}catch(e){throw zo(`[iframe sandbox] error`,e),e}finally{clearTimeout(o),this._status=void 0}}async _setupShadowSandbox(){let e=this._pluginLocal,t=this._shadow=new Ro(e);try{this._status=`pending`,await t.load(),this._connected=!0,this.emit(`connected`),this._call=async(t,n={},r)=>(r&&(n.actor=r),this._pluginLocal?.emit(t,Object.assign(n,{$$pid:e.id})),r?.promise),this._callUserModel=async(...e)=>{let t=e[0];t?.startsWith(`#await#response#`)&&(t=t.replace(Bo,``));let n=e[1]||{},r=this._userModel[t];typeof r==`function`&&await r.call(null,n)}}catch(e){throw zo(`[shadow sandbox] error`,e),e}finally{this._status=void 0}}_extendUserModel(e){return Object.assign(this._userModel,e)}_getSandboxIframeContainer(){return this._parent?.frame.parentNode}_getSandboxShadowContainer(){return this._shadow?.frame}_getSandboxIframeRoot(){return this._parent?.frame}_getSandboxShadowRoot(){return this._shadow?.frame}set debugTag(e){this._debugTag=e}async destroy(){let e=null;this._parent&&(e=this._getSandboxIframeContainer(),this._parent.destroy()),this._shadow&&(e=this._getSandboxShadowContainer(),this._shadow.destroy()),e?.parentNode?.removeChild(e),this._syncGCTimer&&=(clearInterval(this._syncGCTimer),null),this._connected=!1,this._parent=void 0,this._child=void 0,this._shadow=void 0,this._call=void 0,this._callUserModel=void 0,this._status=void 0}},Q=(0,kt.default)(`LSPlugin:core`),Qo=`plugins`;function $o(e,t){e||={},t||={};let n=new Set([...Object.keys(e),...Object.keys(t)]),r=[],i=e=>{if(e===void 0)return`undefined`;try{let t=JSON.stringify(e);return t&&t.length>80?t.slice(0,77)+`...`:t}catch{return String(e)}};for(let a of n){let n=e[a],o=t[a];if(n!==o){if(!(a in e)){r.push(`+${a}: ${i(o)}`);continue}if(!(a in t)){r.push(`-${a}`);continue}try{if(JSON.stringify(n)===JSON.stringify(o))continue}catch{}r.push(`${a}: ${i(n)} -> ${i(o)}`)}}return r.length?r.join(`, `):null}var es=class extends m{_settings={disabled:!1};constructor(e,t){super(),this._userPluginSettings=e,this._schema=t,Object.assign(this._settings,e)}get(e){return this._settings[e]}set(e,t){let n=R({},this._settings);this._settings[e]!==t&&(this._settings={...this._settings,[e]:t},this.emit(`change`,{...this._settings},n))}patch(e){if(!L(e))return;let t=R({},this._settings);this._settings=R(this._settings,e),this.emit(`change`,{...this._settings},t)}replace(e){let t=R({},this._settings);this._settings={disabled:!1,...e||{}},this.emit(`change`,{...this._settings},t)}set settings(e){this.replace(e)}get settings(){return this._settings}setSchema(e,t){this._schema=e,t&&this.replace(Tt(this._settings,e))}reset(){let e=this.settings,t={};this._schema,this.replace(t),this.emit(`reset`,t,e)}toJSON(){return this._settings}},$=function(e){return e.LOADING=`loading`,e.UNLOADING=`unloading`,e.LOADED=`loaded`,e.UNLOADED=`unload`,e.ERROR=`error`,e}($||{});function ts(e){let t=e=>`settings:${e}`;e.on(t(`schema`),({schema:t,isSync:n})=>{e.settingsSchema=t,e.settings?.setSchema(t,n)}),e.on(t(`update`),t=>{t&&e.settings?.patch(t)}),e.on(t(`visible:changed`),t=>{let n=t?.visible;V(`set_focused_settings`,n?e.id:null)})}function ns(e){let t=e=>`main-ui:${e}`;e.on(t(`visible`),({visible:t,toggle:n,cursor:r,autoFocus:i})=>{let a=e.getMainUIContainer();a?.classList[n?`toggle`:t?`add`:`remove`](`visible`),t?!e.shadow&&a&&i!==!1&&a.querySelector(`iframe`)?.contentWindow?.focus():a.ownerDocument.activeElement.blur(),r&&V(`restore_editing_cursor`)}),e.on(t(`attrs`),t=>{let n=e.getMainUIContainer();Object.entries(t).forEach(([t,r])=>{n?.setAttribute(t,String(r)),t===`draggable`&&r&&e._dispose(e._setupDraggableContainer(n,{title:e.options.name,close:()=>{e.caller.call(`sys:ui:visible`,{toggle:!0})}})),t===`resizable`&&r&&e._dispose(e._setupResizableContainer(n))})}),e.on(t(`style`),t=>{let n=e.getMainUIContainer(),r=!!n.dataset.inited_layout;Object.entries(t).forEach(([e,t])=>{r&&[`left`,`top`,`bottom`,`right`,`width`,`height`].includes(e)||(n.style[e]=t)})})}function rs(e){let t=e=>`provider:${e}`,n=!1;e.on(t(`theme`),t=>{e.themeMgr.registerTheme(e.id,t),n||=(e._dispose(()=>{e.themeMgr.unregisterTheme(e.id)}),!0)}),e.on(t(`style`),t=>{let n;typeof t!=`string`&&(n=t.key,t=t.style),!(!t||!t.trim())&&e._dispose(yt(t,{"data-injected-style":n?`${n}-${e.id}`:``,"data-ref":e.id}))}),e.on(t(`ui`),t=>{e._onHostMounted(()=>{let n=xt.call(e,t,Object.assign({"data-ref":e.id},t.attrs||{}),({el:t,float:n})=>{if(!n)return;let r=t.dataset.identity;e.layoutCore.move_container_to_top(r)});typeof n==`function`&&e._dispose(n)})})}function is(e){e.on((e=>`api:${e}`)(`call`),async t=>{let n;try{window.$$callerPluginID=e.id,n=await V.apply(e,[t.method,...t.args])}catch(e){n={[Ho]:e}}finally{window.$$callerPluginID=void 0}if(e.shadow){t.actor&&(n?.hasOwnProperty(`#lspmsg#error#`)?t.actor.reject(n[Ho]):t.actor.resolve(n));return}let{_sync:r}=t;if(r!=null){let t=t=>{e.caller?.callUserModel(Go,{result:t,_sync:r})};Promise.resolve(n).then(t,t)}})}function as(e,t){return t&&e.startsWith(`file://`+t)&&(e=gt(ot,e.substr(it.length+t.length))),e}var os=class extends Error{url;packageJsonPath;constructor(e,t={}){super(e),this.name=`IllegalPluginPackageError`,Object.assign(this,t)}},ss=class extends Error{constructor(e){super(e),this.name=`ExistedImportedPluginPackageError`}},cs=class extends m{_sdk={};_runtimeDisposes=[];_registrationDisposes=[];_id;_status=$.UNLOADED;_loadErr;_localRoot;_dotSettingsFile;_caller;_logger=new pt(`PluginLocal`);_disposeSettingsObserver;constructor(e,t,n){super(),this._options=e,this._themeMgr=t,this._ctx=n,this._id=e.key||z(),this._disposeRegistration(async()=>{this._disposeSettingsObserver?.(),this._disposeSettingsObserver=void 0}),ts(this),ns(this),rs(this),is(this)}async _setupUserSettings(e){let{_options:t}=this;this._logger||=new pt(`Loader`);let n=this._logger;if(!(t.settings&&!e&&this._disposeSettingsObserver))try{let[r,i]=await V(`load_plugin_user_settings`,this.id);this._dotSettingsFile=r;let a=t.settings;a||=t.settings=new es(i),this._disposeSettingsObserver?.(),this._disposeSettingsObserver=void 0,e&&a.replace(i);let o=async(e,t)=>{let r=$o(t,e);r&&n.debug(`settings changed`,r),e&&V(`save_plugin_user_settings`,this.id,e)};a.on(`change`,o);let s=()=>{a.off(`change`,o),this._disposeSettingsObserver===s&&(this._disposeSettingsObserver=void 0)};this._disposeSettingsObserver=s}catch(e){Q(`[load plugin user settings Error]`,e),n?.error(`load user settings failed`,e)}}getMainUIContainer(){return this.shadow?this.caller?._getSandboxShadowContainer():this.caller?._getSandboxIframeContainer()}_resolveResourceFullUrl(e,t){if(!e?.trim())return;if(t||=this._localRoot,this.isWebPlugin)return this.installedFromUserWebUrl?`${this.installedFromUserWebUrl}/${e}`:`https://pub-80f42b85b62c40219354a834fcf2bbfa.r2.dev/${F.join(t,e)}`;let n=/^(http|file)/;if(!n.test(e)){let r=F.join(t,e);e=n.test(r)?r:it+r}return!this.options.effect&&this.isInstalledInLocalDotRoot?as(e,this.dotPluginsRoot):e}async _preparePackageConfigs(){let{url:e,webPkg:t}=this._options,n=t;if(!n){let t;if(!e)t=`Can not resolve package config location`;else{Q(`prepare package root`,e),this._logger?.debug(`prepare package root`,e);try{n=await V(`load_plugin_config`,e),n?(n=JSON.parse(n),n||(t=`Parse package config error #${e}/package.json`)):t=`Parse package config error #${e}/package.json`}catch(e){t=e?.message||String(e)}}if(t)throw new os(t,{url:e,packageJsonPath:e?F.join(e,`package.json`):void 0})}[`name`,`author`,`repository`,`version`,`description`,`repo`,`title`,`effect`,`sponsors`].concat(this.isInstalledInLocalDotRoot?[]:[`devEntry`]).forEach(e=>{this._options[e]=n[e]});let{repo:r,version:i}=this._options,a=this._localRoot=this.isWebPlugin?`${r||e}/${i}`:_t(e),o=n.logseq||{},s=o.entry||o.main||n.main;o.devEntry?(this._options.devEntry=o.devEntry,this._options.entry=o.devEntry):this._options.entry=this._resolveResourceFullUrl(s,a),o.mode&&(this._options.mode=o.mode);let c=o.title||n.title,l=o.icon||n.icon;if(this._options.title=c,this._options.icon=l&&this._resolveResourceFullUrl(l),this._options.theme=!!(o.theme||o.themes),this.isInstalledInLocalDotRoot)this._id=F.basename(a);else if(!this.isWebPlugin)if(o.id)this._id=o.id;else{o.id=this.id;try{await V(`save_plugin_package_json`,e,{...n,logseq:o})}catch(e){Q(`[save plugin ID Error] `,e),this._logger?.warn(`save plugin id failed`,e)}}let{registeredPlugins:u,isRegistering:d}=this._ctx;if(d&&u.has(this.id))throw new ss(this.id);return async()=>{try{let e=o.themes;e&&await this._loadConfigThemes(Array.isArray(e)?e:[e])}catch(e){Q(`[prepare package effect Error]`,e),this._logger?.error(`prepare package effect failed`,e)}}}async _tryToNormalizeEntry(){let{entry:e,settings:t,devEntry:n}=this.options;if(n||=t?.get(`_devEntry`),n){this._options.entry=n;return}if(!e.endsWith(`.js`))return;let r=null,i=`write_user_tmp_file`;this.isInstalledInLocalDotRoot&&(i=`write_dotdir_file`,r=this._localRoot.replace(this.dotPluginsRoot,``),r=F.join(Qo,r));let a=new Date().getDay(),o=await lt(),s=await V(i,`${this._id}_index.html`,`<!doctype html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>logseq plugin entry</title>
|
|
${this.isWebPlugin?`<script src="https://cdn.jsdelivr.net/npm/@logseq/libs/dist/lsplugin.user.min.js?v=${a}"><\/script>`:`<script src="${o}/lsplugin.user.js?v=${a}"><\/script>`}
|
|
|
|
</head>
|
|
<body>
|
|
<div id="app"></div>
|
|
<script src="${e}"><\/script>
|
|
</body>
|
|
</html>`,r);e=ht(F.normalize(s)),this._options.effect||(e=as(e,this.dotPluginsRoot)),this._options.entry=e}async _loadConfigThemes(e){e.forEach(e=>{e.url&&(!e.url.startsWith(`http`)&&this._localRoot&&(e.url=this._resolveResourceFullUrl(e.url,this._localRoot),!this.isWebPlugin&&!e.url.startsWith(`file:`)&&!e.url.startsWith(`lsp:`)&&(e.url=`assets://`+e.url)),this.emit(`provider:theme`,e))})}async _loadLayoutsData(){let[,e]=await V(`load_plugin_user_settings`,this.id+`_layouts`);return e||{}}async _saveLayoutsData(e){await V(`save_plugin_user_settings`,this.id+`_layouts`,e)}async _persistMainUILayoutData(e){let t=await this._loadLayoutsData();t.$$0=e,await this._saveLayoutsData(t)}_setupDraggableContainer(e,t={}){let n=e.dataset;if(n.inited_draggable)return;n.identity||=`dd-`+z();let r=!!t.key,i=document.createElement(`div`);i.classList.add(`draggable-handle`),i.innerHTML=`
|
|
<div class="th">
|
|
<div class="l"><h3>${t.title||``}</h3></div>
|
|
<div class="r">
|
|
<a class="button x"><i class="ti ti-x"></i></a>
|
|
</div>
|
|
</div>
|
|
`,i.querySelector(`.x`).addEventListener(`click`,e=>{t?.close?.(),e.stopPropagation()},!1),i.addEventListener(`mousedown`,e=>{e.target?.closest(`.r`)&&(e.stopPropagation(),e.preventDefault())},!1),e.prepend(i),e.addEventListener(`mousedown`,e=>{this.layoutCore.move_container_to_top(n.identity)},!0);let a=e=>{i.querySelector(`h3`).textContent=e},o=this.layoutCore.setup_draggable_container_BANG_(e,r?()=>{}:this._persistMainUILayoutData.bind(this));n.inited_draggable=`true`,t.title&&a(t.title);let s=null;if(n.close===`outside`){let n=n=>{let r=n.target;e.contains(r)||t.close()};document.addEventListener(`click`,n,!1),s=()=>{document.removeEventListener(`click`,n)}}return()=>{o(),s?.()}}_setupResizableContainer(e,t){let n=e.dataset;if(n.inited_resizable)return;n.identity||=`dd-`+z();let r=document.createElement(`div`);r.classList.add(`resizable-handle`),e.prepend(r);let i=window.frontend.modules.layout.core.setup_resizable_container_BANG_(e,t?()=>{}:this._persistMainUILayoutData.bind(this));return n.inited_resizable=`true`,i}async load(e){if(this.pending||this.loaded){this._logger?.debug(`load skipped`,this.pending?`(pending)`:`(already loaded)`);return}let t=performance.now();this._logger?.info(`load:start`,e?.reload?`(reload)`:``),this._transitionStatus($.LOADING,[$.UNLOADED,$.ERROR]),this._loadErr=void 0;try{let n=await this._preparePackageConfigs();if(await this._setupUserSettings(e?.reload),this.disabled||await n.call(null),this.disabled){this._logger?.info(`load:skip (disabled)`);return}if(!this.options.entry){this._logger?.info(`load:skip (no entry - theme-only package)`);return}this._ctx.emit(`beforeload`,this),await this._tryToNormalizeEntry(),this._logger?.debug(`entry normalized`,this.options.entry),this._caller=new Zo(this),await this._caller.connectToChild(),this._logger?.debug(`sandbox connected`);let r=()=>{this._caller?.callUserModel(Ko,{pid:this.id})};e?.indicator?e.indicator.promise.then(r):r(),this._dispose(async()=>{await this._caller?.destroy()}),this._dispose(H.bind(this)),this._ctx.emit(`loadeded`,this),this._logger?.info(`load:done in ${(performance.now()-t).toFixed(1)}ms`)}catch(e){this.logger.error(`load:failed`,e,!0),this.disposeRuntime().catch(null),this._status=$.ERROR,this._loadErr=e}finally{this._loadErr||this._transitionStatus(this.disabled?$.UNLOADED:$.LOADED,[$.LOADING])}}async reload(){if(this.pending){this._logger?.debug(`reload skipped (pending)`);return}this._logger?.info(`reload:start`),this._ctx.emit(`beforereload`,this),this.loaded&&await this.unload(),await this.load({reload:!0}),this._ctx.emit(`reloaded`,this),this._logger?.info(`reload:done`)}async unload(e=!1){if(this.pending){this._logger?.debug(`unload skipped (pending)`);return}if(!e&&!this.loaded){this._status=$.UNLOADED;return}if(e){this._logger?.info(`unregister:start`),await this.unload(),await this.disposeRegistration(),(this.isWebPlugin||this.isInstalledInLocalDotRoot)&&this._ctx.emit(`unlink-plugin`,this.id),this._logger?.info(`unregister:done`);return}this._logger?.info(`unload:start`);try{let t={unregister:e};if(this.loaded){this._transitionStatus($.UNLOADING,[$.LOADED]);try{await this._caller?.callUserModel(Jo(Wo),t),this.emit(`beforeunload`,t)}catch(e){this.logger.error(`beforeunload hook failed`,e)}await this.disposeRuntime()}this.emit(`unloaded`),this._logger?.info(`unload:done`)}catch(e){this.logger.error(`unload failed`,e)}finally{this._status=$.UNLOADED}}async _runDisposers(e){for(let t of e)try{t&&await t()}catch(e){this._logger?.error(`dispose failed`,e)}}async disposeRuntime(){await this._runDisposers(this._runtimeDisposes),this._runtimeDisposes=[]}async disposeRegistration(){await this._runDisposers(this._registrationDisposes),this._registrationDisposes=[]}_dispose(e){e&&this._runtimeDisposes.push(e)}_disposeRegistration(e){e&&this._registrationDisposes.push(e)}_transitionStatus(e,t){if(t&&!t.includes(this._status))throw Error(`Invalid plugin status transition: ${this._status} -> ${e}`);this._status=e}_onHostMounted(e){let t=this._ctx.hostMountedActor;!t||t.settled?e():t?.promise.then(e)}get isWebPlugin(){return this._ctx.isWebPlatform||!!this.options.webPkg}get installedFromUserWebUrl(){return this.isWebPlugin&&this.options.webPkg?.installedFromUserWebUrl}get layoutCore(){return window.frontend.modules.layout.core}get isInstalledInLocalDotRoot(){if(this.isWebPlugin)return!1;let e=this.dotConfigRoot,t=this.localRoot;return e&&t&&t.startsWith(e)}get loaded(){return this._status===$.LOADED}get pending(){return[$.LOADING,$.UNLOADING].includes(this._status)}get status(){return this._status}get settings(){return this.options.settings}set settingsSchema(e){this._options.settingsSchema=e}get settingsSchema(){return this.options.settingsSchema}get logger(){return this._logger}get disabled(){return this.settings?.get(`disabled`)}get theme(){return this.options.theme}get caller(){return this._caller}get id(){return this._id}get shadow(){return this.options.mode===`shadow`}get options(){return this._options}get themeMgr(){return this._themeMgr}get debugTag(){let e=this._options?.name;return`#${this._id} - ${e??``}`}get localRoot(){return this._localRoot||this._options.url}get loadErr(){return this._loadErr}get dotConfigRoot(){return F.normalize(this._ctx.options.dotConfigRoot)}get dotSettingsFile(){return this._dotSettingsFile}get dotPluginsRoot(){return F.join(this.dotConfigRoot,Qo)}get sdk(){return this._sdk}set sdk(e){this._sdk=e}toJSON(e=!0){let t={...this.options};return t.id=this.id,t.err=this.loadErr,t.usf=this.dotSettingsFile,t.iir=this.isInstalledInLocalDotRoot,t.webMode=this.isWebPlugin?this.installedFromUserWebUrl?`user`:`github`:!1,t.lsr=this._resolveResourceFullUrl(`/`),e===!1?delete t.settings:t.settings=t.settings?.toJSON(),t}},ls=class extends m{_isRegistering=!1;_readyIndicator;_hostMountedActor=vt();_userPreferences={theme:null,themes:{mode:`light`,light:null,dark:null},externals:[]};_registeredThemes=new Map;_registeredPlugins=new Map;_currentTheme;constructor(e){super(),this._options=e}async loadUserPreferences(){try{let e=await V(`load_user_preferences`);e&&Object.assign(this._userPreferences,e)}catch(e){Q(`[load user preferences Error]`,e)}}async saveUserPreferences(e){try{e&&Object.assign(this._userPreferences,e),await V(`save_user_preferences`,this._userPreferences)}catch(e){Q(`[save user preferences Error]`,e)}}async activateUserPreferences(){let{theme:e,themes:t}=this._userPreferences,n=t[t.mode];n?await this.selectTheme(n,{effect:!1,emit:!1}):e&&await this.selectTheme(e,{effect:!1,emit:!1})}async register(e,t=!1){if(!Array.isArray(e)){await this.register([e]);return}let n=new Map,r=()=>{let e=Array.from(n.values()).reduce((e,t)=>{let{id:n,options:r,status:i,disabled:a}=t.o;return a!==!0&&(r.entry||!r.name&&!r.entry)&&(e[n]={name:r.name,entry:r.entry,status:i,enabled:typeof a==`boolean`?a?`⚫️`:`🟢`:`🔴`,perf:t.e?`${(t.e-t.s).toFixed(2)}ms`:t.o.loadErr}),e},{});console.table(e)};window.__debugPluginsPerfInfo=r;let i=this._readyIndicator=vt();try{this._isRegistering=!0,await this.loadUserPreferences();let r=new Set(this._userPreferences.externals);if(r?.size)try{let e=await V(`validate_external_plugins`,[...r]);r=new Set([...Object.entries(e)].reduce((e,[t,n])=>(n&&e.push(t),e),[]))}catch(e){console.error(`[validatedExternals Error]`,e)}t&&(e=e.concat([...r].filter(t=>!e.length||e.every(e=>!e.entry&&e.url!==t)).map(e=>({url:e}))));for(let t of e){let{url:e}=t,a=new cs(t,this,this),o={o:a,s:performance.now(),e:0};n.set(e,o),await a.load({indicator:i}),o.e=performance.now();let{loadErr:s}=a;if(s&&(Q(`[Failed LOAD Plugin] #`,t),a.logger?.error(`register: load failed`,s,!0),this.emit(`error`,s),s instanceof os||s instanceof ss))continue;let c=e=>{this.emit(`settings-changed`,a.id,e),a.caller?.callUserModel(Uo,{payload:e})};a.settings?.on(`change`,c),a._disposeRegistration(()=>{a.settings?.off(`change`,c)}),this._registeredPlugins.set(a.id,a),this.emit(`registered`,a),!a.isWebPlugin&&!a.isInstalledInLocalDotRoot&&r.add(e)}await this.saveUserPreferences({externals:Array.from(r)}),await this.activateUserPreferences(),i.resolve(`ready`)}catch(e){console.error(e)}finally{i.settled||i.resolve(`ready`),this._isRegistering=!1,this.emit(`ready`,n),r()}}async reload(e){if(!Array.isArray(e)){await this.reload([e]);return}for(let t of e)try{await this.ensurePlugin(t).reload()}catch(e){try{this.getPluginLogger(t)?.error(`reload failed`,e)}catch{}Q(e)}}async unregister(e){if(!Array.isArray(e)){await this.unregister([e]);return}let t=[];for(let n of e){let e=this.ensurePlugin(n);!e.isWebPlugin&&!e.isInstalledInLocalDotRoot&&t.push(e.options.url),await e.unload(!0),this._registeredPlugins.delete(n),this.emit(`unregistered`,n)}let n=this._userPreferences.externals;n.length&&t.length&&await this.saveUserPreferences({externals:n.filter(e=>!t.includes(e))})}async enable(e){let t=this.ensurePlugin(e);t.pending||!t.disabled&&t.loaded||(t.logger?.info(`enable:start`),this.emit(`beforeenable`),t.settings?.set(`disabled`,!1),await t.load(),this.emit(`enabled`,t.id),t.logger?.info(`enable:done`))}async disable(e){let t=this.ensurePlugin(e);t.pending||t.disabled&&!t.loaded||(t.logger?.info(`disable:start`),this.emit(`beforedisable`),t.settings?.set(`disabled`,!0),await t.unload(),this.emit(`disabled`,t.id),t.logger?.info(`disable:done`))}async _hook(e,t,n,r){let i=`${e}:${I(t)}`,a=i===`hook:db:changed`,o=i.startsWith(`hook:db:block`),s=r=>{Q(`[call hook][#${r.id}]`,e,t),r.caller?.callUserModel(Vo,{ns:e,type:I(t),payload:n})},c=r&&this._registeredPlugins.get(r);if(c&&!c.disabled&&c.options.entry){s(c);return}for(let[e,t]of this._registeredPlugins)if(!(!t.options.entry||t.disabled)){if(!r){let e=t.sdk?.version;if(!e){if(a||o)continue;s(t)}e&&V(`should_exec_plugin_hook`,t.id,i)&&s(t)}else if(r===t.id){s(t);break}}}async hookApp(e,t,n){return await this._hook(`hook:app`,e,t,n)}async hookEditor(e,t,n){return await this._hook(`hook:editor`,e,t,n)}async hookDb(e,t,n){return await this._hook(`hook:db`,e,t,n)}ensurePlugin(e){if(e instanceof cs)return e;let t=this._registeredPlugins.get(e);if(!t)throw Error(`plugin #${e} not existed.`);return t}getPluginLogger(e){try{return this.ensurePlugin(e)?.logger}catch{return}}getPluginLogs(e){return this.getPluginLogger(e)?.getEntries()||[]}clearPluginLogs(e){this.getPluginLogger(e)?.clear()}hostMounted(){this._hostMountedActor.resolve()}_forceCleanInjectedUI(e){if(e)return St(e)}get isWebPlatform(){return this.options.dotConfigRoot?.startsWith(`LSPUserDotRoot`)}get registeredPlugins(){return this._registeredPlugins}get options(){return this._options}get readyIndicator(){return this._readyIndicator}get hostMountedActor(){return this._hostMountedActor}get isRegistering(){return this._isRegistering}get themes(){return this._registeredThemes}get enabledPlugins(){return[...this.registeredPlugins.entries()].reduce((e,t)=>{let n=t?.[1];return n?.disabled!==!0&&e.set(t?.[0],n),e},new Map)}async registerTheme(e,t){if(Q(`Register theme #`,e,t),!e)return;let n=this._registeredThemes.get(e);n||this._registeredThemes.set(e,n=[]),n.push(t),this.emit(`themes-changed`,this.themes,{id:e,...t}),this.getPluginLogger(e)?.debug(`theme registered`,t?.name||t?.url||``)}async selectTheme(e,t={}){let{effect:n,emit:r}=Object.assign({effect:!0,emit:!0},t);if(this._currentTheme&&this._currentTheme.eject(),!e.url)this._currentTheme=null;else{let t=wt(e.url);this._currentTheme={pid:e.pid,opt:e,eject:t}}n&&await this.saveUserPreferences(e.mode?{themes:{...this._userPreferences.themes,mode:e.mode,[e.mode]:e}}:{theme:e}),r&&this.emit(`theme-selected`,e,t)}async unregisterTheme(e,t=!0){if(Q(`Unregister theme #`,e),this._registeredThemes.has(e)&&(this._registeredThemes.delete(e),this.emit(`themes-changed`,this.themes,{id:e}),t&&this._currentTheme?.pid===e)){this._currentTheme.eject(),this._currentTheme=null;let{theme:t,themes:n}=this._userPreferences;await this.saveUserPreferences({theme:t?.pid===e?null:t,themes:{...n,light:n.light?.pid===e?null:n.light,dark:n.dark?.pid===e?null:n.dark}}),this.emit(`reset-custom-theme`,this._userPreferences.themes)}}};function us(e){let t=new ls(e);Q(`=== 🔗 Setup Logseq Plugin System 🔗 ===`),window.LSPluginCore=t,window.DOMPurify=j}e.PluginLocal=cs,Object.defineProperty(e,`pluginHelpers`,{enumerable:!0,get:function(){return rt}}),e.setupPluginCore=us});
|