'use strict';

var T = require('json5');
var C = require('smiles-drawer');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var T__default = /*#__PURE__*/_interopDefault(T);
var C__default = /*#__PURE__*/_interopDefault(C);

var S=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(r,t)=>(typeof require<"u"?require:r)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});function M(e,r,t,m){let n="```",i=e.bMarks[r]+e.tShift[r],o=e.eMarks[r];if(i+3>o||e.src.slice(i,i+3)!==n)return !1;i+=3;let f=e.src.slice(i,o).trim();if(!f.startsWith("smiles"))return !1;let c=f.match(/^smiles\s*({.*})?/),p={};if(c&&c[1])try{p=T__default.default.parse(c[1]);}catch{}if(m)return !0;let s=r+1,u=!1;for(;s<t&&(i=e.bMarks[s]+e.tShift[s],o=e.eMarks[s],!(i<o&&e.sCount[s]<e.blkIndent));){if(e.src.slice(i,i+3)===n){u=!0;break}s++;}if(!u)return !1;let w=e.getLines(r+1,s,0,!1).trim(),b=e.push("smiles_block","div",0);return b.content=w,b.info=JSON.stringify(p),b.map=[r,s+1],e.line=s+1,!0}function v(...e){let r={};return e.filter(Boolean).forEach(t=>{let m=[...Object.getOwnPropertyNames(t),...Object.getOwnPropertySymbols(t)];for(let n of m)Object.prototype.hasOwnProperty.call(t,n)&&(Object.prototype.toString.call(t[n])==="[object Object]"?r[n]=v(r[n],t[n]):r[n]=t[n]);}),r}function P(){return !1}function L(e,r){return function(m,n,i){var O;let o=m[n];if(!o)return "";let d=o.content,f=e.format||"svg",c=J(f,e);r.hasSmiles=!0;let s=Object.entries({"data-smiles-reactant-weights":"reactantWeights","data-smiles-reagent-weights":"reagentWeights","data-smiles-product-weights":"productWeights","data-smiles-reaction-options":"reactionOptions","data-smiles-theme":"theme","data-smiles-weights":"weights",width:"width",height:"height"}).map(([l,a])=>{if(!i[a])return [];let h=i[a];if(Array.isArray(h)){if(Array.isArray(h[0])){let j=h.map(k=>Array.isArray(k)?k.join(","):k).join(";");return [l,j]}return [l,h.join(",")]}return [l,h]}).filter(Boolean).reduce((l,[a,h])=>(a&&h&&(l[a]=h),l),{});Object.assign(s,{"data-smiles":d,"data-smiles-options":JSON.stringify(i).replaceAll('"',"'")});let u=Object.entries(s).map(([l,a])=>`${l}="${a}"`).join(" "),w=`<${c} ${u}></${c}>`;if(!e.renderAtParse||P())return w;let b=S("jsdom").JSDOM,g=new b(w),y={window:g.window,document:g.window.document,HTMLImageElement:g.window.HTMLImageElement,SVGElement:g.window.SVGElement,Image:function(){return g.window.document.createElement("img")}};Object.assign(globalThis,y);try{let l;if(C__default.default.SmiDrawer.apply(void 0,void 0,void 0,void 0,null,x=>{var $,R;l=x,(R=($=e.errorHandling)==null?void 0:$.onError)==null||R.call($,x);}),l)return (O=e.errorHandling)!=null&&O.fallbackImage?`<img src="${e.errorHandling.fallbackImage}" ${u}></img>`:["<div",' class="smiles-error"',` data-smiles-error="Invalid SMILES: \\"${d}\\""`,`>${l.message}</div>`].join("");let a=g.window.document.querySelector(c);if(!a||f!=="img")return (a==null?void 0:a.outerHTML)??"";a.setAttribute("xmlns","http://www.w3.org/2000/svg");let j=S("sharp")(Buffer.from(a.outerHTML)).png().toBuffer(),k;j.then(x=>{k=x;});let B=S("deasync");for(;!k;)B.sleep(100);return `<img src="data:image/png;base64,${k.toString("base64")}" ${u}></img>`}finally{for(let l in y)delete globalThis[l];}}}function J(e,r){switch(e){case"svg":case"img":if(r.renderAtParse)return "svg";break;default:throw new Error(`Invalid format: ${e}, only 'svg' and 'img' are supported`)}return e}function I(e,r,t,m="block"){let n=L(e,r);return (i,o)=>{var y,O;let d=i[o];if(!d)return "";let f=d.info?JSON.parse(d.info):{},c=v({},(y=e.smilesDrawerOptions)==null?void 0:y.default,(O=e.smilesDrawerOptions)==null?void 0:O[m],f),p=n(i,o,c),s={},{width:u,height:w}=c;typeof u=="number"&&(s.width=`${u}px`),typeof w=="number"&&(s.height=`${w}px`);let b=Object.entries(s).map(([l,a])=>`${l}:${a}`).join(";"),g=m==="inline"?"span":"div";return `<${g} class="${t}" style="${b}">${p}</${g}>`}}function A(e,r){return I(e,r,"smiles-block","block")}function D(e,r){return I(e,r,"smiles-inline","inline")}function E(e,r){let t=e.pos,m=e.posMax;if(t+8>m||e.src.slice(t,t+8)!=="$smiles{")return !1;let n=t+8,i=1,o=-1;for(;n<m&&i>0;)e.src[n]==="{"?i++:e.src[n]==="}"&&i--,n++;if(i!==0)return !1;o=n;let d=e.src.slice(t+8,n-1),f={},c=o;if(e.src[o]==="{"){n=o+1;let s=1;for(;n<m&&s>0;)e.src[n]==="{"?s++:e.src[n]==="}"&&s--,n++;if(s===0){c=n;let u=e.src.slice(o,n).trim();if(u)try{f=T__default.default.parse(u);}catch{}}}if(r)return !0;let p=e.push("smiles_inline","span",0);return p.content=d,p.markup="$smiles{",p.info=JSON.stringify(f),e.pos=c,!0}var N=(()=>{let e="";return ()=>{let r=S.resolve("smiles-drawer/dist/smiles-drawer.min.js");return e||(e=S("fs").readFileSync(r,"utf-8")),e}})();function te(e,r={}){r.renderAtParse&&typeof document<"u"&&(console.warn("renderAtParse is not supported in browser environment, it will be ignored"),r.renderAtParse=!1),e.block.ruler.before("fence","smiles_block",M,{alt:["paragraph","reference","blockquote","list"]}),e.inline.ruler.before("emphasis","smiles_inline",E);let t={hasSmiles:!1};e.renderer.rules.smiles_block=A(r,t),e.renderer.rules.smiles_inline=D(r,t);let m=e.render;e.render=(n,i)=>{let o=m.call(e,n,i);if(!t.hasSmiles)return o;let d=()=>N(),f=r.smilesDrawerScript??"https://cdn.jsdelivr.net/npm/smiles-drawer/dist/smiles-drawer.min.js",c=`
            <style>
                .smiles-block {
                    display: inline-block;
                }
                .smiles-block > svg, .smiles-block > img {
                    width: 100%;
                    height: 100%;
                }
                .smiles-inline {
                    display: inline-block;
                    width: 1em;
                    height: 1em;
                    vertical-align: middle;
                }
                .smiles-inline > svg, .smiles-inline > img {
                    vertical-align: top;
                    width: 100%;
                    height: 100%;
                }
                .smiles-error {
                    color: red;
                    font-size: 12px;
                    font-weight: bold;
                    white-space: pre;
                    border-left: red 4px solid;
                    padding-left: 1em;
                }
                .smiles-error:before {
                    content: attr(data-smiles-error);
                    display: block;
                    margin-bottom: 0.5em;
                }
                .smiles-inline:has(.smiles-error) {
                    display: block;
                    height: fit-content;
                    width: fit-content;
                }
            </style>
        `.replace(/ {16}/g,""),p=f?f?`<script src="${f}"></script>`:"":`<script>${d()}</script>`,s=r.renderAtParse?"":`
            ${p}
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    SmiDrawer.apply();
                })
            </script>
        `.replace(/ {4}/g,"");return o+s+c};}

exports.MarkdownItSmiles = te;
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map