satori 0.0.29 → 0.0.30-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/index.js CHANGED
@@ -1,5 +1,3020 @@
1
- import*as $t from"yoga-layout-prebuilt";var dt=$t;var $e;$e=dt.default;function Mt(e){$e=e}function ee(){return $e}function We(e){let t=typeof e;return!(t==="number"||t==="bigint"||t==="string"||t==="boolean")}function pt(e){return/^class\s/.test(Function.prototype.toString.call(e))}function pe(e,t){return[e[0]*t[0]+e[2]*t[1],e[1]*t[0]+e[3]*t[1],e[0]*t[2]+e[2]*t[3],e[1]*t[2]+e[3]*t[3],e[0]*t[4]+e[2]*t[5]+e[4],e[1]*t[4]+e[3]*t[5]+e[5]]}function K(e,t,n){let i=t[e];return typeof i>"u"?n:i}var gt=void 0,Ne=typeof Intl<"u"&&"Segmenter"in Intl;if(!Ne)throw new Error("Intl.Segmenter does not exist, please use import a polyfill.");var Wt=Ne?new Intl.Segmenter(gt,{granularity:"word"}):null,Nt=Ne?new Intl.Segmenter(gt,{granularity:"grapheme"}):null,Re=[32,160,4961,65792,65793,4153,4241,10].map(e=>String.fromCodePoint(e));function ae(e,t){return t==="word"?[...Wt.segment(e)].map(n=>n.segment):[...Nt.segment(e)].map(n=>n.segment)}function y(e,t,n){let i="";for(let[a,o]of Object.entries(t))typeof o<"u"&&(i+=` ${a}="${o}"`);return n?`<${e}${i}>${n}</${e}>`:`<${e}${i}/>`}function mt(e=20){let t=new Map;function n(a,o){if(t.size>=e){let r=t.keys().next().value;t.delete(r)}t.set(a,o)}function i(a){if(!t.has(a))return;let r=t.get(a);return t.delete(a),t.set(a,r),r}return{set:n,get:i}}var ht={accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",allowReorder:"allowreorder",arabicForm:"arabic-form",attributeName:"attributename",attributeType:"attributetype",autoReverse:"autoreverse",baseFrequency:"basefrequency",baseProfile:"baseprofile",baselineShift:"baseline-shift",calcMode:"calcmode",capHeight:"cap-height",clipPath:"clip-path",clipPathUnits:"clippathunits",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",contentScriptType:"contentscripttype",contentStyleType:"contentstyletype",diffuseConstant:"diffuseconstant",dominantBaseline:"dominant-baseline",edgeMode:"edgemode",enableBackground:"enable-background",externalResourcesRequired:"externalresourcesrequired",fillOpacity:"fill-opacity",fillRule:"fill-rule",filterRes:"filterres",filterUnits:"filterunits",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",glyphRef:"glyphref",gradientTransform:"gradienttransform",gradientUnits:"gradientunits",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",imageRendering:"image-rendering",kernelMatrix:"kernelmatrix",kernelUnitLength:"kernelunitlength",keyPoints:"keypoints",keySplines:"keysplines",keyTimes:"keytimes",lengthAdjust:"lengthadjust",letterSpacing:"letter-spacing",lightingColor:"lighting-color",limitingConeAngle:"limitingconeangle",markerEnd:"marker-end",markerHeight:"markerheight",markerMid:"marker-mid",markerStart:"marker-start",markerUnits:"markerunits",markerWidth:"markerwidth",maskContentUnits:"maskcontentunits",maskUnits:"maskunits",numOctaves:"numoctaves",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pathLength:"pathlength",patternContentUnits:"patterncontentunits",patternTransform:"patterntransform",patternUnits:"patternunits",pointerEvents:"pointer-events",pointsAtX:"pointsatx",pointsAtY:"pointsaty",pointsAtZ:"pointsatz",preserveAlpha:"preservealpha",preserveAspectRatio:"preserveaspectratio",primitiveUnits:"primitiveunits",refX:"refx",refY:"refy",renderingIntent:"rendering-intent",repeatCount:"repeatcount",repeatDur:"repeatdur",requiredExtensions:"requiredextensions",requiredFeatures:"requiredfeatures",shapeRendering:"shape-rendering",specularConstant:"specularconstant",specularExponent:"specularexponent",spreadMethod:"spreadmethod",startOffset:"startoffset",stdDeviation:"stddeviation",stitchTiles:"stitchtiles",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDasharray:"stroke-dasharray",strokeDashoffset:"stroke-dashoffset",strokeLinecap:"stroke-linecap",strokeLinejoin:"stroke-linejoin",strokeMiterlimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",suppressContentEditableWarning:"suppresscontenteditablewarning",suppressHydrationWarning:"suppresshydrationwarning",surfaceScale:"surfacescale",systemLanguage:"systemlanguage",tableValues:"tablevalues",targetX:"targetx",targetY:"targety",textAnchor:"text-anchor",textDecoration:"text-decoration",textLength:"textlength",textRendering:"text-rendering",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",viewBox:"viewbox",viewTarget:"viewtarget",wordSpacing:"word-spacing",writingMode:"writing-mode",xChannelSelector:"xchannelselector",xHeight:"x-height",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xmlspace",xmlnsXlink:"xmlns:xlink",yChannelSelector:"ychannelselector",zoomAndPan:"zoomandpan"},Gt=/[\r\n%#()<>?[\\\]^`{|}"']/g;function Me(e){if(!e)return"";if(Array.isArray(e))return e.map(Me).join("");if(typeof e!="object")return String(e);let t=e.type;if(t==="text")throw new Error("<text> nodes are not currently supported, please convert them to <path>");let{children:n,...i}=e.props||{};return`<${t}${Object.entries(i).map(([a,o])=>` ${ht[a]||a}="${o}"`).join("")}>${Me(n)}</${t}>`}function bt(e){let{viewBox:t,viewbox:n,width:i,height:a,className:o,style:r,children:s,...l}=e.props||{};t||(t=n);let m=t.split(" ").map(p=>parseInt(p,10));return l.xmlns="http://www.w3.org/2000/svg",l.viewBox=t,l.width=m[2],l.height=m[3],`data:image/svg+xml;utf8,${`<svg${Object.entries(l).map(([p,d])=>` ${ht[p]||p}="${d}"`).join("")}>${Me(s)}</svg>`.replace(Gt,encodeURIComponent)}`}var yt={p:{display:"block",marginTop:"1em",marginBottom:"1em"},div:{display:"block"},blockquote:{display:"block",marginTop:"1em",marginBottom:"1em",marginLeft:40,marginRight:40},center:{display:"block",textAlign:"center"},hr:{display:"block",marginTop:"0.5em",marginBottom:"0.5em",marginLeft:"auto",marginRight:"auto",borderWidth:1,borderStyle:"inset"},h1:{display:"block",fontSize:"2em",marginTop:"0.67em",marginBottom:"0.67em",marginLeft:0,marginRight:0,fontWeight:"bold"},h2:{display:"block",fontSize:"1.5em",marginTop:"0.83em",marginBottom:"0.83em",marginLeft:0,marginRight:0,fontWeight:"bold"},h3:{display:"block",fontSize:"1.17em",marginTop:"1em",marginBottom:"1em",marginLeft:0,marginRight:0,fontWeight:"bold"},h4:{display:"block",marginTop:"1.33em",marginBottom:"1.33em",marginLeft:0,marginRight:0,fontWeight:"bold"},h5:{display:"block",fontSize:"0.83em",marginTop:"1.67em",marginBottom:"1.67em",marginLeft:0,marginRight:0,fontWeight:"bold"},h6:{display:"block",fontSize:"0.67em",marginTop:"2.33em",marginBottom:"2.33em",marginLeft:0,marginRight:0,fontWeight:"bold"},u:{textDecoration:"underline"},strong:{fontWeight:"bold"},b:{fontWeight:"bold"},i:{fontStyle:"italic"},em:{fontStyle:"italic"},code:{fontFamily:"monospace"},kbd:{fontFamily:"monospace"},pre:{display:"block",fontFamily:"monospace",whiteSpace:"pre",marginTop:"1em",marginBottom:"1em"},mark:{backgroundColor:"yellow",color:"black"},big:{fontSize:"larger"},small:{fontSize:"smaller"},s:{textDecoration:"line-through"}};var Dt=new Set(["color","font","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","textAlign","textTransform","textShadowOffset","textShadowColor","textShadowRadius","textDecorationLine","textDecorationStyle","textDecorationColor","whiteSpace","transform","wordBreak","opacity","filter","_viewportWidth","_viewportHeight","_inheritedClipPathId","_inheritedBackgroundClipTextPath"]);function Ge(e){let t={};for(let n in e)Dt.has(n)&&(t[n]=e[n]);return t}import{getPropertyName as en,getStylesForProperty as tn}from"css-to-react-native";import{parseElementStyle as nn}from"css-background-parser";var he=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Bt=he((e,t)=>{t.exports=["em","ex","ch","rem","vh","vw","vmin","vmax","px","mm","cm","in","pt","pc","mozmm"]}),Ut=he((e,t)=>{t.exports=["deg","grad","rad","turn"]}),Yt=he((e,t)=>{t.exports=["dpi","dpcm","dppx"]}),zt=he((e,t)=>{t.exports=["Hz","kHz"]}),Ht=he((e,t)=>{t.exports=["s","ms"]}),Xt=Bt(),xt=Ut(),wt=Yt(),Et=zt(),vt=Ht();function Be(e){if(/\.\D?$/.test(e))throw new Error("The dot should be followed by a number");if(/^[+-]{2}/.test(e))throw new Error("Only one leading +/- is allowed");if(jt(e)>1)throw new Error("Only one dot is allowed");if(/%$/.test(e)){this.type="percentage",this.value=De(e),this.unit="%";return}var t=Jt(e);if(!t){this.type="number",this.value=De(e);return}this.type=Kt(t),this.value=De(e.substr(0,e.length-t.length)),this.unit=t}Be.prototype.valueOf=function(){return this.value};Be.prototype.toString=function(){return this.value+(this.unit||"")};function se(e){return new Be(e)}function jt(e){var t=e.match(/\./g);return t?t.length:0}function De(e){var t=parseFloat(e);if(isNaN(t))throw new Error("Invalid number: "+e);return t}var Vt=[].concat(xt,Et,Xt,wt,vt);function Jt(e){var t=e.match(/\D+$/),n=t&&t[0];if(n&&Vt.indexOf(n)===-1)throw new Error("Invalid unit: "+n);return n}var qt=Object.assign(_e(xt,"angle"),_e(Et,"frequency"),_e(wt,"resolution"),_e(vt,"time"));function _e(e,t){return Object.fromEntries(e.map(n=>[n,t]))}function Kt(e){return qt[e]||"length"}import Zt from"postcss-value-parser";function Qt(e,t){try{let n=new se(e);switch(n.unit){case"px":return{absolute:n.value};case"em":return{absolute:n.value*t};case"rem":return{absolute:n.value*16};case"%":return{relative:n.value};default:return{}}}catch{return{}}}function Ue(e,t,n){switch(e){case"top":return{yRelative:0};case"left":return{xRelative:0};case"right":return{xRelative:100};case"bottom":return{yRelative:100};case"center":return{};default:let i=Qt(e,t);return i.absolute?{[n?"xAbsolute":"yAbsolute"]:i.absolute}:i.relative?{[n?"xRelative":"yRelative"]:i.relative}:{}}}function Ye(e,t){if(typeof e=="number")return{xAbsolute:e};let n;try{n=Zt(e).nodes.filter(i=>i.type==="word").map(i=>i.value)}catch{return{}}return n.length===1?Ue(n[0],t,!0):n.length===2?((n[0]==="top"||n[0]==="bottom"||n[1]==="left"||n[1]==="right")&&n.reverse(),{...Ue(n[0],t,!0),...Ue(n[1],t,!1)}):{}}var rn=new Set(["flex","flexGrow","flexShrink","flexBasis","fontWeight","lineHeight","opacity","scale","scaleX","scaleY"]),on=new Set(["lineHeight"]),kt=[1,0,0,1,0,0];function an(e,t,n,i){return e==="border"&&!n.includes(t.borderColor)?t.borderColor=i:e==="borderColor"?t.borderColor=t.borderTopColor:e==="textDecoration"&&!n.includes(t.textDecorationColor)&&(t.textDecorationColor=i),t}function St(e,t){return typeof t=="number"?rn.has(e)?on.has(e)?t:String(t):t+"px":t}function sn(e,t){return e==="lineHeight"?{lineHeight:St(e,t)}:e==="fontFamily"?{fontFamily:t.split(",").map(n=>n.trim().replace(/(^['"])|(['"]$)/g,"").toLocaleLowerCase())}:null}function ze(e,t,n,{percentage:i}={percentage:!1}){if(typeof e=="number")return e;try{let a=new se(e);if(a.type==="length")switch(a.unit){case"em":return a.value*t;case"rem":return a.value*16;case"vw":return~~(a.value*n._viewportWidth/100);case"vh":return~~(a.value*n._viewportHeight/100);default:return a.value}else if(a.type==="angle")switch(a.unit){case"deg":return a.value;case"rad":return a.value*180/Math.PI;default:return a.value}else if(a.type==="percentage"&&i)return a.value/100*t}catch{}}function Ce(e,t){let n={};for(let a in e){if(a.startsWith("_")){n[a]=e[a];continue}let o=en(a);Object.assign(n,sn(o,e[a])||an(o,tn(o,St(o,e[a]),!0),e[a],e.color||t.color))}if(n.backgroundImage){let{backgrounds:a}=nn(n);n.backgroundImage=a}let i=n.fontSize||t.fontSize;if(typeof i=="string")try{let a=new se(i);switch(a.unit){case"em":i=a.value*t.fontSize;break;case"rem":i=a.value*16;break}}catch{i=16}typeof n.fontSize<"u"&&(n.fontSize=i),n.transformOrigin&&(n.transformOrigin=Ye(n.transformOrigin,i));for(let a in n){let o=n[a];if(a==="lineHeight")typeof o=="string"&&(o=n[a]=ze(o,i,t,{percentage:!0})/i);else if(typeof o=="string"){let r=ze(o,i,t);typeof r<"u"&&(n[a]=r),o=n[a]}if(a==="opacity"&&(o=n[a]=o*t.opacity),a==="transform"){let r=[...kt],s=o;for(let l of s){let m=Object.keys(l)[0],p=l[m],d=typeof p=="string"?ze(p,i,t):p,g=[...kt];switch(m){case"translateX":g[4]=d;break;case"translateY":g[5]=d;break;case"scale":g[0]=d,g[3]=d;break;case"scaleX":g[0]=d;break;case"scaleY":g[3]=d;break;case"rotate":let h=d*Math.PI/180,f=Math.cos(h),u=Math.sin(h);g[0]=f,g[1]=u,g[2]=-u,g[3]=f;break;case"skewX":g[2]=Math.tan(d*Math.PI/180);break;case"skewY":g[1]=Math.tan(d*Math.PI/180);break}r=pe(g,r)}n.transform=r}}return n}function He(e,t,n,i,a){let o=ee(),r={...n,...Ce(yt[t],n),...Ce(i,n)};if(t==="img"){let s=parseInt(a.width),m=parseInt(a.height)/s;r.width||(r.width=s),r.height||(r.height=m*r.width)}if(t==="svg"){let l=(a.viewBox||a.viewbox).split(" ").map(g=>parseInt(g,10)),m=l[3]/l[2],{width:p,height:d}=a;typeof p>"u"&&d?typeof d=="string"&&d.endsWith("%")?p=parseInt(d)/m+"%":p=parseInt(d)/m:typeof d>"u"&&p?typeof p=="string"&&p.endsWith("%")?d=parseInt(p)*m+"%":d=parseInt(p)*m:(p||(p=l[2]),d||(d=l[3])),r.width||(r.width=p),r.height||(r.height=d)}return e.setDisplay(K(r.display,{flex:o.DISPLAY_FLEX,none:o.DISPLAY_NONE},o.DISPLAY_FLEX)),e.setAlignContent(K(r.alignContent,{stretch:o.ALIGN_STRETCH,center:o.ALIGN_CENTER,"flex-start":o.ALIGN_FLEX_START,"flex-end":o.ALIGN_FLEX_END,"space-between":o.ALIGN_SPACE_BETWEEN,"space-around":o.ALIGN_SPACE_AROUND,baseline:o.ALIGN_BASELINE,normal:o.ALIGN_AUTO},o.ALIGN_AUTO)),e.setAlignItems(K(r.alignItems,{stretch:o.ALIGN_STRETCH,center:o.ALIGN_CENTER,"flex-start":o.ALIGN_FLEX_START,"flex-end":o.ALIGN_FLEX_END,baseline:o.ALIGN_BASELINE,normal:o.ALIGN_AUTO},o.ALIGN_FLEX_START)),e.setAlignSelf(K(r.alignSelf,{stretch:o.ALIGN_STRETCH,center:o.ALIGN_CENTER,"flex-start":o.ALIGN_FLEX_START,"flex-end":o.ALIGN_FLEX_END,baseline:o.ALIGN_BASELINE,normal:o.ALIGN_AUTO},o.ALIGN_AUTO)),e.setJustifyContent(K(r.justifyContent,{center:o.JUSTIFY_CENTER,"flex-start":o.JUSTIFY_FLEX_START,"flex-end":o.JUSTIFY_FLEX_END,"space-between":o.JUSTIFY_SPACE_BETWEEN,"space-around":o.JUSTIFY_SPACE_AROUND},o.JUSTIFY_FLEX_START)),e.setFlexDirection(K(r.flexDirection,{row:o.FLEX_DIRECTION_ROW,column:o.FLEX_DIRECTION_COLUMN,"row-reverse":o.FLEX_DIRECTION_ROW_REVERSE,"column-reverse":o.FLEX_DIRECTION_COLUMN_REVERSE},o.FLEX_DIRECTION_ROW)),e.setFlexWrap(K(r.flexWrap,{wrap:o.WRAP_WRAP,nowrap:o.WRAP_NO_WRAP,"wrap-reverse":o.WRAP_WRAP_REVERSE},o.WRAP_WRAP)),typeof r.flexBasis<"u"&&e.setFlexBasis(r.flexBasis),e.setFlexGrow(typeof r.flexGrow>"u"?0:r.flexGrow),e.setFlexShrink(typeof r.flexShrink>"u"?0:r.flexShrink),typeof r.maxHeight<"u"&&e.setMaxHeight(r.maxHeight),typeof r.maxWidth<"u"&&e.setMaxWidth(r.maxWidth),typeof r.minHeight<"u"&&e.setMinHeight(r.minHeight),typeof r.minWidth<"u"&&e.setMinWidth(r.minWidth),e.setOverflow(K(r.overflow,{visible:o.OVERFLOW_VISIBLE,hidden:o.OVERFLOW_HIDDEN},o.OVERFLOW_VISIBLE)),e.setMargin(o.EDGE_TOP,r.marginTop||0),e.setMargin(o.EDGE_BOTTOM,r.marginBottom||0),e.setMargin(o.EDGE_LEFT,r.marginLeft||0),e.setMargin(o.EDGE_RIGHT,r.marginRight||0),e.setBorder(o.EDGE_TOP,r.borderWidth||0),e.setBorder(o.EDGE_BOTTOM,r.borderWidth||0),e.setBorder(o.EDGE_LEFT,r.borderWidth||0),e.setBorder(o.EDGE_RIGHT,r.borderWidth||0),e.setPadding(o.EDGE_TOP,r.paddingTop||0),e.setPadding(o.EDGE_BOTTOM,r.paddingBottom||0),e.setPadding(o.EDGE_LEFT,r.paddingLeft||0),e.setPadding(o.EDGE_RIGHT,r.paddingRight||0),e.setPositionType(K(r.position,{absolute:o.POSITION_TYPE_ABSOLUTE,relative:o.POSITION_TYPE_RELATIVE},o.POSITION_TYPE_RELATIVE)),typeof r.top<"u"&&e.setPosition(o.EDGE_TOP,r.top),typeof r.bottom<"u"&&e.setPosition(o.EDGE_BOTTOM,r.bottom),typeof r.left<"u"&&e.setPosition(o.EDGE_LEFT,r.left),typeof r.right<"u"&&e.setPosition(o.EDGE_RIGHT,r.right),typeof r.height<"u"?e.setHeight(r.height):e.setHeightAuto(),typeof r.width<"u"?e.setWidth(r.width):e.setWidthAuto(),[r,Ge(r)]}function le({left:e,top:t,width:n,height:i},a,o,r){var l,m,p,d;let s;if(o)s=a;else{let g=(m=r==null?void 0:r.xAbsolute)!=null?m:((l=r==null?void 0:r.xRelative)!=null?l:50)*n/100,h=(d=r==null?void 0:r.yAbsolute)!=null?d:((p=r==null?void 0:r.yRelative)!=null?p:50)*i/100,f=e+g,u=t+h;s=pe([1,0,0,1,f,u],pe(a,[1,0,0,1,-f,-u])),a.__parent&&(s=pe(a.__parent,s)),a.splice(0,6,...s)}return`matrix(${s.map(g=>g.toFixed(2)).join(",")})`}function Tt({left:e,top:t,width:n,height:i,isInheritingTransform:a},o){let r="",s=1;return o.transform&&(r=le({left:e,top:t,width:n,height:i},o.transform,a,o.transformOrigin)),o.opacity&&(s=+o.opacity),{matrix:r,opacity:s}}function Xe({id:e,content:t,filter:n,left:i,top:a,width:o,height:r,matrix:s,opacity:l,image:m,clipPathId:p,debug:d,shape:g,decorationShape:h},f){let u="";if(d&&(u=y("rect",{x:i,y:a-r,width:o,height:r,fill:"transparent",stroke:"#575eff","stroke-width":1,transform:s||void 0,"clip-path":p?`url(#${p})`:void 0})),m){let x={href:m,x:i,y:a,width:o,height:r,transform:s||void 0,"clip-path":p?`url(#${p})`:void 0,style:f.filter?`filter:${f.filter}`:void 0};return[(n?`${n}<g filter="url(#satori_s-${e})">`:"")+y("image",{...x,opacity:l!==1?l:void 0})+(h||"")+(n?"</g>":"")+u,""]}let b={x:i,y:a,width:o,height:r,"font-weight":f.fontWeight,"font-style":f.fontStyle,"font-size":f.fontSize,"font-family":f.fontFamily,"letter-spacing":f.letterSpacing||void 0,transform:s||void 0,"clip-path":p?`url(#${p})`:void 0,style:f.filter?`filter:${f.filter}`:void 0};return[(n?`${n}<g filter="url(#satori_s-${e})">`:"")+y("text",{...b,fill:f.color,opacity:l!==1?l:void 0},t)+(h||"")+(n?"</g>":"")+u,g?y("text",b,t):""]}function fe({id:e,width:t,height:n},i){if(!i.shadowColor||!i.shadowOffset||typeof i.shadowRadius>"u")return"";let a=i.shadowRadius*i.shadowRadius/4,o=Math.min(i.shadowOffset.width-a,0),r=Math.max(i.shadowOffset.width+a+t,t),s=Math.min(i.shadowOffset.height-a,0),l=Math.max(i.shadowOffset.height+a+n,n);return`<defs><filter id="satori_s-${e}" x="${o/t*100}%" y="${s/n*100}%" width="${(r-o)/t*100}%" height="${(l-s)/n*100}%"><feDropShadow dx="${i.shadowOffset.width}" dy="${i.shadowOffset.height}" stdDeviation="${i.shadowRadius/2}" flood-color="${i.shadowColor}" flood-opacity="1"/></filter></defs>`}function je({width:e,left:t,top:n,ascender:i,clipPathId:a},o){let{textDecorationColor:r,textDecorationStyle:s,textDecorationLine:l,fontSize:m}=o;if(!l||l==="none")return"";let p=Math.max(1,m*.1),d=l==="line-through"?n+i*.5:l==="underline"?n+i*1.1:n,g=s==="dashed"?`${p*1.2} ${p*2}`:s==="dotted"?`0 ${p*2}`:void 0;return y("line",{x1:t,y1:d,x2:t+e,y2:d,stroke:r,"stroke-width":p,"stroke-dasharray":g,"stroke-linecap":s==="dotted"?"round":"square","clip-path":a?`url(#${a})`:void 0})}var Ve=void 0;async function*Je(e,t){var ft;let n=ee(),{parentStyle:i,inheritedStyle:a,parent:o,font:r,id:s,isInheritingTransform:l,debug:m,embedFont:p,graphemeImages:d,canLoadAdditionalAssets:g}=t;i.textTransform==="uppercase"?e=e.toLocaleUpperCase(Ve):i.textTransform==="lowercase"?e=e.toLocaleLowerCase(Ve):i.textTransform==="capitalize"&&(e=ae(e,"word").map(_=>ae(_,"grapheme").map((I,L)=>L===0?I.toLocaleUpperCase(Ve):I).join("")).join(""));let h=K(i.wordBreak,{normal:"word","break-all":"grapheme","break-word":"grapheme","keep-all":"word"},"word"),f=ae(e,h),u=n.Node.create();u.setAlignItems(n.ALIGN_BASELINE),i.textAlign==="left"?u.setJustifyContent(n.JUSTIFY_FLEX_START):i.textAlign==="center"?u.setJustifyContent(n.JUSTIFY_CENTER):i.textAlign==="right"?u.setJustifyContent(n.JUSTIFY_FLEX_END):i.textAlign==="justify"&&u.setJustifyContent(n.JUSTIFY_SPACE_BETWEEN),o.insertChild(u,o.getChildCount());let{textAlign:b,textOverflow:x,whiteSpace:E,lineHeight:F,filter:$,_inheritedBackgroundClipTextPath:N}=i,W=i.fontSize,R=r.getEngine(W,F,i),V=g?f.filter(_=>!R.check(_)):[];yield V,V.length&&(R=r.getEngine(W,F,i));let A=[],v=[],M=[],G=[],Y=new Map,k=_=>{let I=0;for(let L of _){if(Y.has(L)){I+=Y.get(L);continue}let U=R.measure(L,i);Y.set(L,U),I+=U}return I},O=0,J=[],c=0;for(let _ of f){let I=!1,L=d&&d[_];E==="pre"?I=_[0]===`
2
- `:E!=="nowrap"&&(L||Re.includes(_[0]))&&(I=!0),I?(E==="nowrap"?c+=k(J)+i.fontSize:(O=Math.max(O,k(J)),L&&(O=Math.max(O,i.fontSize))),J=[]):(!Re.includes(_[0])||!J.length)&&J.push(_===`
3
- `?" ":_)}O=Math.max(O,k(J)+c);let w=o.getMinWidth(),C=o.getMaxWidth(),Z=o.getWidth();isNaN(Z.value)&&(isNaN(w.value)||w.unit===1&&w.value>O)&&(isNaN(C.value)||C.unit===1&&(O=Math.min(O,C.value)),o.setMinWidth(O)),typeof i.flexShrink>"u"&&o.setFlexShrink(1);let ge=E==="pre-wrap"||E==="pre";u.setMeasureFunc(_=>{let I=0,L="",U=0,z=0,H=0,X=-1,re=0,P=0,ie=0;A=[],M=[0];for(let ne=0;ne<f.length;ne++){let D=f[ne];if(!ge&&Re.includes(D[0]))L||(L=" "),U=k([L]),G[ne]=null;else{let oe=ge&&D===`
4
- `,j=oe?0:d&&d[D]?i.fontSize:k([D]);z||(L="",U=0);let B=U||",.!?:-@)>]}%#".indexOf(D[0])<0,q=!z||!!U;if(oe||ne&&B&&z+U+j>_&&E!=="nowrap"&&E!=="pre")A.push(z),v.push(ie),I++,re+=P,z=j,P=j?R.height(D):0,ie=j?R.baseline(D):0,M.push(1),X=-1,oe||(H=Math.max(H,_));else{z+=U+j;let de=R.height(D);de>P&&(P=de,ie=R.baseline(D)),q&&M[M.length-1]++}L="",U=0,q&&X++,H=Math.max(H,z),G[ne]={y:re,x:z-j,width:j,line:I,lineIndex:X}}}return z&&(I++,A.push(z),v.push(ie),re+=P),{width:H,height:re}});let[Ot,Ft]=yield,Oe="",we="",te=a._inheritedClipPathId,{left:it,top:ot,width:Ee,height:at}=u.getComputedLayout(),Fe=o.getComputedWidth()-o.getComputedPadding(n.EDGE_LEFT)-o.getComputedPadding(n.EDGE_RIGHT)-o.getComputedBorder(n.EDGE_LEFT)-o.getComputedBorder(n.EDGE_RIGHT),ue=Ot+it,ce=Ft+ot,{matrix:Q,opacity:ve}=Tt({left:it,top:ot,width:Ee,height:at,isInheritingTransform:l},i),ke="";i.textShadowOffset&&(ke=fe({width:Ee,height:at,id:s},{shadowColor:i.textShadowColor,shadowOffset:i.textShadowOffset,shadowRadius:i.textShadowRadius}));let me="",Se="",st="",Pe=-1,lt=x==="ellipsis"?k(["\u2026"]):0,Pt=x==="ellipsis"?k([" "]):0,Te={};for(let _=0;_<f.length;_++){if(!G[_])continue;let I=G[_],L=f[_],U=null,z=d?d[L]:null,H=I.y,X=I.x,re=I.width,P=I.line;if(P===Pe)continue;let ie=!1;if(A.length>1){let B=Ee-A[P];if(b==="right"||b==="end")X+=B;else if(b==="center")X+=B/2;else if(b==="justify"&&P<A.length-1){let q=M[P];X+=(q>1?B/(q-1):0)*I.lineIndex,ie=!0}}if(Te[P]||(Te[P]=[X,ie?Ee:A[P]]),x==="ellipsis"&&A[P]>Fe&&I.x+re+lt+Pt>Fe){let B=ae(L,"grapheme"),q="",de=0;for(let ut of B){let ct=I.x+k([q+ut]);if(q&&ct+lt>Fe)break;q+=ut,de=ct}L=q+"\u2026",Pe=P,Te[P][1]=de}let ne=v[P],D=R.baseline(L),oe=R.height(L),j=ne-D;if(z?H+=0:p?(U=R.getSVG(L,{...i,left:ue+X,top:ce+H+D+j,letterSpacing:i.letterSpacing}),m&&(st+=y("rect",{x:ue+X,y:ce+H+j,width:I.width,height:oe,fill:"transparent",stroke:"#575eff","stroke-width":1,transform:Q||void 0,"clip-path":te?`url(#${te})`:void 0})+y("line",{x1:ue+X,x2:ue+X+I.width,y1:ce+H+j+D,y2:ce+H+j+D,stroke:"#14c000","stroke-width":1,transform:Q||void 0,"clip-path":te?`url(#${te})`:void 0}))):H+=D+j,i.textDecorationLine&&(P!==((ft=G[_+1])==null?void 0:ft.line)||Pe===P)){let B=Te[P];B&&!B[2]&&(me+=je({left:ue+B[0],top:ce+oe*+P,width:B[1],ascender:R.baseline(L),clipPathId:te},i),B[2]=1)}if(U!==null)Se+=U+" ";else{let[B,q]=Xe({content:L,filter:ke,id:s,left:ue+X,top:ce+H,width:re,height:oe,matrix:Q,opacity:ve,image:z,clipPathId:te,debug:m,shape:!!N,decorationShape:me},i);Oe+=B,we+=q,me=""}}if(Se){let _=i.color!=="transparent"&&ve!==0?y("path",{fill:i.color,d:Se,transform:Q||void 0,opacity:ve!==1?ve:void 0,"clip-path":te?`url(#${te})`:void 0,style:$?`filter:${$}`:void 0}):"";N&&(we=y("path",{d:Se,transform:Q||void 0})),Oe+=(ke?ke+y("g",{filter:`url(#satori_s-${s})`},_+me):_+me)+st}return we&&(i._inheritedBackgroundClipTextPath.value+=we),Oe}var qe=qe||{};qe.parse=function(){var e={linearGradient:/^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,repeatingLinearGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,radialGradient:/^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,repeatingRadialGradient:/^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,sideOrCorner:/^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,extentKeywords:/^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,positionKeywords:/^(left|center|right|top|bottom)/i,pixelValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,percentageValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,emValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,angleValue:/^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,startCall:/^\(/,endCall:/^\)/,comma:/^,/,hexColor:/^\#([0-9a-fA-F]+)/,literalColor:/^([a-zA-Z]+)/,rgbColor:/^rgb/i,rgbaColor:/^rgba/i,number:/^(([0-9]*\.[0-9]+)|([0-9]+\.?))/},t="";function n(c){var w=new Error(t+": "+c);throw w.source=t,w}function i(){var c=a();return t.length>0&&n("Invalid input not EOF"),c}function a(){return F(o)}function o(){return r("linear-gradient",e.linearGradient,l)||r("repeating-linear-gradient",e.repeatingLinearGradient,l)||r("radial-gradient",e.radialGradient,d)||r("repeating-radial-gradient",e.repeatingRadialGradient,d)}function r(c,w,C){return s(w,function(Z){var ge=C();return ge&&(O(e.comma)||n("Missing comma before color stops")),{type:c,orientation:ge,colorStops:F($)}})}function s(c,w){var C=O(c);if(C){O(e.startCall)||n("Missing (");var Z=w(C);return O(e.endCall)||n("Missing )"),Z}}function l(){return m()||p()}function m(){return k("directional",e.sideOrCorner,1)}function p(){return k("angular",e.angleValue,1)}function d(){var c,w=g(),C;return w&&(c=[],c.push(w),C=t,O(e.comma)&&(w=g(),w?c.push(w):t=C)),c}function g(){var c=h()||f();if(c)c.at=b();else{var w=u();if(w){c=w;var C=b();C&&(c.at=C)}else{var Z=x();Z&&(c={type:"default-radial",at:Z})}}return c}function h(){var c=k("shape",/^(circle)/i,0);return c&&(c.style=Y()||u()),c}function f(){var c=k("shape",/^(ellipse)/i,0);return c&&(c.style=M()||u()),c}function u(){return k("extent-keyword",e.extentKeywords,1)}function b(){if(k("position",/^at/,0)){var c=x();return c||n("Missing positioning value"),c}}function x(){var c=E();if(c.x||c.y)return{type:"position",value:c}}function E(){return{x:M(),y:M()}}function F(c){var w=c(),C=[];if(w)for(C.push(w);O(e.comma);)w=c(),w?C.push(w):n("One extra comma");return C}function $(){var c=N();return c||n("Expected color definition"),c.length=M(),c}function N(){return R()||A()||V()||W()}function W(){return k("literal",e.literalColor,0)}function R(){return k("hex",e.hexColor,1)}function V(){return s(e.rgbColor,function(){return{type:"rgb",value:F(v)}})}function A(){return s(e.rgbaColor,function(){return{type:"rgba",value:F(v)}})}function v(){return O(e.number)[1]}function M(){return k("%",e.percentageValue,1)||G()||Y()}function G(){return k("position-keyword",e.positionKeywords,1)}function Y(){return k("px",e.pixelValue,1)||k("em",e.emValue,1)}function k(c,w,C){var Z=O(w);if(Z)return{type:c,value:Z[C]}}function O(c){var w,C;return C=/^[\n\r\t\s]+/.exec(t),C&&J(C[0].length),w=c.exec(t),w&&J(w[0].length),w}function J(c){t=t.substr(c)}return function(c){return t=c.toString(),i()}}();var Ke=qe;var Rt=mt(100),Ze=new Map,ln=["image/png","image/jpeg","image/gif","image/svg+xml"];function fn(e){let t="",n=new Uint8Array(e);for(let i=0;i<n.byteLength;i++)t+=String.fromCharCode(n[i]);return btoa(t)}async function Ie(e){if(!e)throw new Error("Image URL is not provided");if(e.startsWith("data:"))return e;if(!globalThis.fetch)throw new Error("`fetch` is required to be polyfilled to load images.");if(Ze.has(e))return Ze.get(e);let t=Rt.get(e);if(t)return t;let n=new Promise((i,a)=>{let o;fetch(e).then(r=>{if(o=r.headers.get("content-type").toLowerCase(),!ln.includes(o))throw new Error(`Unsupported image type: ${o}`);return r.arrayBuffer()}).then(r=>{let s=`data:${o};base64,${fn(r)}`;Rt.set(e,s),i(s)}).catch(a)});return Ze.set(e,n),n}function un(e){return e.type==="literal"?e.value:e.type==="hex"?`#${e.value}`:e.type==="rgb"?`rgb(${e.value.join(",")})`:e.type==="rgba"?`rgba(${e.value.join(",")})`:"transparent"}function cn(e,t){return typeof e=="string"&&e.endsWith("%")?t*parseFloat(e)/100:+e}function _t(e,{x:t,y:n,defaultX:i,defaultY:a}){return(e?e.split(" ").map(o=>{try{let r=new se(o);return r.type==="length"||r.type==="number"?r.value:r.value+r.unit}catch{return null}}).filter(o=>o!==null):[i,a]).map((o,r)=>cn(o,[t,n][r]))}function Ct(e,t){let n=[];for(let r of t){let s=un(r);if(!n.length&&(n.push({offset:0,color:s}),typeof r.length>"u"||r.length.value==="0"))continue;let l=typeof r.length>"u"?void 0:r.length.type==="%"?r.length.value/100:r.length.value/e;n.push({offset:l,color:s})}n.length||n.push({offset:0,color:"transparent"});let i=n[n.length-1];i.offset!==1&&(typeof i.offset>"u"?i.offset=1:n.push({offset:1,color:i.color}));let a=0,o=1;for(let r=0;r<n.length;r++)if(typeof n[r].offset>"u"){for(o<r&&(o=r);typeof n[o].offset>"u";)o++;n[r].offset=(n[o].offset-n[a].offset)/(o-a)*(r-a)+n[a].offset}else a=r;return n}async function Qe({id:e,width:t,height:n},{image:i,size:a,position:o,repeat:r}){r=r||"repeat";let s=r==="repeat-x"||r==="repeat",l=r==="repeat-y"||r==="repeat",m=_t(a,{x:t,y:n,defaultX:t,defaultY:n}),p=_t(o,{x:t,y:n,defaultX:0,defaultY:0});if(i.startsWith("linear-gradient(")){let d=Ke.parse(i)[0],g,h,f,u;if(d.orientation.type==="directional")[g,h,f,u]={top:[0,1,0,0],bottom:[0,0,0,1],left:[1,0,0,0],right:[0,0,1,0]}[d.orientation.value];else if(d.orientation.type==="angular"){let x=+d.orientation.value/180*Math.PI-Math.PI/2,E=Math.cos(x),F=Math.sin(x);g=0,h=0,f=E,u=F,f<0&&(g-=f,f=0),u<0&&(h-=u,u=0)}let b=Ct(t,d.colorStops);return[`satori_bi${e}`,`<linearGradient id="satori_bi${e}" x1="${g}" y1="${h}" x2="${f}" y2="${u}">${b.map(x=>`<stop offset="${x.offset*100}%" stop-color="${x.color}"/>`).join("")}</linearGradient>`]}if(i.startsWith("radial-gradient(")){let d=Ke.parse(i)[0],g=d.orientation[0],[h,f]=m,u="circle",b=h/2,x=f/2;if(g.type==="shape"){if(u=g.value,g.at)if(g.at.type==="position")b=g.at.value.x.value,x=g.at.value.y.value;else throw new Error("orientation.at.type not implemented: "+g.at.type)}else throw new Error("orientation.type not implemented: "+g.type);let E=Ct(t,d.colorStops),F=`satori_radial_${e}`,$=`satori_pattern_${e}`,N={},W=Math.max(Math.abs(h-b),Math.abs(b)),R=Math.max(Math.abs(f-x),Math.abs(x));if(u==="circle")N.r=Math.sqrt(W*W+R*R);else if(u==="ellipse"){let v=R!==0?W/R:1;N.ry=Math.sqrt(W*W+R*R*v*v)/v,N.rx=N.ry*v}let V=y("pattern",{id:$,x:p[0],y:p[1],width:s?h:"100%",height:l?f:"100%",patternUnits:"userSpaceOnUse"},y("radialGradient",{id:F},E.map(v=>y("stop",{offset:v.offset,"stop-color":v.color})).join(""))+y(u,{cx:b,cy:x,width:h,height:f,...N,fill:`url(#${F})`}));return[$,V]}if(i.startsWith("url(")){let d=await Ie(i.slice(4,-1));return[`satori_bi${e}`,y("pattern",{id:`satori_bi${e}`,patternContentUnits:"userSpaceOnUse",patternUnits:"userSpaceOnUse",x:p[0],y:p[1],width:s?m[0]:"100%",height:l?m[1]:"100%"},y("image",{x:0,y:0,width:m[0],height:m[1],href:d}))]}}function Le(e,t,n){return n<e+t&&(n/2<e&&n/2<t?e=t=n/2:n/2<e?e=n-t:n/2<t&&(t=n-e)),[e,t]}function be({left:e,top:t,width:n,height:i},a){let{borderTopLeftRadius:o,borderTopRightRadius:r,borderBottomLeftRadius:s,borderBottomRightRadius:l}=a;return o=Math.min(o||0,n,i),r=Math.min(r||0,n,i),s=Math.min(s||0,n,i),l=Math.min(l||0,n,i),!o&&!r&&!s&&!l?"":([o,r]=Le(o,r,n),[o,s]=Le(o,s,i),[r,l]=Le(r,l,i),[s,l]=Le(s,l,n),`M${e+o},${t} h${n-o-r} a${r},${r} 0 0 1 ${r},${r} v${i-r-l} a${l},${l} 0 0 1 ${-l},${l} h${l+s-n} a${s},${s} 0 0 1 ${-s},${-s} v${s+o-i} a${o},${o} 0 0 1 ${o},${-o}`)}function et({left:e,top:t,width:n,height:i,path:a,id:o},r){return r.overflow!=="hidden"?"":a?y("clipPath",{id:`satori_cp-${o}`,"clip-path":r._inheritedClipPathId?`url(#${r._inheritedClipPathId})`:void 0},y("path",{x:e,y:t,width:n,height:i,d:a})):y("clipPath",{id:`satori_cp-${o}`,"clip-path":r._inheritedClipPathId?`url(#${r._inheritedClipPathId})`:void 0},y("rect",{x:e,y:t,width:n,height:i}))}async function tt({id:e,left:t,top:n,width:i,height:a,isInheritingTransform:o,debug:r},s){if(s.display==="none")return"";let l="rect",m="transparent",p="",d=0,g="",h="",f=[],u=1,b="";s.backgroundColor&&f.push(s.backgroundColor),s.borderWidth&&(d=s.borderWidth,m=s.borderColor,s.borderStyle==="dashed"&&(p=d*2+" "+d)),s.opacity&&(u=+s.opacity),s.transform&&(g=le({left:t,top:n,width:i,height:a},s.transform,o,s.transformOrigin));let x="";if(s.backgroundImage){let A=[];for(let v=0;v<s.backgroundImage.length;v++){let M=s.backgroundImage[v],G=await Qe({id:e+"_"+v,width:i,height:a},M);G&&A.push(G)}for(let v of A)f.push(`url(#${v[0]})`),h+=v[1],v[2]&&(x+=v[2])}let E=be({left:t,top:n,width:i,height:a},s);E&&(l="path");let F=et({left:t,top:n,width:i,height:a,path:E,id:e},s),$=s._inheritedClipPathId,N=fe({width:i,height:a,id:e},s);r&&(b=y("rect",{x:t,y:n,width:i,height:a,fill:"transparent",stroke:"#ff5757","stroke-width":1,"stroke-dasharray":p||void 0,transform:g||void 0,"clip-path":$?`url(#${$})`:void 0})),f.length||f.push("transparent");let{backgroundClip:W,filter:R}=s,V=f.map((A,v)=>{if(A==="transparent"&&!(v===f.length-1&&d))return"";let M=!!d,G=v===f.length-1&&M&&W!=="text",Y=W==="text"?`url(#satori_bct-${e})`:$?`url(#${$})`:void 0;return G&&(h+=y("clipPath",{id:`satori_bc-${e}`,"clip-path":Y},y(l,{x:t,y:n,width:i,height:a,d:E||void 0})),Y=`url(#satori_bc-${e})`),y(l,{x:t,y:n,width:i,height:a,fill:A,stroke:G||M?m:void 0,"stroke-width":G?d*2:M?1:void 0,"stroke-dasharray":p||void 0,d:E||void 0,transform:g||void 0,"clip-path":Y,style:R?`filter:${R}`:void 0})}).join("");return W==="text"&&d&&(V=y(l,{x:t,y:n,width:i,height:a,fill:"transparent",stroke:m,"stroke-width":d*2,"stroke-dasharray":p||void 0,d:E||void 0,transform:g||void 0,"clip-path":$?`url(#${$})`:void 0})+V),(h?`<defs>${h}</defs>`:"")+F+(N?`${N}<g filter="url(#satori_s-${e})">`:"")+(u!==1?`<g opacity="${u}">`:"")+(x||V)+(u!==1?"</g>":"")+(N?"</g>":"")+b}function Ae({id:e,left:t,top:n,width:i,height:a,src:o,debug:r,isInheritingTransform:s},l){if(l.display==="none")return"";let m="",p=1,d="",g=l.objectFit==="contain"?"xMidYMid":l.objectFit==="cover"?"xMidYMid slice":"none",h=be({left:t,top:n,width:i,height:a},l),f=l._inheritedClipPathId;h&&(m=y("clipPath",{id:`satori_c-${e}`,"clip-path":f?`url(#${f})`:void 0},y("path",{x:t,y:n,width:i,height:a,d:h}))),l.opacity&&(p=+l.opacity);let u=fe({width:i,height:a,id:e},l);return l.transform&&(d=le({left:t,top:n,width:i,height:a},l.transform,s,l.transformOrigin)),u+(u?`<g filter="url(#satori_s-${e})">`:"")+m+y("image",{x:t,y:n,width:i,height:a,href:o,preserveAspectRatio:g,transform:d||void 0,"clip-path":m?`url(#satori_c-${e})`:f?`url(#${f})`:void 0})+(u?"</g>":"")}async function*ye(e,t){var J;let n=ee(),{id:i,inheritedStyle:a,parent:o,font:r,debug:s,embedFont:l=!0,graphemeImages:m,canLoadAdditionalAssets:p}=t;if(e===null||typeof e>"u")return yield,yield,"";if(!We(e)||typeof e.type=="function"){let c;if(!We(e))c=Je(String(e),t),yield(await c.next()).value;else{if(pt(e.type))throw new Error("Class component is not supported.");c=ye(e.type(e.props),t),yield(await c.next()).value}await c.next();let w=yield;return(await c.next(w)).value}let{type:d,props:g}=e,{style:h,children:f}=g||{},u=n.Node.create();o.insertChild(u,o.getChildCount());let[b,x]=He(u,d,a,h,g),E=b.transform===a.transform;if(E||(b.transform.__parent=a.transform),b.overflow==="hidden"&&(x._inheritedClipPathId=`satori_cp-${i}`),b.backgroundClip==="text"){let c={value:""};x._inheritedBackgroundClipTextPath=c,b._inheritedBackgroundClipTextPath=c}let F=typeof f>"u"?[]:[].concat(f).flat(1/0),$=[],N=0,W=[];for(let c of F){let w=ye(c,{id:i+"-"+N++,parentStyle:b,inheritedStyle:x,isInheritingTransform:!0,parent:u,font:r,embedFont:l,debug:s,graphemeImages:m,canLoadAdditionalAssets:p});p?W.push(...(await w.next()).value||[]):await w.next(),$.push(w)}yield W;for(let c of $)await c.next();let[R,V]=yield;b.position==="absolute"&&u.calculateLayout();let{left:A,top:v,width:M,height:G}=u.getComputedLayout();A+=R,v+=V;let Y="",k="",O="";if(d==="img"){let c=await Ie(g.src);k=Ae({id:i,left:A,top:v,width:M,height:G,src:c,isInheritingTransform:E,debug:s},b)}else if(d==="svg"){let c=bt(e);k=Ae({id:i,left:A,top:v,width:M,height:G,src:c,isInheritingTransform:E,debug:s},b)}else{let c=(J=h==null?void 0:h.display)!=null?J:"block";if(d==="div"&&f&&typeof f!="string"&&c!=="flex"&&c!=="none")throw new Error(`Expected <div> to have style={{display: 'flex'}} but received style={{display: '${c}'}}`);k=await tt({id:i,left:A,top:v,width:M,height:G,isInheritingTransform:E,debug:s},b)}for(let c of $)Y+=(await c.next([A,v])).value;return b._inheritedBackgroundClipTextPath&&(O+=y("clipPath",{id:`satori_bct-${i}`,"clip-path":b._inheritedClipPathId?`url(#${b._inheritedClipPathId})`:void 0},b._inheritedBackgroundClipTextPath.value)),O+k+Y}import dn from"@shuding/opentype.js";function pn(e,t,[n,i],[a,o]){if(n!==a)return n?!a||n===e?-1:a===e?1:e===400&&n===500||e===500&&n===400?-1:e===400&&a===500||e===500&&a===400?1:e<400?n<e&&a<e?a-n:n<e?-1:a<e?1:n-a:e<n&&e<a?n-a:e<n?-1:e<a?1:a-n:1;if(i!==o){if(i===t)return-1;if(o===t)return 1}return-1}var xe=class{constructor(t){this.fonts=new Map;this.addFonts(t)}get({name:t,weight:n,style:i}){if(!this.fonts.has(t))return null;n==="normal"&&(n=400),n==="bold"&&(n=700);let a=[...this.fonts.get(t)],o=a[0];for(let r=1;r<a.length;r++){let[,s,l]=o,[,m,p]=a[r];pn(n,i,[s,l],[m,p])>0&&(o=a[r])}return o[0]}addFonts(t){for(let n of t){let i=n.data,a=dn.parse("buffer"in i?i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength):i,{lowMemory:!0}),o=a.charToGlyphIndex;a.charToGlyphIndex=s=>{let l=o.call(a,s);return l===0&&a._trackBrokenChars&&a._trackBrokenChars.push(s),l},this.defaultFont||(this.defaultFont=a);let r=n.name.toLowerCase();this.fonts.has(r)||this.fonts.set(r,[]),this.fonts.get(r).push([a,n.weight,n.style])}}getEngine(t=16,n=1.2,{fontFamily:i,fontWeight:a=400,fontStyle:o="normal"}){i=Array.isArray(i)?i:[i];let r=i.map(f=>this.get({name:f,weight:a,style:o})).filter(Boolean),s=Array.from(this.fonts.keys());for(let f of s)i.includes(f)||r.push(this.get({name:f,weight:a,style:o}));let l=new Map,m=(f,u=!0)=>{let b=f.charCodeAt(0);if(l.has(b))return l.get(b);let x=r.find((E,F)=>!!E.charToGlyphIndex(f)||u&&F===r.length-1);return x&&l.set(b,x),x},p=(f,u=!1)=>{var x,E;return((u?(E=(x=f.tables)==null?void 0:x.os2)==null?void 0:E.sTypoAscender:0)||f.ascender)/f.unitsPerEm*t},d=(f,u=!1)=>{var x,E;return((u?(E=(x=f.tables)==null?void 0:x.os2)==null?void 0:E.sTypoDescender:0)||f.descender)/f.unitsPerEm*t},g=f=>m(f,!1),h={check:f=>{let u=g(f);return u?(u._trackBrokenChars=[],u.stringToGlyphs(f),u._trackBrokenChars.length?(u._trackBrokenChars=void 0,!1):!0):!1},baseline:(f,u=typeof f>"u"?r[0]:m(f))=>{let b=p(u,!0),x=d(u,!0),E=h.height(f,u),{yMax:F,yMin:$}=u.tables.head,N=b-x,W=(F/(F-$)-1)*N;return E*((1.2/n+1)/2)+W},height:(f,u=typeof f>"u"?r[0]:m(f))=>(p(u)-d(u))*(n/1.2),measure:(f,u)=>this.measure(m,f,u),getSVG:(f,u)=>this.getSVG(m,f,u)};return h}patchFontFallbackResolver(t,n){let i=[];t._trackBrokenChars=i;let a=t.stringToGlyphs;return t.stringToGlyphs=(o,...r)=>{let s=a.call(t,o,...r);for(let l=0;l<s.length;l++)if(s[l].unicode===void 0){let m=i.shift(),p=n(m);p!==t&&(s[l]=p.charToGlyph(m))}return s},()=>{t.stringToGlyphs=a,t._trackBrokenChars=void 0}}measure(t,n,{fontSize:i,letterSpacing:a=0}){let o=t(n),r=this.patchFontFallbackResolver(o,t);try{return o.getAdvanceWidth(n,i,{letterSpacing:a/i})}finally{r()}}getSVG(t,n,{fontSize:i,top:a,left:o,letterSpacing:r=0}){let s=t(n),l=this.patchFontFallbackResolver(s,t);try{return s.getPath(n,o,a,i,{letterSpacing:r/i}).toPathData(1)}finally{l()}}};function nt({width:e,height:t,content:n}){return y("svg",{width:e,height:t,viewBox:`0 0 ${e} ${t}`,xmlns:"http://www.w3.org/2000/svg"},n)}var It={emoji:/\p{RI}\p{RI}|\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?(\u{200D}\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?)+|\p{EPres}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?|\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})/u,ja:/\p{scx=Hira}|\p{scx=Kana}|[,;:]/u,ko:/\p{scx=Hangul}/u,zh:/\p{scx=Han}/u,th:/\p{scx=Thai}/u,bn:/\p{scx=Bengali}/u,ar:/\p{scx=Arabic}/u,ta:/\p{scx=Tamil}/u,ml:/\p{scx=Malayalam}/u,he:/\p{scx=Hebrew}/u,te:/\p{scx=Telugu}/u,devanagari:/\p{scx=Devanagari}/u};function Lt(e){for(let t in It)if(It[t].test(e))return t;return"unknown"}var rt=new WeakMap;async function At(e,t){let n=ee();if(!n)throw new Error("Satori is not initialized.");let i;rt.has(t.fonts)?i=rt.get(t.fonts):rt.set(t.fonts,i=new xe(t.fonts));let a=n.Node.create();a.setWidth(t.width),a.setHeight(t.height),a.setFlexDirection(n.FLEX_DIRECTION_ROW),a.setFlexWrap(n.WRAP_WRAP),a.setAlignContent(n.ALIGN_AUTO),a.setAlignItems(n.ALIGN_FLEX_START),a.setJustifyContent(n.JUSTIFY_FLEX_START),a.setOverflow(n.OVERFLOW_HIDDEN);let o={...t.graphemeImages},r=ye(e,{id:"id",parentStyle:{},inheritedStyle:{fontSize:16,fontWeight:"normal",fontFamily:"serif",fontStyle:"normal",lineHeight:1.2,color:"black",opacity:1,whiteSpace:"normal",_viewportWidth:t.width,_viewportHeight:t.height},parent:a,font:i,embedFont:t.embedFont,debug:t.debug,graphemeImages:o,canLoadAdditionalAssets:!!t.loadAdditionalAsset}),s=(await r.next()).value;if(t.loadAdditionalAsset&&s.length){s=Array.from(new Set(ae(s.join(""),"grapheme")));let m={};s.forEach(g=>{let h=Lt(g);m[h]=m[h]||[],h==="emoji"?m[h].push(g):m[h][0]=(m[h][0]||"")+g});let p=[],d={};await Promise.all(Object.entries(m).flatMap(([g,h])=>h.map(f=>t.loadAdditionalAsset(g,f).then(u=>{typeof u=="string"?d[f]=u:u&&p.push(u)})))),i.addFonts(p),Object.assign(o,d)}await r.next(),a.calculateLayout(t.width,t.height,n.DIRECTION_LTR);let l=(await r.next([0,0])).value;return a.freeRecursive(),nt({width:t.width,height:t.height,content:l})}export{At as default,Mt as init};
1
+ // src/yoga/yoga-prebuilt.ts
2
+ import * as Yoga from "yoga-layout-prebuilt";
3
+ var yoga_prebuilt_default = Yoga;
4
+
5
+ // src/yoga/index.ts
6
+ var Yoga2;
7
+ Yoga2 = yoga_prebuilt_default.default;
8
+ function init(yoga) {
9
+ Yoga2 = yoga;
10
+ }
11
+ function getYoga() {
12
+ return Yoga2;
13
+ }
14
+
15
+ // src/utils.ts
16
+ function isReactElement(node) {
17
+ const type = typeof node;
18
+ if (type === "number" || type === "bigint" || type === "string" || type === "boolean") {
19
+ return false;
20
+ }
21
+ return true;
22
+ }
23
+ function isClass(f2) {
24
+ return /^class\s/.test(Function.prototype.toString.call(f2));
25
+ }
26
+ function multiply(m1, m2) {
27
+ return [
28
+ m1[0] * m2[0] + m1[2] * m2[1],
29
+ m1[1] * m2[0] + m1[3] * m2[1],
30
+ m1[0] * m2[2] + m1[2] * m2[3],
31
+ m1[1] * m2[2] + m1[3] * m2[3],
32
+ m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
33
+ m1[1] * m2[4] + m1[3] * m2[5] + m1[5]
34
+ ];
35
+ }
36
+ function v(field, map, fallback) {
37
+ const value = map[field];
38
+ return typeof value === "undefined" ? fallback : value;
39
+ }
40
+ var locale = void 0;
41
+ var INTL_SEGMENTER_SUPPORTED = typeof Intl !== "undefined" && "Segmenter" in Intl;
42
+ if (!INTL_SEGMENTER_SUPPORTED) {
43
+ throw new Error(
44
+ "Intl.Segmenter does not exist, please use import a polyfill."
45
+ );
46
+ }
47
+ var wordSegmenter = INTL_SEGMENTER_SUPPORTED ? new Intl.Segmenter(locale, { granularity: "word" }) : null;
48
+ var graphemeSegmenter = INTL_SEGMENTER_SUPPORTED ? new Intl.Segmenter(locale, {
49
+ granularity: "grapheme"
50
+ }) : null;
51
+ var wordSeparators = [
52
+ 32,
53
+ 160,
54
+ 4961,
55
+ 65792,
56
+ 65793,
57
+ 4153,
58
+ 4241,
59
+ 10
60
+ ].map((point) => String.fromCodePoint(point));
61
+ function segment(content, granularity) {
62
+ return granularity === "word" ? [...wordSegmenter.segment(content)].map((seg) => seg.segment) : [...graphemeSegmenter.segment(content)].map((seg) => seg.segment);
63
+ }
64
+ function buildXMLString(type, attrs, children) {
65
+ let attrString = "";
66
+ for (const [k, v2] of Object.entries(attrs)) {
67
+ if (typeof v2 !== "undefined") {
68
+ attrString += ` ${k}="${v2}"`;
69
+ }
70
+ }
71
+ if (children) {
72
+ return `<${type}${attrString}>${children}</${type}>`;
73
+ }
74
+ return `<${type}${attrString}/>`;
75
+ }
76
+ function createLRU(max = 20) {
77
+ const store = /* @__PURE__ */ new Map();
78
+ function set(key, value) {
79
+ if (store.size >= max) {
80
+ const keyToDelete = store.keys().next().value;
81
+ store.delete(keyToDelete);
82
+ }
83
+ store.set(key, value);
84
+ }
85
+ function get(key) {
86
+ const hasKey = store.has(key);
87
+ if (!hasKey)
88
+ return void 0;
89
+ const entry = store.get(key);
90
+ store.delete(key);
91
+ store.set(key, entry);
92
+ return entry;
93
+ }
94
+ return {
95
+ set,
96
+ get
97
+ };
98
+ }
99
+ var ATTRIBUTE_MAPPING = {
100
+ accentHeight: "accent-height",
101
+ alignmentBaseline: "alignment-baseline",
102
+ allowReorder: "allowreorder",
103
+ arabicForm: "arabic-form",
104
+ attributeName: "attributename",
105
+ attributeType: "attributetype",
106
+ autoReverse: "autoreverse",
107
+ baseFrequency: "basefrequency",
108
+ baseProfile: "baseprofile",
109
+ baselineShift: "baseline-shift",
110
+ calcMode: "calcmode",
111
+ capHeight: "cap-height",
112
+ clipPath: "clip-path",
113
+ clipPathUnits: "clippathunits",
114
+ clipRule: "clip-rule",
115
+ colorInterpolation: "color-interpolation",
116
+ colorInterpolationFilters: "color-interpolation-filters",
117
+ colorProfile: "color-profile",
118
+ colorRendering: "color-rendering",
119
+ contentScriptType: "contentscripttype",
120
+ contentStyleType: "contentstyletype",
121
+ diffuseConstant: "diffuseconstant",
122
+ dominantBaseline: "dominant-baseline",
123
+ edgeMode: "edgemode",
124
+ enableBackground: "enable-background",
125
+ externalResourcesRequired: "externalresourcesrequired",
126
+ fillOpacity: "fill-opacity",
127
+ fillRule: "fill-rule",
128
+ filterRes: "filterres",
129
+ filterUnits: "filterunits",
130
+ floodColor: "flood-color",
131
+ floodOpacity: "flood-opacity",
132
+ fontFamily: "font-family",
133
+ fontSize: "font-size",
134
+ fontSizeAdjust: "font-size-adjust",
135
+ fontStretch: "font-stretch",
136
+ fontStyle: "font-style",
137
+ fontVariant: "font-variant",
138
+ fontWeight: "font-weight",
139
+ glyphName: "glyph-name",
140
+ glyphOrientationHorizontal: "glyph-orientation-horizontal",
141
+ glyphOrientationVertical: "glyph-orientation-vertical",
142
+ glyphRef: "glyphref",
143
+ gradientTransform: "gradienttransform",
144
+ gradientUnits: "gradientunits",
145
+ horizAdvX: "horiz-adv-x",
146
+ horizOriginX: "horiz-origin-x",
147
+ imageRendering: "image-rendering",
148
+ kernelMatrix: "kernelmatrix",
149
+ kernelUnitLength: "kernelunitlength",
150
+ keyPoints: "keypoints",
151
+ keySplines: "keysplines",
152
+ keyTimes: "keytimes",
153
+ lengthAdjust: "lengthadjust",
154
+ letterSpacing: "letter-spacing",
155
+ lightingColor: "lighting-color",
156
+ limitingConeAngle: "limitingconeangle",
157
+ markerEnd: "marker-end",
158
+ markerHeight: "markerheight",
159
+ markerMid: "marker-mid",
160
+ markerStart: "marker-start",
161
+ markerUnits: "markerunits",
162
+ markerWidth: "markerwidth",
163
+ maskContentUnits: "maskcontentunits",
164
+ maskUnits: "maskunits",
165
+ numOctaves: "numoctaves",
166
+ overlinePosition: "overline-position",
167
+ overlineThickness: "overline-thickness",
168
+ paintOrder: "paint-order",
169
+ panose1: "panose-1",
170
+ pathLength: "pathlength",
171
+ patternContentUnits: "patterncontentunits",
172
+ patternTransform: "patterntransform",
173
+ patternUnits: "patternunits",
174
+ pointerEvents: "pointer-events",
175
+ pointsAtX: "pointsatx",
176
+ pointsAtY: "pointsaty",
177
+ pointsAtZ: "pointsatz",
178
+ preserveAlpha: "preservealpha",
179
+ preserveAspectRatio: "preserveaspectratio",
180
+ primitiveUnits: "primitiveunits",
181
+ refX: "refx",
182
+ refY: "refy",
183
+ renderingIntent: "rendering-intent",
184
+ repeatCount: "repeatcount",
185
+ repeatDur: "repeatdur",
186
+ requiredExtensions: "requiredextensions",
187
+ requiredFeatures: "requiredfeatures",
188
+ shapeRendering: "shape-rendering",
189
+ specularConstant: "specularconstant",
190
+ specularExponent: "specularexponent",
191
+ spreadMethod: "spreadmethod",
192
+ startOffset: "startoffset",
193
+ stdDeviation: "stddeviation",
194
+ stitchTiles: "stitchtiles",
195
+ stopColor: "stop-color",
196
+ stopOpacity: "stop-opacity",
197
+ strikethroughPosition: "strikethrough-position",
198
+ strikethroughThickness: "strikethrough-thickness",
199
+ strokeDasharray: "stroke-dasharray",
200
+ strokeDashoffset: "stroke-dashoffset",
201
+ strokeLinecap: "stroke-linecap",
202
+ strokeLinejoin: "stroke-linejoin",
203
+ strokeMiterlimit: "stroke-miterlimit",
204
+ strokeOpacity: "stroke-opacity",
205
+ strokeWidth: "stroke-width",
206
+ suppressContentEditableWarning: "suppresscontenteditablewarning",
207
+ suppressHydrationWarning: "suppresshydrationwarning",
208
+ surfaceScale: "surfacescale",
209
+ systemLanguage: "systemlanguage",
210
+ tableValues: "tablevalues",
211
+ targetX: "targetx",
212
+ targetY: "targety",
213
+ textAnchor: "text-anchor",
214
+ textDecoration: "text-decoration",
215
+ textLength: "textlength",
216
+ textRendering: "text-rendering",
217
+ underlinePosition: "underline-position",
218
+ underlineThickness: "underline-thickness",
219
+ unicodeBidi: "unicode-bidi",
220
+ unicodeRange: "unicode-range",
221
+ unitsPerEm: "units-per-em",
222
+ vAlphabetic: "v-alphabetic",
223
+ vHanging: "v-hanging",
224
+ vIdeographic: "v-ideographic",
225
+ vMathematical: "v-mathematical",
226
+ vectorEffect: "vector-effect",
227
+ vertAdvY: "vert-adv-y",
228
+ vertOriginX: "vert-origin-x",
229
+ vertOriginY: "vert-origin-y",
230
+ viewBox: "viewbox",
231
+ viewTarget: "viewtarget",
232
+ wordSpacing: "word-spacing",
233
+ writingMode: "writing-mode",
234
+ xChannelSelector: "xchannelselector",
235
+ xHeight: "x-height",
236
+ xlinkActuate: "xlink:actuate",
237
+ xlinkArcrole: "xlink:arcrole",
238
+ xlinkHref: "xlink:href",
239
+ xlinkRole: "xlink:role",
240
+ xlinkShow: "xlink:show",
241
+ xlinkTitle: "xlink:title",
242
+ xlinkType: "xlink:type",
243
+ xmlBase: "xml:base",
244
+ xmlLang: "xml:lang",
245
+ xmlSpace: "xmlspace",
246
+ xmlnsXlink: "xmlns:xlink",
247
+ yChannelSelector: "ychannelselector",
248
+ zoomAndPan: "zoomandpan"
249
+ };
250
+ var SVGSymbols = /[\r\n%#()<>?[\\\]^`{|}"']/g;
251
+ function translateSVGNodeToSVGString(node) {
252
+ if (!node)
253
+ return "";
254
+ if (Array.isArray(node)) {
255
+ return node.map(translateSVGNodeToSVGString).join("");
256
+ }
257
+ if (typeof node !== "object")
258
+ return String(node);
259
+ const type = node.type;
260
+ if (type === "text") {
261
+ throw new Error(
262
+ "<text> nodes are not currently supported, please convert them to <path>"
263
+ );
264
+ }
265
+ const { children, ...restProps } = node.props || {};
266
+ return `<${type}${Object.entries(restProps).map(([k, v2]) => {
267
+ return ` ${ATTRIBUTE_MAPPING[k] || k}="${v2}"`;
268
+ }).join("")}>${translateSVGNodeToSVGString(children)}</${type}>`;
269
+ }
270
+ function SVGNodeToImage(node) {
271
+ let {
272
+ viewBox,
273
+ viewbox,
274
+ width,
275
+ height,
276
+ className,
277
+ style,
278
+ children,
279
+ ...restProps
280
+ } = node.props || {};
281
+ viewBox || (viewBox = viewbox);
282
+ const viewBoxSize = viewBox.split(" ").map((v2) => parseInt(v2, 10));
283
+ restProps.xmlns = "http://www.w3.org/2000/svg";
284
+ restProps.viewBox = viewBox;
285
+ restProps.width = viewBoxSize[2];
286
+ restProps.height = viewBoxSize[3];
287
+ return `data:image/svg+xml;utf8,${`<svg${Object.entries(restProps).map(([k, v2]) => {
288
+ return ` ${ATTRIBUTE_MAPPING[k] || k}="${v2}"`;
289
+ }).join("")}>${translateSVGNodeToSVGString(children)}</svg>`.replace(
290
+ SVGSymbols,
291
+ encodeURIComponent
292
+ )}`;
293
+ }
294
+
295
+ // src/handler/presets.ts
296
+ var presets_default = {
297
+ p: {
298
+ display: "block",
299
+ marginTop: "1em",
300
+ marginBottom: "1em"
301
+ },
302
+ div: {
303
+ display: "block"
304
+ },
305
+ blockquote: {
306
+ display: "block",
307
+ marginTop: "1em",
308
+ marginBottom: "1em",
309
+ marginLeft: 40,
310
+ marginRight: 40
311
+ },
312
+ center: {
313
+ display: "block",
314
+ textAlign: "center"
315
+ },
316
+ hr: {
317
+ display: "block",
318
+ marginTop: "0.5em",
319
+ marginBottom: "0.5em",
320
+ marginLeft: "auto",
321
+ marginRight: "auto",
322
+ borderWidth: 1,
323
+ borderStyle: "inset"
324
+ },
325
+ h1: {
326
+ display: "block",
327
+ fontSize: "2em",
328
+ marginTop: "0.67em",
329
+ marginBottom: "0.67em",
330
+ marginLeft: 0,
331
+ marginRight: 0,
332
+ fontWeight: "bold"
333
+ },
334
+ h2: {
335
+ display: "block",
336
+ fontSize: "1.5em",
337
+ marginTop: "0.83em",
338
+ marginBottom: "0.83em",
339
+ marginLeft: 0,
340
+ marginRight: 0,
341
+ fontWeight: "bold"
342
+ },
343
+ h3: {
344
+ display: "block",
345
+ fontSize: "1.17em",
346
+ marginTop: "1em",
347
+ marginBottom: "1em",
348
+ marginLeft: 0,
349
+ marginRight: 0,
350
+ fontWeight: "bold"
351
+ },
352
+ h4: {
353
+ display: "block",
354
+ marginTop: "1.33em",
355
+ marginBottom: "1.33em",
356
+ marginLeft: 0,
357
+ marginRight: 0,
358
+ fontWeight: "bold"
359
+ },
360
+ h5: {
361
+ display: "block",
362
+ fontSize: "0.83em",
363
+ marginTop: "1.67em",
364
+ marginBottom: "1.67em",
365
+ marginLeft: 0,
366
+ marginRight: 0,
367
+ fontWeight: "bold"
368
+ },
369
+ h6: {
370
+ display: "block",
371
+ fontSize: "0.67em",
372
+ marginTop: "2.33em",
373
+ marginBottom: "2.33em",
374
+ marginLeft: 0,
375
+ marginRight: 0,
376
+ fontWeight: "bold"
377
+ },
378
+ u: {
379
+ textDecoration: "underline"
380
+ },
381
+ strong: {
382
+ fontWeight: "bold"
383
+ },
384
+ b: {
385
+ fontWeight: "bold"
386
+ },
387
+ i: {
388
+ fontStyle: "italic"
389
+ },
390
+ em: {
391
+ fontStyle: "italic"
392
+ },
393
+ code: {
394
+ fontFamily: "monospace"
395
+ },
396
+ kbd: {
397
+ fontFamily: "monospace"
398
+ },
399
+ pre: {
400
+ display: "block",
401
+ fontFamily: "monospace",
402
+ whiteSpace: "pre",
403
+ marginTop: "1em",
404
+ marginBottom: "1em"
405
+ },
406
+ mark: {
407
+ backgroundColor: "yellow",
408
+ color: "black"
409
+ },
410
+ big: {
411
+ fontSize: "larger"
412
+ },
413
+ small: {
414
+ fontSize: "smaller"
415
+ },
416
+ s: {
417
+ textDecoration: "line-through"
418
+ }
419
+ };
420
+
421
+ // src/handler/inheritable.ts
422
+ var list = /* @__PURE__ */ new Set([
423
+ "color",
424
+ "font",
425
+ "fontFamily",
426
+ "fontSize",
427
+ "fontStyle",
428
+ "fontWeight",
429
+ "letterSpacing",
430
+ "lineHeight",
431
+ "textAlign",
432
+ "textTransform",
433
+ "textShadowOffset",
434
+ "textShadowColor",
435
+ "textShadowRadius",
436
+ "textDecorationLine",
437
+ "textDecorationStyle",
438
+ "textDecorationColor",
439
+ "whiteSpace",
440
+ "transform",
441
+ "wordBreak",
442
+ "opacity",
443
+ "filter",
444
+ "_viewportWidth",
445
+ "_viewportHeight",
446
+ "_inheritedClipPathId",
447
+ "_inheritedBackgroundClipTextPath"
448
+ ]);
449
+ function inheritable(style) {
450
+ const inheritedStyle = {};
451
+ for (const prop in style) {
452
+ if (list.has(prop)) {
453
+ inheritedStyle[prop] = style[prop];
454
+ }
455
+ }
456
+ return inheritedStyle;
457
+ }
458
+
459
+ // src/handler/expand.ts
460
+ import { getPropertyName, getStylesForProperty } from "css-to-react-native";
461
+ import { parseElementStyle } from "css-background-parser";
462
+
463
+ // src/vendor/parse-css-dimension/index.js
464
+ var e = (t, r) => () => (r || t((r = { exports: {} }).exports, r), r.exports);
465
+ var u = e((k, g) => {
466
+ g.exports = ["em", "ex", "ch", "rem", "vh", "vw", "vmin", "vmax", "px", "mm", "cm", "in", "pt", "pc", "mozmm"];
467
+ });
468
+ var a = e((z, v2) => {
469
+ v2.exports = ["deg", "grad", "rad", "turn"];
470
+ });
471
+ var c = e((L, w) => {
472
+ w.exports = ["dpi", "dpcm", "dppx"];
473
+ });
474
+ var h = e(($, y) => {
475
+ y.exports = ["Hz", "kHz"];
476
+ });
477
+ var m = e((j, b) => {
478
+ b.exports = ["s", "ms"];
479
+ });
480
+ var q = u();
481
+ var f = a();
482
+ var p = c();
483
+ var l = h();
484
+ var d = m();
485
+ function s(t) {
486
+ if (/\.\D?$/.test(t))
487
+ throw new Error("The dot should be followed by a number");
488
+ if (/^[+-]{2}/.test(t))
489
+ throw new Error("Only one leading +/- is allowed");
490
+ if (x(t) > 1)
491
+ throw new Error("Only one dot is allowed");
492
+ if (/%$/.test(t)) {
493
+ this.type = "percentage", this.value = o(t), this.unit = "%";
494
+ return;
495
+ }
496
+ var r = O(t);
497
+ if (!r) {
498
+ this.type = "number", this.value = o(t);
499
+ return;
500
+ }
501
+ this.type = F(r), this.value = o(t.substr(0, t.length - r.length)), this.unit = r;
502
+ }
503
+ s.prototype.valueOf = function() {
504
+ return this.value;
505
+ };
506
+ s.prototype.toString = function() {
507
+ return this.value + (this.unit || "");
508
+ };
509
+ function U(t) {
510
+ return new s(t);
511
+ }
512
+ function x(t) {
513
+ var r = t.match(/\./g);
514
+ return r ? r.length : 0;
515
+ }
516
+ function o(t) {
517
+ var r = parseFloat(t);
518
+ if (isNaN(r))
519
+ throw new Error("Invalid number: " + t);
520
+ return r;
521
+ }
522
+ var E = [].concat(f, l, q, p, d);
523
+ function O(t) {
524
+ var r = t.match(/\D+$/), n = r && r[0];
525
+ if (n && E.indexOf(n) === -1)
526
+ throw new Error("Invalid unit: " + n);
527
+ return n;
528
+ }
529
+ var D = Object.assign(i(f, "angle"), i(l, "frequency"), i(p, "resolution"), i(d, "time"));
530
+ function i(t, r) {
531
+ return Object.fromEntries(t.map((n) => [n, r]));
532
+ }
533
+ function F(t) {
534
+ return D[t] || "length";
535
+ }
536
+
537
+ // src/transform-origin.ts
538
+ import valueParser from "postcss-value-parser";
539
+ function parseUnit(word, baseFontSize) {
540
+ try {
541
+ const parsed = new U(word);
542
+ switch (parsed.unit) {
543
+ case "px":
544
+ return { absolute: parsed.value };
545
+ case "em":
546
+ return { absolute: parsed.value * baseFontSize };
547
+ case "rem":
548
+ return { absolute: parsed.value * 16 };
549
+ case "%":
550
+ return { relative: parsed.value };
551
+ default:
552
+ return {};
553
+ }
554
+ } catch (e2) {
555
+ return {};
556
+ }
557
+ }
558
+ function handleWord(word, baseFontSize, unitIsHorizontal) {
559
+ switch (word) {
560
+ case "top":
561
+ return { yRelative: 0 };
562
+ case "left":
563
+ return { xRelative: 0 };
564
+ case "right":
565
+ return { xRelative: 100 };
566
+ case "bottom":
567
+ return { yRelative: 100 };
568
+ case "center":
569
+ return {};
570
+ default:
571
+ const parsedUnit = parseUnit(word, baseFontSize);
572
+ return parsedUnit.absolute ? {
573
+ [unitIsHorizontal ? "xAbsolute" : "yAbsolute"]: parsedUnit.absolute
574
+ } : parsedUnit.relative ? {
575
+ [unitIsHorizontal ? "xRelative" : "yRelative"]: parsedUnit.relative
576
+ } : {};
577
+ }
578
+ }
579
+ function parseTranformOrigin(value, baseFontSize) {
580
+ if (typeof value === "number") {
581
+ return { xAbsolute: value };
582
+ }
583
+ let words;
584
+ try {
585
+ words = valueParser(value).nodes.filter((node) => node.type === "word").map((node) => node.value);
586
+ } catch (e2) {
587
+ return {};
588
+ }
589
+ if (words.length === 1) {
590
+ return handleWord(words[0], baseFontSize, true);
591
+ } else if (words.length === 2) {
592
+ if (words[0] === "top" || words[0] === "bottom" || words[1] === "left" || words[1] === "right") {
593
+ words.reverse();
594
+ }
595
+ return {
596
+ ...handleWord(words[0], baseFontSize, true),
597
+ ...handleWord(words[1], baseFontSize, false)
598
+ };
599
+ } else {
600
+ return {};
601
+ }
602
+ }
603
+
604
+ // src/handler/expand.ts
605
+ var optOutPx = /* @__PURE__ */ new Set([
606
+ "flex",
607
+ "flexGrow",
608
+ "flexShrink",
609
+ "flexBasis",
610
+ "fontWeight",
611
+ "lineHeight",
612
+ "opacity",
613
+ "scale",
614
+ "scaleX",
615
+ "scaleY"
616
+ ]);
617
+ var keepNumber = /* @__PURE__ */ new Set(["lineHeight"]);
618
+ var baseMatrix = [1, 0, 0, 1, 0, 0];
619
+ function handleFallbackColor(prop, parsed, rawInput, currentColor) {
620
+ if (prop === "border" && !rawInput.includes(parsed.borderColor)) {
621
+ parsed.borderColor = currentColor;
622
+ } else if (prop === "borderColor") {
623
+ parsed.borderColor = parsed.borderTopColor;
624
+ } else if (prop === "textDecoration" && !rawInput.includes(parsed.textDecorationColor)) {
625
+ parsed.textDecorationColor = currentColor;
626
+ }
627
+ return parsed;
628
+ }
629
+ function purify(name, value) {
630
+ if (typeof value === "number") {
631
+ if (!optOutPx.has(name))
632
+ return value + "px";
633
+ if (keepNumber.has(name))
634
+ return value;
635
+ return String(value);
636
+ }
637
+ return value;
638
+ }
639
+ function handleSpecialCase(name, value) {
640
+ if (name === "lineHeight")
641
+ return { lineHeight: purify(name, value) };
642
+ if (name === "fontFamily")
643
+ return {
644
+ fontFamily: value.split(",").map((v2) => {
645
+ return v2.trim().replace(/(^['"])|(['"]$)/g, "").toLocaleLowerCase();
646
+ })
647
+ };
648
+ return null;
649
+ }
650
+ function lengthToNumber(length, baseFontSize, inheritedStyle, { percentage } = { percentage: false }) {
651
+ if (typeof length === "number")
652
+ return length;
653
+ try {
654
+ const parsed = new U(length);
655
+ if (parsed.type === "length") {
656
+ switch (parsed.unit) {
657
+ case "em":
658
+ return parsed.value * baseFontSize;
659
+ case "rem":
660
+ return parsed.value * 16;
661
+ case "vw":
662
+ return ~~(parsed.value * inheritedStyle._viewportWidth / 100);
663
+ case "vh":
664
+ return ~~(parsed.value * inheritedStyle._viewportHeight / 100);
665
+ default:
666
+ return parsed.value;
667
+ }
668
+ } else if (parsed.type === "angle") {
669
+ switch (parsed.unit) {
670
+ case "deg":
671
+ return parsed.value;
672
+ case "rad":
673
+ return parsed.value * 180 / Math.PI;
674
+ default:
675
+ return parsed.value;
676
+ }
677
+ } else if (parsed.type === "percentage") {
678
+ if (percentage) {
679
+ return parsed.value / 100 * baseFontSize;
680
+ }
681
+ }
682
+ } catch (err) {
683
+ }
684
+ }
685
+ function expand(style, inheritedStyle) {
686
+ const transformedStyle = {};
687
+ for (const prop in style) {
688
+ if (prop.startsWith("_")) {
689
+ transformedStyle[prop] = style[prop];
690
+ continue;
691
+ }
692
+ const name = getPropertyName(prop);
693
+ Object.assign(
694
+ transformedStyle,
695
+ handleSpecialCase(name, style[prop]) || handleFallbackColor(
696
+ name,
697
+ getStylesForProperty(name, purify(name, style[prop]), true),
698
+ style[prop],
699
+ style.color || inheritedStyle.color
700
+ )
701
+ );
702
+ }
703
+ if (transformedStyle.backgroundImage) {
704
+ const { backgrounds } = parseElementStyle(transformedStyle);
705
+ transformedStyle.backgroundImage = backgrounds;
706
+ }
707
+ let baseFontSize = transformedStyle.fontSize || inheritedStyle.fontSize;
708
+ if (typeof baseFontSize === "string") {
709
+ try {
710
+ const parsed = new U(baseFontSize);
711
+ switch (parsed.unit) {
712
+ case "em":
713
+ baseFontSize = parsed.value * inheritedStyle.fontSize;
714
+ break;
715
+ case "rem":
716
+ baseFontSize = parsed.value * 16;
717
+ break;
718
+ }
719
+ } catch (err) {
720
+ baseFontSize = 16;
721
+ }
722
+ }
723
+ if (typeof transformedStyle.fontSize !== "undefined") {
724
+ transformedStyle.fontSize = baseFontSize;
725
+ }
726
+ if (transformedStyle.transformOrigin) {
727
+ transformedStyle.transformOrigin = parseTranformOrigin(
728
+ transformedStyle.transformOrigin,
729
+ baseFontSize
730
+ );
731
+ }
732
+ for (const prop in transformedStyle) {
733
+ let value = transformedStyle[prop];
734
+ if (prop === "lineHeight") {
735
+ if (typeof value === "string") {
736
+ value = transformedStyle[prop] = lengthToNumber(value, baseFontSize, inheritedStyle, {
737
+ percentage: true
738
+ }) / baseFontSize;
739
+ }
740
+ } else {
741
+ if (typeof value === "string") {
742
+ const len = lengthToNumber(value, baseFontSize, inheritedStyle);
743
+ if (typeof len !== "undefined")
744
+ transformedStyle[prop] = len;
745
+ value = transformedStyle[prop];
746
+ }
747
+ }
748
+ if (prop === "opacity") {
749
+ value = transformedStyle[prop] = value * inheritedStyle.opacity;
750
+ }
751
+ if (prop === "transform") {
752
+ let matrix = [...baseMatrix];
753
+ const transforms = value;
754
+ for (const transform2 of transforms) {
755
+ const type = Object.keys(transform2)[0];
756
+ const v2 = transform2[type];
757
+ const len = typeof v2 === "string" ? lengthToNumber(v2, baseFontSize, inheritedStyle) : v2;
758
+ const transformMatrix = [...baseMatrix];
759
+ switch (type) {
760
+ case "translateX":
761
+ transformMatrix[4] = len;
762
+ break;
763
+ case "translateY":
764
+ transformMatrix[5] = len;
765
+ break;
766
+ case "scale":
767
+ transformMatrix[0] = len;
768
+ transformMatrix[3] = len;
769
+ break;
770
+ case "scaleX":
771
+ transformMatrix[0] = len;
772
+ break;
773
+ case "scaleY":
774
+ transformMatrix[3] = len;
775
+ break;
776
+ case "rotate":
777
+ const rad = len * Math.PI / 180;
778
+ const c2 = Math.cos(rad);
779
+ const s2 = Math.sin(rad);
780
+ transformMatrix[0] = c2;
781
+ transformMatrix[1] = s2;
782
+ transformMatrix[2] = -s2;
783
+ transformMatrix[3] = c2;
784
+ break;
785
+ case "skewX":
786
+ transformMatrix[2] = Math.tan(len * Math.PI / 180);
787
+ break;
788
+ case "skewY":
789
+ transformMatrix[1] = Math.tan(len * Math.PI / 180);
790
+ break;
791
+ }
792
+ matrix = multiply(transformMatrix, matrix);
793
+ }
794
+ transformedStyle.transform = matrix;
795
+ }
796
+ }
797
+ return transformedStyle;
798
+ }
799
+
800
+ // src/handler/index.ts
801
+ function handler(node, type, inheritedStyle, definedStyle, props) {
802
+ const Yoga3 = getYoga();
803
+ const style = {
804
+ ...inheritedStyle,
805
+ ...expand(presets_default[type], inheritedStyle),
806
+ ...expand(definedStyle, inheritedStyle)
807
+ };
808
+ if (type === "img") {
809
+ const width = parseInt(props.width);
810
+ const height = parseInt(props.height);
811
+ const r = height / width;
812
+ if (!style.width)
813
+ style.width = width;
814
+ if (!style.height)
815
+ style.height = r * style.width;
816
+ }
817
+ if (type === "svg") {
818
+ const viewBox = props.viewBox || props.viewbox;
819
+ const viewBoxSize = viewBox.split(" ").map((v2) => parseInt(v2, 10));
820
+ const ratio = viewBoxSize[3] / viewBoxSize[2];
821
+ let { width, height } = props;
822
+ if (typeof width === "undefined" && height) {
823
+ if (typeof height === "string" && height.endsWith("%")) {
824
+ width = parseInt(height) / ratio + "%";
825
+ } else {
826
+ width = parseInt(height) / ratio;
827
+ }
828
+ } else if (typeof height === "undefined" && width) {
829
+ if (typeof width === "string" && width.endsWith("%")) {
830
+ height = parseInt(width) * ratio + "%";
831
+ } else {
832
+ height = parseInt(width) * ratio;
833
+ }
834
+ } else {
835
+ width || (width = viewBoxSize[2]);
836
+ height || (height = viewBoxSize[3]);
837
+ }
838
+ if (!style.width)
839
+ style.width = width;
840
+ if (!style.height)
841
+ style.height = height;
842
+ }
843
+ node.setDisplay(
844
+ v(
845
+ style.display,
846
+ {
847
+ flex: Yoga3.DISPLAY_FLEX,
848
+ none: Yoga3.DISPLAY_NONE
849
+ },
850
+ Yoga3.DISPLAY_FLEX
851
+ )
852
+ );
853
+ node.setAlignContent(
854
+ v(
855
+ style.alignContent,
856
+ {
857
+ stretch: Yoga3.ALIGN_STRETCH,
858
+ center: Yoga3.ALIGN_CENTER,
859
+ "flex-start": Yoga3.ALIGN_FLEX_START,
860
+ "flex-end": Yoga3.ALIGN_FLEX_END,
861
+ "space-between": Yoga3.ALIGN_SPACE_BETWEEN,
862
+ "space-around": Yoga3.ALIGN_SPACE_AROUND,
863
+ baseline: Yoga3.ALIGN_BASELINE,
864
+ normal: Yoga3.ALIGN_AUTO
865
+ },
866
+ Yoga3.ALIGN_AUTO
867
+ )
868
+ );
869
+ node.setAlignItems(
870
+ v(
871
+ style.alignItems,
872
+ {
873
+ stretch: Yoga3.ALIGN_STRETCH,
874
+ center: Yoga3.ALIGN_CENTER,
875
+ "flex-start": Yoga3.ALIGN_FLEX_START,
876
+ "flex-end": Yoga3.ALIGN_FLEX_END,
877
+ baseline: Yoga3.ALIGN_BASELINE,
878
+ normal: Yoga3.ALIGN_AUTO
879
+ },
880
+ Yoga3.ALIGN_FLEX_START
881
+ )
882
+ );
883
+ node.setAlignSelf(
884
+ v(
885
+ style.alignSelf,
886
+ {
887
+ stretch: Yoga3.ALIGN_STRETCH,
888
+ center: Yoga3.ALIGN_CENTER,
889
+ "flex-start": Yoga3.ALIGN_FLEX_START,
890
+ "flex-end": Yoga3.ALIGN_FLEX_END,
891
+ baseline: Yoga3.ALIGN_BASELINE,
892
+ normal: Yoga3.ALIGN_AUTO
893
+ },
894
+ Yoga3.ALIGN_AUTO
895
+ )
896
+ );
897
+ node.setJustifyContent(
898
+ v(
899
+ style.justifyContent,
900
+ {
901
+ center: Yoga3.JUSTIFY_CENTER,
902
+ "flex-start": Yoga3.JUSTIFY_FLEX_START,
903
+ "flex-end": Yoga3.JUSTIFY_FLEX_END,
904
+ "space-between": Yoga3.JUSTIFY_SPACE_BETWEEN,
905
+ "space-around": Yoga3.JUSTIFY_SPACE_AROUND
906
+ },
907
+ Yoga3.JUSTIFY_FLEX_START
908
+ )
909
+ );
910
+ node.setFlexDirection(
911
+ v(
912
+ style.flexDirection,
913
+ {
914
+ row: Yoga3.FLEX_DIRECTION_ROW,
915
+ column: Yoga3.FLEX_DIRECTION_COLUMN,
916
+ "row-reverse": Yoga3.FLEX_DIRECTION_ROW_REVERSE,
917
+ "column-reverse": Yoga3.FLEX_DIRECTION_COLUMN_REVERSE
918
+ },
919
+ Yoga3.FLEX_DIRECTION_ROW
920
+ )
921
+ );
922
+ node.setFlexWrap(
923
+ v(
924
+ style.flexWrap,
925
+ {
926
+ wrap: Yoga3.WRAP_WRAP,
927
+ nowrap: Yoga3.WRAP_NO_WRAP,
928
+ "wrap-reverse": Yoga3.WRAP_WRAP_REVERSE
929
+ },
930
+ Yoga3.WRAP_WRAP
931
+ )
932
+ );
933
+ if (typeof style.flexBasis !== "undefined") {
934
+ node.setFlexBasis(style.flexBasis);
935
+ }
936
+ node.setFlexGrow(
937
+ typeof style.flexGrow === "undefined" ? 0 : style.flexGrow
938
+ );
939
+ node.setFlexShrink(
940
+ typeof style.flexShrink === "undefined" ? 0 : style.flexShrink
941
+ );
942
+ if (typeof style.maxHeight !== "undefined") {
943
+ node.setMaxHeight(style.maxHeight);
944
+ }
945
+ if (typeof style.maxWidth !== "undefined") {
946
+ node.setMaxWidth(style.maxWidth);
947
+ }
948
+ if (typeof style.minHeight !== "undefined") {
949
+ node.setMinHeight(style.minHeight);
950
+ }
951
+ if (typeof style.minWidth !== "undefined") {
952
+ node.setMinWidth(style.minWidth);
953
+ }
954
+ node.setOverflow(
955
+ v(
956
+ style.overflow,
957
+ {
958
+ visible: Yoga3.OVERFLOW_VISIBLE,
959
+ hidden: Yoga3.OVERFLOW_HIDDEN
960
+ },
961
+ Yoga3.OVERFLOW_VISIBLE
962
+ )
963
+ );
964
+ node.setMargin(Yoga3.EDGE_TOP, style.marginTop || 0);
965
+ node.setMargin(Yoga3.EDGE_BOTTOM, style.marginBottom || 0);
966
+ node.setMargin(Yoga3.EDGE_LEFT, style.marginLeft || 0);
967
+ node.setMargin(Yoga3.EDGE_RIGHT, style.marginRight || 0);
968
+ node.setBorder(Yoga3.EDGE_TOP, style.borderWidth || 0);
969
+ node.setBorder(Yoga3.EDGE_BOTTOM, style.borderWidth || 0);
970
+ node.setBorder(Yoga3.EDGE_LEFT, style.borderWidth || 0);
971
+ node.setBorder(Yoga3.EDGE_RIGHT, style.borderWidth || 0);
972
+ node.setPadding(Yoga3.EDGE_TOP, style.paddingTop || 0);
973
+ node.setPadding(Yoga3.EDGE_BOTTOM, style.paddingBottom || 0);
974
+ node.setPadding(Yoga3.EDGE_LEFT, style.paddingLeft || 0);
975
+ node.setPadding(Yoga3.EDGE_RIGHT, style.paddingRight || 0);
976
+ node.setPositionType(
977
+ v(
978
+ style.position,
979
+ {
980
+ absolute: Yoga3.POSITION_TYPE_ABSOLUTE,
981
+ relative: Yoga3.POSITION_TYPE_RELATIVE
982
+ },
983
+ Yoga3.POSITION_TYPE_RELATIVE
984
+ )
985
+ );
986
+ if (typeof style.top !== "undefined") {
987
+ node.setPosition(Yoga3.EDGE_TOP, style.top);
988
+ }
989
+ if (typeof style.bottom !== "undefined") {
990
+ node.setPosition(Yoga3.EDGE_BOTTOM, style.bottom);
991
+ }
992
+ if (typeof style.left !== "undefined") {
993
+ node.setPosition(Yoga3.EDGE_LEFT, style.left);
994
+ }
995
+ if (typeof style.right !== "undefined") {
996
+ node.setPosition(Yoga3.EDGE_RIGHT, style.right);
997
+ }
998
+ if (typeof style.height !== "undefined") {
999
+ node.setHeight(style.height);
1000
+ } else {
1001
+ node.setHeightAuto();
1002
+ }
1003
+ if (typeof style.width !== "undefined") {
1004
+ node.setWidth(style.width);
1005
+ } else {
1006
+ node.setWidthAuto();
1007
+ }
1008
+ return [style, inheritable(style)];
1009
+ }
1010
+
1011
+ // src/builder/transform.ts
1012
+ function transform({
1013
+ left,
1014
+ top,
1015
+ width,
1016
+ height
1017
+ }, matrix, isInheritingTransform, transformOrigin) {
1018
+ var _a, _b, _c, _d;
1019
+ let result;
1020
+ if (isInheritingTransform) {
1021
+ result = matrix;
1022
+ } else {
1023
+ const xOrigin = (_b = transformOrigin == null ? void 0 : transformOrigin.xAbsolute) != null ? _b : ((_a = transformOrigin == null ? void 0 : transformOrigin.xRelative) != null ? _a : 50) * width / 100;
1024
+ const yOrigin = (_d = transformOrigin == null ? void 0 : transformOrigin.yAbsolute) != null ? _d : ((_c = transformOrigin == null ? void 0 : transformOrigin.yRelative) != null ? _c : 50) * height / 100;
1025
+ const x2 = left + xOrigin;
1026
+ const y = top + yOrigin;
1027
+ result = multiply(
1028
+ [1, 0, 0, 1, x2, y],
1029
+ multiply(matrix, [1, 0, 0, 1, -x2, -y])
1030
+ );
1031
+ if (matrix.__parent) {
1032
+ result = multiply(matrix.__parent, result);
1033
+ }
1034
+ matrix.splice(0, 6, ...result);
1035
+ }
1036
+ return `matrix(${result.map((v2) => v2.toFixed(2)).join(",")})`;
1037
+ }
1038
+
1039
+ // src/builder/text.ts
1040
+ function container({
1041
+ left,
1042
+ top,
1043
+ width,
1044
+ height,
1045
+ isInheritingTransform
1046
+ }, style) {
1047
+ let matrix = "";
1048
+ let opacity = 1;
1049
+ if (style.transform) {
1050
+ matrix = transform(
1051
+ {
1052
+ left,
1053
+ top,
1054
+ width,
1055
+ height
1056
+ },
1057
+ style.transform,
1058
+ isInheritingTransform,
1059
+ style.transformOrigin
1060
+ );
1061
+ }
1062
+ if (style.opacity) {
1063
+ opacity = +style.opacity;
1064
+ }
1065
+ return { matrix, opacity };
1066
+ }
1067
+ function text({
1068
+ id,
1069
+ content,
1070
+ filter,
1071
+ left,
1072
+ top,
1073
+ width,
1074
+ height,
1075
+ matrix,
1076
+ opacity,
1077
+ image: image2,
1078
+ clipPathId,
1079
+ debug,
1080
+ shape,
1081
+ decorationShape
1082
+ }, style) {
1083
+ let extra = "";
1084
+ if (debug) {
1085
+ extra = buildXMLString("rect", {
1086
+ x: left,
1087
+ y: top - height,
1088
+ width,
1089
+ height,
1090
+ fill: "transparent",
1091
+ stroke: "#575eff",
1092
+ "stroke-width": 1,
1093
+ transform: matrix || void 0,
1094
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
1095
+ });
1096
+ }
1097
+ if (image2) {
1098
+ const shapeProps2 = {
1099
+ href: image2,
1100
+ x: left,
1101
+ y: top,
1102
+ width,
1103
+ height,
1104
+ transform: matrix || void 0,
1105
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0,
1106
+ style: style.filter ? `filter:${style.filter}` : void 0
1107
+ };
1108
+ return [
1109
+ (filter ? `${filter}<g filter="url(#satori_s-${id})">` : "") + buildXMLString("image", {
1110
+ ...shapeProps2,
1111
+ opacity: opacity !== 1 ? opacity : void 0
1112
+ }) + (decorationShape || "") + (filter ? "</g>" : "") + extra,
1113
+ ""
1114
+ ];
1115
+ }
1116
+ const shapeProps = {
1117
+ x: left,
1118
+ y: top,
1119
+ width,
1120
+ height,
1121
+ "font-weight": style.fontWeight,
1122
+ "font-style": style.fontStyle,
1123
+ "font-size": style.fontSize,
1124
+ "font-family": style.fontFamily,
1125
+ "letter-spacing": style.letterSpacing || void 0,
1126
+ transform: matrix || void 0,
1127
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0,
1128
+ style: style.filter ? `filter:${style.filter}` : void 0
1129
+ };
1130
+ return [
1131
+ (filter ? `${filter}<g filter="url(#satori_s-${id})">` : "") + buildXMLString(
1132
+ "text",
1133
+ {
1134
+ ...shapeProps,
1135
+ fill: style.color,
1136
+ opacity: opacity !== 1 ? opacity : void 0
1137
+ },
1138
+ content
1139
+ ) + (decorationShape || "") + (filter ? "</g>" : "") + extra,
1140
+ shape ? buildXMLString("text", shapeProps, content) : ""
1141
+ ];
1142
+ }
1143
+
1144
+ // src/builder/shadow.ts
1145
+ function shadow({ id, width, height }, style) {
1146
+ if (!style.shadowColor || !style.shadowOffset || typeof style.shadowRadius === "undefined") {
1147
+ return "";
1148
+ }
1149
+ const grow = style.shadowRadius * style.shadowRadius / 4;
1150
+ const left = Math.min(style.shadowOffset.width - grow, 0);
1151
+ const right = Math.max(style.shadowOffset.width + grow + width, width);
1152
+ const top = Math.min(style.shadowOffset.height - grow, 0);
1153
+ const bottom = Math.max(style.shadowOffset.height + grow + height, height);
1154
+ return `<defs><filter id="satori_s-${id}" x="${left / width * 100}%" y="${top / height * 100}%" width="${(right - left) / width * 100}%" height="${(bottom - top) / height * 100}%"><feDropShadow dx="${style.shadowOffset.width}" dy="${style.shadowOffset.height}" stdDeviation="${style.shadowRadius / 2}" flood-color="${style.shadowColor}" flood-opacity="1"/></filter></defs>`;
1155
+ }
1156
+
1157
+ // src/builder/text-decoration.ts
1158
+ function decoration({
1159
+ width,
1160
+ left,
1161
+ top,
1162
+ ascender,
1163
+ clipPathId
1164
+ }, style) {
1165
+ const {
1166
+ textDecorationColor,
1167
+ textDecorationStyle,
1168
+ textDecorationLine,
1169
+ fontSize
1170
+ } = style;
1171
+ if (!textDecorationLine || textDecorationLine === "none")
1172
+ return "";
1173
+ const height = Math.max(1, fontSize * 0.1);
1174
+ const y = textDecorationLine === "line-through" ? top + ascender * 0.5 : textDecorationLine === "underline" ? top + ascender * 1.1 : top;
1175
+ const dasharray = textDecorationStyle === "dashed" ? `${height * 1.2} ${height * 2}` : textDecorationStyle === "dotted" ? `0 ${height * 2}` : void 0;
1176
+ return buildXMLString("line", {
1177
+ x1: left,
1178
+ y1: y,
1179
+ x2: left + width,
1180
+ y2: y,
1181
+ stroke: textDecorationColor,
1182
+ "stroke-width": height,
1183
+ "stroke-dasharray": dasharray,
1184
+ "stroke-linecap": textDecorationStyle === "dotted" ? "round" : "square",
1185
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
1186
+ });
1187
+ }
1188
+
1189
+ // src/text.ts
1190
+ var locale2 = void 0;
1191
+ async function* buildTextNodes(content, context) {
1192
+ var _a;
1193
+ const Yoga3 = getYoga();
1194
+ const {
1195
+ parentStyle,
1196
+ inheritedStyle,
1197
+ parent,
1198
+ font,
1199
+ id,
1200
+ isInheritingTransform,
1201
+ debug,
1202
+ embedFont,
1203
+ graphemeImages,
1204
+ canLoadAdditionalAssets
1205
+ } = context;
1206
+ if (parentStyle.textTransform === "uppercase") {
1207
+ content = content.toLocaleUpperCase(locale2);
1208
+ } else if (parentStyle.textTransform === "lowercase") {
1209
+ content = content.toLocaleLowerCase(locale2);
1210
+ } else if (parentStyle.textTransform === "capitalize") {
1211
+ content = segment(content, "word").map((word) => {
1212
+ return segment(word, "grapheme").map((grapheme, index) => {
1213
+ return index === 0 ? grapheme.toLocaleUpperCase(locale2) : grapheme;
1214
+ }).join("");
1215
+ }).join("");
1216
+ }
1217
+ const segmenter = v(
1218
+ parentStyle.wordBreak,
1219
+ {
1220
+ normal: "word",
1221
+ "break-all": "grapheme",
1222
+ "break-word": "grapheme",
1223
+ "keep-all": "word"
1224
+ },
1225
+ "word"
1226
+ );
1227
+ const words = segment(content, segmenter);
1228
+ const textContainer = Yoga3.Node.create();
1229
+ textContainer.setAlignItems(Yoga3.ALIGN_BASELINE);
1230
+ if (parentStyle.textAlign === "left") {
1231
+ textContainer.setJustifyContent(Yoga3.JUSTIFY_FLEX_START);
1232
+ } else if (parentStyle.textAlign === "center") {
1233
+ textContainer.setJustifyContent(Yoga3.JUSTIFY_CENTER);
1234
+ } else if (parentStyle.textAlign === "right") {
1235
+ textContainer.setJustifyContent(Yoga3.JUSTIFY_FLEX_END);
1236
+ } else if (parentStyle.textAlign === "justify") {
1237
+ textContainer.setJustifyContent(Yoga3.JUSTIFY_SPACE_BETWEEN);
1238
+ }
1239
+ parent.insertChild(textContainer, parent.getChildCount());
1240
+ const {
1241
+ textAlign,
1242
+ textOverflow,
1243
+ whiteSpace,
1244
+ lineHeight,
1245
+ filter: cssFilter,
1246
+ _inheritedBackgroundClipTextPath
1247
+ } = parentStyle;
1248
+ const baseFontSize = parentStyle.fontSize;
1249
+ let engine = font.getEngine(
1250
+ baseFontSize,
1251
+ lineHeight,
1252
+ parentStyle
1253
+ );
1254
+ const wordsMissingFont = canLoadAdditionalAssets ? words.filter((word) => !engine.check(word)) : [];
1255
+ yield wordsMissingFont;
1256
+ if (wordsMissingFont.length) {
1257
+ engine = font.getEngine(
1258
+ baseFontSize,
1259
+ lineHeight,
1260
+ parentStyle
1261
+ );
1262
+ }
1263
+ let lineWidths = [];
1264
+ let baselines = [];
1265
+ let lineSegmentNumber = [];
1266
+ let wordsInLayout = [];
1267
+ const wordWidthCache = /* @__PURE__ */ new Map();
1268
+ const measureWithCache = (segments) => {
1269
+ let total = 0;
1270
+ for (const s2 of segments) {
1271
+ if (wordWidthCache.has(s2)) {
1272
+ total += wordWidthCache.get(s2);
1273
+ continue;
1274
+ }
1275
+ const width = engine.measure(s2, parentStyle);
1276
+ wordWidthCache.set(s2, width);
1277
+ total += width;
1278
+ }
1279
+ return total;
1280
+ };
1281
+ let minWidth = 0;
1282
+ let remainingSegment = [];
1283
+ let extraWidth = 0;
1284
+ for (const word of words) {
1285
+ let breakSegment = false;
1286
+ const isImage = graphemeImages && graphemeImages[word];
1287
+ if (whiteSpace === "pre") {
1288
+ breakSegment = word[0] === "\n";
1289
+ } else if (whiteSpace !== "nowrap") {
1290
+ if (isImage || wordSeparators.includes(word[0])) {
1291
+ breakSegment = true;
1292
+ }
1293
+ }
1294
+ if (!breakSegment) {
1295
+ if (!wordSeparators.includes(word[0]) || !remainingSegment.length) {
1296
+ remainingSegment.push(word === "\n" ? " " : word);
1297
+ }
1298
+ } else {
1299
+ if (whiteSpace === "nowrap") {
1300
+ extraWidth += measureWithCache(remainingSegment) + parentStyle.fontSize;
1301
+ } else {
1302
+ minWidth = Math.max(minWidth, measureWithCache(remainingSegment));
1303
+ if (isImage) {
1304
+ minWidth = Math.max(minWidth, parentStyle.fontSize);
1305
+ }
1306
+ }
1307
+ remainingSegment = [];
1308
+ }
1309
+ }
1310
+ minWidth = Math.max(minWidth, measureWithCache(remainingSegment) + extraWidth);
1311
+ const currentMinWidth = parent.getMinWidth();
1312
+ const currentMaxWidth = parent.getMaxWidth();
1313
+ const currentWidth = parent.getWidth();
1314
+ if (isNaN(currentWidth.value) && (isNaN(currentMinWidth.value) || currentMinWidth.unit === 1 && currentMinWidth.value > minWidth)) {
1315
+ if (!isNaN(currentMaxWidth.value)) {
1316
+ if (currentMaxWidth.unit === 1) {
1317
+ minWidth = Math.min(minWidth, currentMaxWidth.value);
1318
+ } else {
1319
+ }
1320
+ }
1321
+ parent.setMinWidth(minWidth);
1322
+ }
1323
+ if (typeof parentStyle.flexShrink === "undefined") {
1324
+ parent.setFlexShrink(1);
1325
+ }
1326
+ const shouldAlwaysBreakLine = whiteSpace === "pre-wrap" || whiteSpace === "pre";
1327
+ textContainer.setMeasureFunc((width) => {
1328
+ let lines = 0;
1329
+ let remainingSpace = "";
1330
+ let remainingSpaceWidth = 0;
1331
+ let currentWidth2 = 0;
1332
+ let maxWidth = 0;
1333
+ let lineIndex = -1;
1334
+ let height = 0;
1335
+ let currentLineHeight = 0;
1336
+ let currentBaselineOffset = 0;
1337
+ lineWidths = [];
1338
+ lineSegmentNumber = [0];
1339
+ for (let i2 = 0; i2 < words.length; i2++) {
1340
+ const word = words[i2];
1341
+ if (!shouldAlwaysBreakLine && wordSeparators.includes(
1342
+ word[0]
1343
+ )) {
1344
+ if (!remainingSpace) {
1345
+ remainingSpace = " ";
1346
+ }
1347
+ remainingSpaceWidth = measureWithCache([remainingSpace]);
1348
+ wordsInLayout[i2] = null;
1349
+ } else {
1350
+ const forceBreak = shouldAlwaysBreakLine && word === "\n";
1351
+ const w = forceBreak ? 0 : graphemeImages && graphemeImages[word] ? parentStyle.fontSize : measureWithCache([word]);
1352
+ if (!currentWidth2) {
1353
+ remainingSpace = "";
1354
+ remainingSpaceWidth = 0;
1355
+ }
1356
+ const allowedToPutAtBeginning = remainingSpaceWidth || ",.!?:-@)>]}%#".indexOf(word[0]) < 0;
1357
+ const allowedToJustify = !currentWidth2 || !!remainingSpaceWidth;
1358
+ if (forceBreak || i2 && allowedToPutAtBeginning && currentWidth2 + remainingSpaceWidth + w > width && whiteSpace !== "nowrap" && whiteSpace !== "pre") {
1359
+ lineWidths.push(currentWidth2);
1360
+ baselines.push(currentBaselineOffset);
1361
+ lines++;
1362
+ height += currentLineHeight;
1363
+ currentWidth2 = w;
1364
+ currentLineHeight = w ? engine.height(word) : 0;
1365
+ currentBaselineOffset = w ? engine.baseline(word) : 0;
1366
+ lineSegmentNumber.push(1);
1367
+ lineIndex = -1;
1368
+ if (!forceBreak) {
1369
+ maxWidth = Math.max(maxWidth, width);
1370
+ }
1371
+ } else {
1372
+ currentWidth2 += remainingSpaceWidth + w;
1373
+ const glyphHeight = engine.height(word);
1374
+ if (glyphHeight > currentLineHeight) {
1375
+ currentLineHeight = glyphHeight;
1376
+ currentBaselineOffset = engine.baseline(word);
1377
+ }
1378
+ if (allowedToJustify) {
1379
+ lineSegmentNumber[lineSegmentNumber.length - 1]++;
1380
+ }
1381
+ }
1382
+ remainingSpace = "";
1383
+ remainingSpaceWidth = 0;
1384
+ if (allowedToJustify) {
1385
+ lineIndex++;
1386
+ }
1387
+ maxWidth = Math.max(maxWidth, currentWidth2);
1388
+ wordsInLayout[i2] = {
1389
+ y: height,
1390
+ x: currentWidth2 - w,
1391
+ width: w,
1392
+ line: lines,
1393
+ lineIndex
1394
+ };
1395
+ }
1396
+ }
1397
+ if (currentWidth2) {
1398
+ lines++;
1399
+ lineWidths.push(currentWidth2);
1400
+ baselines.push(currentBaselineOffset);
1401
+ height += currentLineHeight;
1402
+ }
1403
+ return { width: maxWidth, height };
1404
+ });
1405
+ const [x2, y] = yield;
1406
+ let result = "";
1407
+ let backgroundClipDef = "";
1408
+ const clipPathId = inheritedStyle._inheritedClipPathId;
1409
+ const {
1410
+ left: containerLeft,
1411
+ top: containerTop,
1412
+ width: containerWidth,
1413
+ height: containerHeight
1414
+ } = textContainer.getComputedLayout();
1415
+ const parentContainerInnerWidth = parent.getComputedWidth() - parent.getComputedPadding(Yoga3.EDGE_LEFT) - parent.getComputedPadding(Yoga3.EDGE_RIGHT) - parent.getComputedBorder(Yoga3.EDGE_LEFT) - parent.getComputedBorder(Yoga3.EDGE_RIGHT);
1416
+ const left = x2 + containerLeft;
1417
+ const top = y + containerTop;
1418
+ const { matrix, opacity } = container(
1419
+ {
1420
+ left: containerLeft,
1421
+ top: containerTop,
1422
+ width: containerWidth,
1423
+ height: containerHeight,
1424
+ isInheritingTransform
1425
+ },
1426
+ parentStyle
1427
+ );
1428
+ let filter = "";
1429
+ if (parentStyle.textShadowOffset) {
1430
+ filter = shadow(
1431
+ {
1432
+ width: containerWidth,
1433
+ height: containerHeight,
1434
+ id
1435
+ },
1436
+ {
1437
+ shadowColor: parentStyle.textShadowColor,
1438
+ shadowOffset: parentStyle.textShadowOffset,
1439
+ shadowRadius: parentStyle.textShadowRadius
1440
+ }
1441
+ );
1442
+ }
1443
+ let decorationShape = "";
1444
+ let mergedPath = "";
1445
+ let extra = "";
1446
+ let skippedLine = -1;
1447
+ let ellipsisWidth = textOverflow === "ellipsis" ? measureWithCache(["\u2026"]) : 0;
1448
+ let spaceWidth = textOverflow === "ellipsis" ? measureWithCache([" "]) : 0;
1449
+ let decorationLines = {};
1450
+ for (let i2 = 0; i2 < words.length; i2++) {
1451
+ if (!wordsInLayout[i2])
1452
+ continue;
1453
+ const layout2 = wordsInLayout[i2];
1454
+ let word = words[i2];
1455
+ let path = null;
1456
+ const image2 = graphemeImages ? graphemeImages[word] : null;
1457
+ let topOffset = layout2.y;
1458
+ let leftOffset = layout2.x;
1459
+ const width = layout2.width;
1460
+ const line = layout2.line;
1461
+ if (line === skippedLine) {
1462
+ continue;
1463
+ }
1464
+ let extendedWidth = false;
1465
+ if (lineWidths.length > 1) {
1466
+ const remainingWidth = containerWidth - lineWidths[line];
1467
+ if (textAlign === "right" || textAlign === "end") {
1468
+ leftOffset += remainingWidth;
1469
+ } else if (textAlign === "center") {
1470
+ leftOffset += remainingWidth / 2;
1471
+ } else if (textAlign === "justify") {
1472
+ if (line < lineWidths.length - 1) {
1473
+ const segments = lineSegmentNumber[line];
1474
+ const gutter = segments > 1 ? remainingWidth / (segments - 1) : 0;
1475
+ leftOffset += gutter * layout2.lineIndex;
1476
+ extendedWidth = true;
1477
+ }
1478
+ }
1479
+ }
1480
+ if (!decorationLines[line]) {
1481
+ decorationLines[line] = [
1482
+ leftOffset,
1483
+ extendedWidth ? containerWidth : lineWidths[line]
1484
+ ];
1485
+ }
1486
+ if (textOverflow === "ellipsis") {
1487
+ if (lineWidths[line] > parentContainerInnerWidth) {
1488
+ if (layout2.x + width + ellipsisWidth + spaceWidth > parentContainerInnerWidth) {
1489
+ const chars = segment(word, "grapheme");
1490
+ let subset = "";
1491
+ let resolvedWidth = 0;
1492
+ for (const char of chars) {
1493
+ const w = layout2.x + measureWithCache([subset + char]);
1494
+ if (subset && w + ellipsisWidth > parentContainerInnerWidth) {
1495
+ break;
1496
+ }
1497
+ subset += char;
1498
+ resolvedWidth = w;
1499
+ }
1500
+ word = subset + "\u2026";
1501
+ skippedLine = line;
1502
+ decorationLines[line][1] = resolvedWidth;
1503
+ }
1504
+ }
1505
+ }
1506
+ const baselineOfLine = baselines[line];
1507
+ const baselineOfWord = engine.baseline(word);
1508
+ const heightOfWord = engine.height(word);
1509
+ const baselineDelta = baselineOfLine - baselineOfWord;
1510
+ if (image2) {
1511
+ topOffset += 0;
1512
+ } else if (embedFont) {
1513
+ path = engine.getSVG(word, {
1514
+ ...parentStyle,
1515
+ left: left + leftOffset,
1516
+ top: top + topOffset + baselineOfWord + baselineDelta,
1517
+ letterSpacing: parentStyle.letterSpacing
1518
+ });
1519
+ if (debug) {
1520
+ extra += buildXMLString("rect", {
1521
+ x: left + leftOffset,
1522
+ y: top + topOffset + baselineDelta,
1523
+ width: layout2.width,
1524
+ height: heightOfWord,
1525
+ fill: "transparent",
1526
+ stroke: "#575eff",
1527
+ "stroke-width": 1,
1528
+ transform: matrix ? matrix : void 0,
1529
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
1530
+ }) + buildXMLString("line", {
1531
+ x1: left + leftOffset,
1532
+ x2: left + leftOffset + layout2.width,
1533
+ y1: top + topOffset + baselineDelta + baselineOfWord,
1534
+ y2: top + topOffset + baselineDelta + baselineOfWord,
1535
+ stroke: "#14c000",
1536
+ "stroke-width": 1,
1537
+ transform: matrix ? matrix : void 0,
1538
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
1539
+ });
1540
+ }
1541
+ } else {
1542
+ topOffset += baselineOfWord + baselineDelta;
1543
+ }
1544
+ if (parentStyle.textDecorationLine) {
1545
+ if (line !== ((_a = wordsInLayout[i2 + 1]) == null ? void 0 : _a.line) || skippedLine === line) {
1546
+ const deco = decorationLines[line];
1547
+ if (deco && !deco[2]) {
1548
+ decorationShape += decoration(
1549
+ {
1550
+ left: left + deco[0],
1551
+ top: top + heightOfWord * +line,
1552
+ width: deco[1],
1553
+ ascender: engine.baseline(word),
1554
+ clipPathId
1555
+ },
1556
+ parentStyle
1557
+ );
1558
+ deco[2] = 1;
1559
+ }
1560
+ }
1561
+ }
1562
+ if (path !== null) {
1563
+ mergedPath += path + " ";
1564
+ } else {
1565
+ const [t, shape] = text(
1566
+ {
1567
+ content: word,
1568
+ filter,
1569
+ id,
1570
+ left: left + leftOffset,
1571
+ top: top + topOffset,
1572
+ width,
1573
+ height: heightOfWord,
1574
+ matrix,
1575
+ opacity,
1576
+ image: image2,
1577
+ clipPathId,
1578
+ debug,
1579
+ shape: !!_inheritedBackgroundClipTextPath,
1580
+ decorationShape
1581
+ },
1582
+ parentStyle
1583
+ );
1584
+ result += t;
1585
+ backgroundClipDef += shape;
1586
+ decorationShape = "";
1587
+ }
1588
+ }
1589
+ if (mergedPath) {
1590
+ const p2 = parentStyle.color !== "transparent" && opacity !== 0 ? buildXMLString("path", {
1591
+ fill: parentStyle.color,
1592
+ d: mergedPath,
1593
+ transform: matrix ? matrix : void 0,
1594
+ opacity: opacity !== 1 ? opacity : void 0,
1595
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0,
1596
+ style: cssFilter ? `filter:${cssFilter}` : void 0
1597
+ }) : "";
1598
+ if (!!_inheritedBackgroundClipTextPath) {
1599
+ backgroundClipDef = buildXMLString("path", {
1600
+ d: mergedPath,
1601
+ transform: matrix ? matrix : void 0
1602
+ });
1603
+ }
1604
+ result += (filter ? filter + buildXMLString(
1605
+ "g",
1606
+ { filter: `url(#satori_s-${id})` },
1607
+ p2 + decorationShape
1608
+ ) : p2 + decorationShape) + extra;
1609
+ }
1610
+ if (backgroundClipDef) {
1611
+ ;
1612
+ parentStyle._inheritedBackgroundClipTextPath.value += backgroundClipDef;
1613
+ }
1614
+ return result;
1615
+ }
1616
+
1617
+ // src/vendor/gradient-parser/index.js
1618
+ var GradientParser = GradientParser || {};
1619
+ GradientParser.parse = function() {
1620
+ var tokens = {
1621
+ linearGradient: /^(\-(webkit|o|ms|moz)\-)?(linear\-gradient)/i,
1622
+ repeatingLinearGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-linear\-gradient)/i,
1623
+ radialGradient: /^(\-(webkit|o|ms|moz)\-)?(radial\-gradient)/i,
1624
+ repeatingRadialGradient: /^(\-(webkit|o|ms|moz)\-)?(repeating\-radial\-gradient)/i,
1625
+ sideOrCorner: /^to (left (top|bottom)|right (top|bottom)|top (left|right)|bottom (left|right)|left|right|top|bottom)/i,
1626
+ extentKeywords: /^(closest\-side|closest\-corner|farthest\-side|farthest\-corner|contain|cover)/,
1627
+ positionKeywords: /^(left|center|right|top|bottom)/i,
1628
+ pixelValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))px/,
1629
+ percentageValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))\%/,
1630
+ emValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))em/,
1631
+ angleValue: /^(-?(([0-9]*\.[0-9]+)|([0-9]+\.?)))deg/,
1632
+ startCall: /^\(/,
1633
+ endCall: /^\)/,
1634
+ comma: /^,/,
1635
+ hexColor: /^\#([0-9a-fA-F]+)/,
1636
+ literalColor: /^([a-zA-Z]+)/,
1637
+ rgbColor: /^rgb/i,
1638
+ rgbaColor: /^rgba/i,
1639
+ number: /^(([0-9]*\.[0-9]+)|([0-9]+\.?))/
1640
+ };
1641
+ var input = "";
1642
+ function error(msg) {
1643
+ var err = new Error(input + ": " + msg);
1644
+ err.source = input;
1645
+ throw err;
1646
+ }
1647
+ function getAST() {
1648
+ var ast = matchListDefinitions();
1649
+ if (input.length > 0) {
1650
+ error("Invalid input not EOF");
1651
+ }
1652
+ return ast;
1653
+ }
1654
+ function matchListDefinitions() {
1655
+ return matchListing(matchDefinition);
1656
+ }
1657
+ function matchDefinition() {
1658
+ return matchGradient(
1659
+ "linear-gradient",
1660
+ tokens.linearGradient,
1661
+ matchLinearOrientation
1662
+ ) || matchGradient(
1663
+ "repeating-linear-gradient",
1664
+ tokens.repeatingLinearGradient,
1665
+ matchLinearOrientation
1666
+ ) || matchGradient(
1667
+ "radial-gradient",
1668
+ tokens.radialGradient,
1669
+ matchListRadialOrientations
1670
+ ) || matchGradient(
1671
+ "repeating-radial-gradient",
1672
+ tokens.repeatingRadialGradient,
1673
+ matchListRadialOrientations
1674
+ );
1675
+ }
1676
+ function matchGradient(gradientType, pattern, orientationMatcher) {
1677
+ return matchCall(pattern, function(captures) {
1678
+ var orientation = orientationMatcher();
1679
+ if (orientation) {
1680
+ if (!scan(tokens.comma)) {
1681
+ error("Missing comma before color stops");
1682
+ }
1683
+ }
1684
+ return {
1685
+ type: gradientType,
1686
+ orientation,
1687
+ colorStops: matchListing(matchColorStop)
1688
+ };
1689
+ });
1690
+ }
1691
+ function matchCall(pattern, callback) {
1692
+ var captures = scan(pattern);
1693
+ if (captures) {
1694
+ if (!scan(tokens.startCall)) {
1695
+ error("Missing (");
1696
+ }
1697
+ var result = callback(captures);
1698
+ if (!scan(tokens.endCall)) {
1699
+ error("Missing )");
1700
+ }
1701
+ return result;
1702
+ }
1703
+ }
1704
+ function matchLinearOrientation() {
1705
+ return matchSideOrCorner() || matchAngle();
1706
+ }
1707
+ function matchSideOrCorner() {
1708
+ return match("directional", tokens.sideOrCorner, 1);
1709
+ }
1710
+ function matchAngle() {
1711
+ return match("angular", tokens.angleValue, 1);
1712
+ }
1713
+ function matchListRadialOrientations() {
1714
+ var radialOrientations, radialOrientation = matchRadialOrientation(), lookaheadCache;
1715
+ if (radialOrientation) {
1716
+ radialOrientations = [];
1717
+ radialOrientations.push(radialOrientation);
1718
+ lookaheadCache = input;
1719
+ if (scan(tokens.comma)) {
1720
+ radialOrientation = matchRadialOrientation();
1721
+ if (radialOrientation) {
1722
+ radialOrientations.push(radialOrientation);
1723
+ } else {
1724
+ input = lookaheadCache;
1725
+ }
1726
+ }
1727
+ }
1728
+ return radialOrientations;
1729
+ }
1730
+ function matchRadialOrientation() {
1731
+ var radialType = matchCircle() || matchEllipse();
1732
+ if (radialType) {
1733
+ radialType.at = matchAtPosition();
1734
+ } else {
1735
+ var extent = matchExtentKeyword();
1736
+ if (extent) {
1737
+ radialType = extent;
1738
+ var positionAt = matchAtPosition();
1739
+ if (positionAt) {
1740
+ radialType.at = positionAt;
1741
+ }
1742
+ } else {
1743
+ var defaultPosition = matchPositioning();
1744
+ if (defaultPosition) {
1745
+ radialType = {
1746
+ type: "default-radial",
1747
+ at: defaultPosition
1748
+ };
1749
+ }
1750
+ }
1751
+ }
1752
+ return radialType;
1753
+ }
1754
+ function matchCircle() {
1755
+ var circle = match("shape", /^(circle)/i, 0);
1756
+ if (circle) {
1757
+ circle.style = matchLength() || matchExtentKeyword();
1758
+ }
1759
+ return circle;
1760
+ }
1761
+ function matchEllipse() {
1762
+ var ellipse = match("shape", /^(ellipse)/i, 0);
1763
+ if (ellipse) {
1764
+ ellipse.style = matchDistance() || matchExtentKeyword();
1765
+ }
1766
+ return ellipse;
1767
+ }
1768
+ function matchExtentKeyword() {
1769
+ return match("extent-keyword", tokens.extentKeywords, 1);
1770
+ }
1771
+ function matchAtPosition() {
1772
+ if (match("position", /^at/, 0)) {
1773
+ var positioning = matchPositioning();
1774
+ if (!positioning) {
1775
+ error("Missing positioning value");
1776
+ }
1777
+ return positioning;
1778
+ }
1779
+ }
1780
+ function matchPositioning() {
1781
+ var location = matchCoordinates();
1782
+ if (location.x || location.y) {
1783
+ return {
1784
+ type: "position",
1785
+ value: location
1786
+ };
1787
+ }
1788
+ }
1789
+ function matchCoordinates() {
1790
+ return {
1791
+ x: matchDistance(),
1792
+ y: matchDistance()
1793
+ };
1794
+ }
1795
+ function matchListing(matcher) {
1796
+ var captures = matcher(), result = [];
1797
+ if (captures) {
1798
+ result.push(captures);
1799
+ while (scan(tokens.comma)) {
1800
+ captures = matcher();
1801
+ if (captures) {
1802
+ result.push(captures);
1803
+ } else {
1804
+ error("One extra comma");
1805
+ }
1806
+ }
1807
+ }
1808
+ return result;
1809
+ }
1810
+ function matchColorStop() {
1811
+ var color = matchColor();
1812
+ if (!color) {
1813
+ error("Expected color definition");
1814
+ }
1815
+ color.length = matchDistance();
1816
+ return color;
1817
+ }
1818
+ function matchColor() {
1819
+ return matchHexColor() || matchRGBAColor() || matchRGBColor() || matchLiteralColor();
1820
+ }
1821
+ function matchLiteralColor() {
1822
+ return match("literal", tokens.literalColor, 0);
1823
+ }
1824
+ function matchHexColor() {
1825
+ return match("hex", tokens.hexColor, 1);
1826
+ }
1827
+ function matchRGBColor() {
1828
+ return matchCall(tokens.rgbColor, function() {
1829
+ return {
1830
+ type: "rgb",
1831
+ value: matchListing(matchNumber)
1832
+ };
1833
+ });
1834
+ }
1835
+ function matchRGBAColor() {
1836
+ return matchCall(tokens.rgbaColor, function() {
1837
+ return {
1838
+ type: "rgba",
1839
+ value: matchListing(matchNumber)
1840
+ };
1841
+ });
1842
+ }
1843
+ function matchNumber() {
1844
+ return scan(tokens.number)[1];
1845
+ }
1846
+ function matchDistance() {
1847
+ return match("%", tokens.percentageValue, 1) || matchPositionKeyword() || matchLength();
1848
+ }
1849
+ function matchPositionKeyword() {
1850
+ return match("position-keyword", tokens.positionKeywords, 1);
1851
+ }
1852
+ function matchLength() {
1853
+ return match("px", tokens.pixelValue, 1) || match("em", tokens.emValue, 1);
1854
+ }
1855
+ function match(type, pattern, captureIndex) {
1856
+ var captures = scan(pattern);
1857
+ if (captures) {
1858
+ return {
1859
+ type,
1860
+ value: captures[captureIndex]
1861
+ };
1862
+ }
1863
+ }
1864
+ function scan(regexp) {
1865
+ var captures, blankCaptures;
1866
+ blankCaptures = /^[\n\r\t\s]+/.exec(input);
1867
+ if (blankCaptures) {
1868
+ consume(blankCaptures[0].length);
1869
+ }
1870
+ captures = regexp.exec(input);
1871
+ if (captures) {
1872
+ consume(captures[0].length);
1873
+ }
1874
+ return captures;
1875
+ }
1876
+ function consume(size) {
1877
+ input = input.substr(size);
1878
+ }
1879
+ return function(code2) {
1880
+ input = code2.toString();
1881
+ return getAST();
1882
+ };
1883
+ }();
1884
+ var gradient_parser_default = GradientParser;
1885
+
1886
+ // src/handler/image.ts
1887
+ var cache = createLRU(100);
1888
+ var inflightRequests = /* @__PURE__ */ new Map();
1889
+ var ALLOWED_IMAGE_TYPES = [
1890
+ "image/png",
1891
+ "image/jpeg",
1892
+ "image/gif",
1893
+ "image/svg+xml"
1894
+ ];
1895
+ function arrayBufferToBase64(buffer) {
1896
+ let binary = "";
1897
+ const bytes = new Uint8Array(buffer);
1898
+ for (let i2 = 0; i2 < bytes.byteLength; i2++) {
1899
+ binary += String.fromCharCode(bytes[i2]);
1900
+ }
1901
+ return btoa(binary);
1902
+ }
1903
+ async function resolveImageData(src) {
1904
+ if (!src) {
1905
+ throw new Error("Image URL is not provided");
1906
+ }
1907
+ if (src.startsWith("data:")) {
1908
+ return src;
1909
+ }
1910
+ if (!globalThis.fetch) {
1911
+ throw new Error("`fetch` is required to be polyfilled to load images.");
1912
+ }
1913
+ if (inflightRequests.has(src)) {
1914
+ return inflightRequests.get(src);
1915
+ }
1916
+ const cached = cache.get(src);
1917
+ if (cached) {
1918
+ return cached;
1919
+ }
1920
+ const promise = new Promise((resolve, reject) => {
1921
+ let imageType;
1922
+ fetch(src).then((res) => {
1923
+ imageType = res.headers.get("content-type").toLowerCase();
1924
+ if (!ALLOWED_IMAGE_TYPES.includes(imageType)) {
1925
+ throw new Error(`Unsupported image type: ${imageType}`);
1926
+ }
1927
+ return res.arrayBuffer();
1928
+ }).then((data) => {
1929
+ const newSrc = `data:${imageType};base64,${arrayBufferToBase64(data)}`;
1930
+ cache.set(src, newSrc);
1931
+ resolve(newSrc);
1932
+ }).catch(reject);
1933
+ });
1934
+ inflightRequests.set(src, promise);
1935
+ return promise;
1936
+ }
1937
+
1938
+ // src/builder/background-image.ts
1939
+ function resolveColorFromStop(stop) {
1940
+ if (stop.type === "literal")
1941
+ return stop.value;
1942
+ if (stop.type === "hex")
1943
+ return `#${stop.value}`;
1944
+ if (stop.type === "rgb")
1945
+ return `rgb(${stop.value.join(",")})`;
1946
+ if (stop.type === "rgba")
1947
+ return `rgba(${stop.value.join(",")})`;
1948
+ return "transparent";
1949
+ }
1950
+ function toAbsoluteValue(v2, base) {
1951
+ if (typeof v2 === "string" && v2.endsWith("%")) {
1952
+ return base * parseFloat(v2) / 100;
1953
+ }
1954
+ return +v2;
1955
+ }
1956
+ function parseLengthPairs(str, {
1957
+ x: x2,
1958
+ y,
1959
+ defaultX,
1960
+ defaultY
1961
+ }) {
1962
+ return (str ? str.split(" ").map((value) => {
1963
+ try {
1964
+ const parsed = new U(value);
1965
+ return parsed.type === "length" || parsed.type === "number" ? parsed.value : parsed.value + parsed.unit;
1966
+ } catch (e2) {
1967
+ return null;
1968
+ }
1969
+ }).filter((v2) => v2 !== null) : [defaultX, defaultY]).map((v2, index) => toAbsoluteValue(v2, [x2, y][index]));
1970
+ }
1971
+ function normalizeStops(totalLength, colorStops) {
1972
+ const stops = [];
1973
+ for (const stop of colorStops) {
1974
+ const color = resolveColorFromStop(stop);
1975
+ if (!stops.length) {
1976
+ stops.push({
1977
+ offset: 0,
1978
+ color
1979
+ });
1980
+ if (typeof stop.length === "undefined")
1981
+ continue;
1982
+ if (stop.length.value === "0")
1983
+ continue;
1984
+ }
1985
+ const offset = typeof stop.length === "undefined" ? void 0 : stop.length.type === "%" ? stop.length.value / 100 : stop.length.value / totalLength;
1986
+ stops.push({
1987
+ offset,
1988
+ color
1989
+ });
1990
+ }
1991
+ if (!stops.length) {
1992
+ stops.push({
1993
+ offset: 0,
1994
+ color: "transparent"
1995
+ });
1996
+ }
1997
+ const lastStop = stops[stops.length - 1];
1998
+ if (lastStop.offset !== 1) {
1999
+ if (typeof lastStop.offset === "undefined") {
2000
+ lastStop.offset = 1;
2001
+ } else {
2002
+ stops.push({
2003
+ offset: 1,
2004
+ color: lastStop.color
2005
+ });
2006
+ }
2007
+ }
2008
+ let previousStop = 0;
2009
+ let nextStop = 1;
2010
+ for (let i2 = 0; i2 < stops.length; i2++) {
2011
+ if (typeof stops[i2].offset === "undefined") {
2012
+ if (nextStop < i2)
2013
+ nextStop = i2;
2014
+ while (typeof stops[nextStop].offset === "undefined")
2015
+ nextStop++;
2016
+ stops[i2].offset = (stops[nextStop].offset - stops[previousStop].offset) / (nextStop - previousStop) * (i2 - previousStop) + stops[previousStop].offset;
2017
+ } else {
2018
+ previousStop = i2;
2019
+ }
2020
+ }
2021
+ return stops;
2022
+ }
2023
+ async function backgroundImage({ id, width, height }, { image: image2, size, position, repeat }) {
2024
+ repeat = repeat || "repeat";
2025
+ const repeatX = repeat === "repeat-x" || repeat === "repeat";
2026
+ const repeatY = repeat === "repeat-y" || repeat === "repeat";
2027
+ const dimensions = parseLengthPairs(size, {
2028
+ x: width,
2029
+ y: height,
2030
+ defaultX: width,
2031
+ defaultY: height
2032
+ });
2033
+ const offsets = parseLengthPairs(position, {
2034
+ x: width,
2035
+ y: height,
2036
+ defaultX: 0,
2037
+ defaultY: 0
2038
+ });
2039
+ if (image2.startsWith("linear-gradient(")) {
2040
+ const parsed = gradient_parser_default.parse(image2)[0];
2041
+ let x1, y1, x2, y2;
2042
+ if (parsed.orientation.type === "directional") {
2043
+ ;
2044
+ [x1, y1, x2, y2] = {
2045
+ top: [0, 1, 0, 0],
2046
+ bottom: [0, 0, 0, 1],
2047
+ left: [1, 0, 0, 0],
2048
+ right: [0, 0, 1, 0]
2049
+ }[parsed.orientation.value];
2050
+ } else if (parsed.orientation.type === "angular") {
2051
+ const angle = +parsed.orientation.value / 180 * Math.PI - Math.PI / 2;
2052
+ const c2 = Math.cos(angle);
2053
+ const s2 = Math.sin(angle);
2054
+ x1 = 0;
2055
+ y1 = 0;
2056
+ x2 = c2;
2057
+ y2 = s2;
2058
+ if (x2 < 0) {
2059
+ x1 -= x2;
2060
+ x2 = 0;
2061
+ }
2062
+ if (y2 < 0) {
2063
+ y1 -= y2;
2064
+ y2 = 0;
2065
+ }
2066
+ }
2067
+ const stops = normalizeStops(width, parsed.colorStops);
2068
+ return [
2069
+ `satori_bi${id}`,
2070
+ `<linearGradient id="satori_bi${id}" x1="${x1}" y1="${y1}" x2="${x2}" y2="${y2}">${stops.map(
2071
+ (stop) => `<stop offset="${stop.offset * 100}%" stop-color="${stop.color}"/>`
2072
+ ).join("")}</linearGradient>`
2073
+ ];
2074
+ }
2075
+ if (image2.startsWith("radial-gradient(")) {
2076
+ const parsed = gradient_parser_default.parse(image2)[0];
2077
+ const orientation = parsed.orientation[0];
2078
+ const [xDelta, yDelta] = dimensions;
2079
+ let shape = "circle";
2080
+ let cx = xDelta / 2;
2081
+ let cy = yDelta / 2;
2082
+ if (orientation.type === "shape") {
2083
+ shape = orientation.value;
2084
+ if (!orientation.at) {
2085
+ } else if (orientation.at.type === "position") {
2086
+ cx = orientation.at.value.x.value;
2087
+ cy = orientation.at.value.y.value;
2088
+ } else {
2089
+ throw new Error(
2090
+ "orientation.at.type not implemented: " + orientation.at.type
2091
+ );
2092
+ }
2093
+ } else {
2094
+ throw new Error("orientation.type not implemented: " + orientation.type);
2095
+ }
2096
+ const stops = normalizeStops(width, parsed.colorStops);
2097
+ const gradientId = `satori_radial_${id}`;
2098
+ const patternId = `satori_pattern_${id}`;
2099
+ const spread = {};
2100
+ const fx = Math.max(Math.abs(xDelta - cx), Math.abs(cx));
2101
+ const fy = Math.max(Math.abs(yDelta - cy), Math.abs(cy));
2102
+ if (shape === "circle") {
2103
+ spread.r = Math.sqrt(fx * fx + fy * fy);
2104
+ } else if (shape === "ellipse") {
2105
+ const ratio = fy !== 0 ? fx / fy : 1;
2106
+ spread.ry = Math.sqrt(fx * fx + fy * fy * ratio * ratio) / ratio;
2107
+ spread.rx = spread.ry * ratio;
2108
+ }
2109
+ const defs = buildXMLString(
2110
+ "pattern",
2111
+ {
2112
+ id: patternId,
2113
+ x: offsets[0],
2114
+ y: offsets[1],
2115
+ width: repeatX ? xDelta : "100%",
2116
+ height: repeatY ? yDelta : "100%",
2117
+ patternUnits: "userSpaceOnUse"
2118
+ },
2119
+ buildXMLString(
2120
+ "radialGradient",
2121
+ {
2122
+ id: gradientId
2123
+ },
2124
+ stops.map(
2125
+ (stop) => buildXMLString("stop", {
2126
+ offset: stop.offset,
2127
+ "stop-color": stop.color
2128
+ })
2129
+ ).join("")
2130
+ ) + buildXMLString(shape, {
2131
+ cx,
2132
+ cy,
2133
+ width: xDelta,
2134
+ height: yDelta,
2135
+ ...spread,
2136
+ fill: `url(#${gradientId})`
2137
+ })
2138
+ );
2139
+ const result = [patternId, defs];
2140
+ return result;
2141
+ }
2142
+ if (image2.startsWith("url(")) {
2143
+ const src = await resolveImageData(image2.slice(4, -1));
2144
+ return [
2145
+ `satori_bi${id}`,
2146
+ buildXMLString(
2147
+ "pattern",
2148
+ {
2149
+ id: `satori_bi${id}`,
2150
+ patternContentUnits: "userSpaceOnUse",
2151
+ patternUnits: "userSpaceOnUse",
2152
+ x: offsets[0],
2153
+ y: offsets[1],
2154
+ width: repeatX ? dimensions[0] : "100%",
2155
+ height: repeatY ? dimensions[1] : "100%"
2156
+ },
2157
+ buildXMLString("image", {
2158
+ x: 0,
2159
+ y: 0,
2160
+ width: dimensions[0],
2161
+ height: dimensions[1],
2162
+ href: src
2163
+ })
2164
+ )
2165
+ ];
2166
+ }
2167
+ }
2168
+
2169
+ // src/builder/border-radius.ts
2170
+ function resolveSize(a2, b, limit) {
2171
+ if (limit < a2 + b) {
2172
+ if (limit / 2 < a2 && limit / 2 < b) {
2173
+ a2 = b = limit / 2;
2174
+ } else if (limit / 2 < a2) {
2175
+ a2 = limit - b;
2176
+ } else if (limit / 2 < b) {
2177
+ b = limit - a2;
2178
+ }
2179
+ }
2180
+ return [a2, b];
2181
+ }
2182
+ function radius({
2183
+ left,
2184
+ top,
2185
+ width,
2186
+ height
2187
+ }, style) {
2188
+ let {
2189
+ borderTopLeftRadius,
2190
+ borderTopRightRadius,
2191
+ borderBottomLeftRadius,
2192
+ borderBottomRightRadius
2193
+ } = style;
2194
+ borderTopLeftRadius = Math.min(borderTopLeftRadius || 0, width, height);
2195
+ borderTopRightRadius = Math.min(borderTopRightRadius || 0, width, height);
2196
+ borderBottomLeftRadius = Math.min(borderBottomLeftRadius || 0, width, height);
2197
+ borderBottomRightRadius = Math.min(
2198
+ borderBottomRightRadius || 0,
2199
+ width,
2200
+ height
2201
+ );
2202
+ if (!borderTopLeftRadius && !borderTopRightRadius && !borderBottomLeftRadius && !borderBottomRightRadius) {
2203
+ return "";
2204
+ }
2205
+ ;
2206
+ [borderTopLeftRadius, borderTopRightRadius] = resolveSize(
2207
+ borderTopLeftRadius,
2208
+ borderTopRightRadius,
2209
+ width
2210
+ );
2211
+ [borderTopLeftRadius, borderBottomLeftRadius] = resolveSize(
2212
+ borderTopLeftRadius,
2213
+ borderBottomLeftRadius,
2214
+ height
2215
+ );
2216
+ [borderTopRightRadius, borderBottomRightRadius] = resolveSize(
2217
+ borderTopRightRadius,
2218
+ borderBottomRightRadius,
2219
+ height
2220
+ );
2221
+ [borderBottomLeftRadius, borderBottomRightRadius] = resolveSize(
2222
+ borderBottomLeftRadius,
2223
+ borderBottomRightRadius,
2224
+ width
2225
+ );
2226
+ return `M${left + borderTopLeftRadius},${top} h${width - borderTopLeftRadius - borderTopRightRadius} a${borderTopRightRadius},${borderTopRightRadius} 0 0 1 ${borderTopRightRadius},${borderTopRightRadius} v${height - borderTopRightRadius - borderBottomRightRadius} a${borderBottomRightRadius},${borderBottomRightRadius} 0 0 1 ${-borderBottomRightRadius},${borderBottomRightRadius} h${borderBottomRightRadius + borderBottomLeftRadius - width} a${borderBottomLeftRadius},${borderBottomLeftRadius} 0 0 1 ${-borderBottomLeftRadius},${-borderBottomLeftRadius} v${borderBottomLeftRadius + borderTopLeftRadius - height} a${borderTopLeftRadius},${borderTopLeftRadius} 0 0 1 ${borderTopLeftRadius},${-borderTopLeftRadius}`;
2227
+ }
2228
+
2229
+ // src/builder/overflow.ts
2230
+ function overflow({
2231
+ left,
2232
+ top,
2233
+ width,
2234
+ height,
2235
+ path,
2236
+ id
2237
+ }, style) {
2238
+ if (style.overflow !== "hidden") {
2239
+ return "";
2240
+ }
2241
+ if (path) {
2242
+ return buildXMLString(
2243
+ "clipPath",
2244
+ {
2245
+ id: `satori_cp-${id}`,
2246
+ "clip-path": style._inheritedClipPathId ? `url(#${style._inheritedClipPathId})` : void 0
2247
+ },
2248
+ buildXMLString("path", {
2249
+ x: left,
2250
+ y: top,
2251
+ width,
2252
+ height,
2253
+ d: path
2254
+ })
2255
+ );
2256
+ }
2257
+ return buildXMLString(
2258
+ "clipPath",
2259
+ {
2260
+ id: `satori_cp-${id}`,
2261
+ "clip-path": style._inheritedClipPathId ? `url(#${style._inheritedClipPathId})` : void 0
2262
+ },
2263
+ buildXMLString("rect", {
2264
+ x: left,
2265
+ y: top,
2266
+ width,
2267
+ height
2268
+ })
2269
+ );
2270
+ }
2271
+
2272
+ // src/builder/rect.ts
2273
+ async function rect({
2274
+ id,
2275
+ left,
2276
+ top,
2277
+ width,
2278
+ height,
2279
+ isInheritingTransform,
2280
+ debug
2281
+ }, style) {
2282
+ if (style.display === "none")
2283
+ return "";
2284
+ let type = "rect";
2285
+ let stroke = "transparent";
2286
+ let strokeDashArray = "";
2287
+ let strokeWidth = 0;
2288
+ let matrix = "";
2289
+ let defs = "";
2290
+ let fills = [];
2291
+ let opacity = 1;
2292
+ let extra = "";
2293
+ if (style.backgroundColor) {
2294
+ fills.push(style.backgroundColor);
2295
+ }
2296
+ if (style.borderWidth) {
2297
+ strokeWidth = style.borderWidth;
2298
+ stroke = style.borderColor;
2299
+ if (style.borderStyle === "dashed") {
2300
+ strokeDashArray = strokeWidth * 2 + " " + strokeWidth;
2301
+ }
2302
+ }
2303
+ if (style.opacity) {
2304
+ opacity = +style.opacity;
2305
+ }
2306
+ if (style.transform) {
2307
+ matrix = transform(
2308
+ {
2309
+ left,
2310
+ top,
2311
+ width,
2312
+ height
2313
+ },
2314
+ style.transform,
2315
+ isInheritingTransform,
2316
+ style.transformOrigin
2317
+ );
2318
+ }
2319
+ let backgroundShapes = "";
2320
+ if (style.backgroundImage) {
2321
+ const backgrounds = [];
2322
+ for (let index = 0; index < style.backgroundImage.length; index++) {
2323
+ const background = style.backgroundImage[index];
2324
+ const image2 = await backgroundImage(
2325
+ { id: id + "_" + index, width, height },
2326
+ background
2327
+ );
2328
+ if (image2) {
2329
+ backgrounds.push(image2);
2330
+ }
2331
+ }
2332
+ for (const background of backgrounds) {
2333
+ fills.push(`url(#${background[0]})`);
2334
+ defs += background[1];
2335
+ if (background[2]) {
2336
+ backgroundShapes += background[2];
2337
+ }
2338
+ }
2339
+ }
2340
+ const path = radius(
2341
+ { left, top, width, height },
2342
+ style
2343
+ );
2344
+ if (path) {
2345
+ type = "path";
2346
+ }
2347
+ const clip = overflow(
2348
+ { left, top, width, height, path, id },
2349
+ style
2350
+ );
2351
+ const clipPathId = style._inheritedClipPathId;
2352
+ const filter = shadow({ width, height, id }, style);
2353
+ if (debug) {
2354
+ extra = buildXMLString("rect", {
2355
+ x: left,
2356
+ y: top,
2357
+ width,
2358
+ height,
2359
+ fill: "transparent",
2360
+ stroke: "#ff5757",
2361
+ "stroke-width": 1,
2362
+ "stroke-dasharray": strokeDashArray || void 0,
2363
+ transform: matrix || void 0,
2364
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
2365
+ });
2366
+ }
2367
+ if (!fills.length)
2368
+ fills.push("transparent");
2369
+ const { backgroundClip, filter: cssFilter } = style;
2370
+ let shape = fills.map((fill, i2) => {
2371
+ if (fill === "transparent" && !(i2 === fills.length - 1 && strokeWidth)) {
2372
+ return "";
2373
+ }
2374
+ const hasStroke = !!strokeWidth;
2375
+ const drawStroke = i2 === fills.length - 1 && hasStroke && backgroundClip !== "text";
2376
+ let currentClipPath = backgroundClip === "text" ? `url(#satori_bct-${id})` : clipPathId ? `url(#${clipPathId})` : void 0;
2377
+ if (drawStroke) {
2378
+ defs += buildXMLString(
2379
+ "clipPath",
2380
+ {
2381
+ id: `satori_bc-${id}`,
2382
+ "clip-path": currentClipPath
2383
+ },
2384
+ buildXMLString(type, {
2385
+ x: left,
2386
+ y: top,
2387
+ width,
2388
+ height,
2389
+ d: path ? path : void 0
2390
+ })
2391
+ );
2392
+ currentClipPath = `url(#satori_bc-${id})`;
2393
+ }
2394
+ return buildXMLString(type, {
2395
+ x: left,
2396
+ y: top,
2397
+ width,
2398
+ height,
2399
+ fill,
2400
+ stroke: drawStroke || hasStroke ? stroke : void 0,
2401
+ "stroke-width": drawStroke ? strokeWidth * 2 : hasStroke ? 1 : void 0,
2402
+ "stroke-dasharray": strokeDashArray || void 0,
2403
+ d: path ? path : void 0,
2404
+ transform: matrix ? matrix : void 0,
2405
+ "clip-path": currentClipPath,
2406
+ style: cssFilter ? `filter:${cssFilter}` : void 0
2407
+ });
2408
+ }).join("");
2409
+ if (backgroundClip === "text" && strokeWidth) {
2410
+ shape = buildXMLString(type, {
2411
+ x: left,
2412
+ y: top,
2413
+ width,
2414
+ height,
2415
+ fill: "transparent",
2416
+ stroke,
2417
+ "stroke-width": strokeWidth * 2,
2418
+ "stroke-dasharray": strokeDashArray || void 0,
2419
+ d: path ? path : void 0,
2420
+ transform: matrix ? matrix : void 0,
2421
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
2422
+ }) + shape;
2423
+ }
2424
+ return (defs ? `<defs>${defs}</defs>` : "") + clip + (filter ? `${filter}<g filter="url(#satori_s-${id})">` : "") + (opacity !== 1 ? `<g opacity="${opacity}">` : "") + (backgroundShapes || shape) + (opacity !== 1 ? `</g>` : "") + (filter ? "</g>" : "") + extra;
2425
+ }
2426
+
2427
+ // src/builder/image.ts
2428
+ function image({
2429
+ id,
2430
+ left,
2431
+ top,
2432
+ width,
2433
+ height,
2434
+ src,
2435
+ debug: _debug,
2436
+ isInheritingTransform
2437
+ }, style) {
2438
+ if (style.display === "none")
2439
+ return "";
2440
+ let clip = "";
2441
+ let opacity = 1;
2442
+ let matrix = "";
2443
+ const preserveAspectRatio = style.objectFit === "contain" ? "xMidYMid" : style.objectFit === "cover" ? "xMidYMid slice" : "none";
2444
+ const path = radius(
2445
+ { left, top, width, height },
2446
+ style
2447
+ );
2448
+ const clipPathId = style._inheritedClipPathId;
2449
+ if (path) {
2450
+ clip = buildXMLString(
2451
+ "clipPath",
2452
+ {
2453
+ id: `satori_c-${id}`,
2454
+ "clip-path": clipPathId ? `url(#${clipPathId})` : void 0
2455
+ },
2456
+ buildXMLString("path", {
2457
+ x: left,
2458
+ y: top,
2459
+ width,
2460
+ height,
2461
+ d: path
2462
+ })
2463
+ );
2464
+ }
2465
+ if (style.opacity) {
2466
+ opacity = +style.opacity;
2467
+ }
2468
+ const filter = shadow({ width, height, id }, style);
2469
+ if (style.transform) {
2470
+ matrix = transform(
2471
+ {
2472
+ left,
2473
+ top,
2474
+ width,
2475
+ height
2476
+ },
2477
+ style.transform,
2478
+ isInheritingTransform,
2479
+ style.transformOrigin
2480
+ );
2481
+ }
2482
+ return filter + (filter ? `<g filter="url(#satori_s-${id})">` : "") + clip + buildXMLString("image", {
2483
+ x: left,
2484
+ y: top,
2485
+ width,
2486
+ height,
2487
+ href: src,
2488
+ preserveAspectRatio,
2489
+ transform: matrix ? matrix : void 0,
2490
+ "clip-path": clip ? `url(#satori_c-${id})` : clipPathId ? `url(#${clipPathId})` : void 0
2491
+ }) + (filter ? `</g>` : "");
2492
+ }
2493
+
2494
+ // src/layout.ts
2495
+ async function* layout(element, context) {
2496
+ var _a;
2497
+ const Yoga3 = getYoga();
2498
+ const {
2499
+ id,
2500
+ inheritedStyle,
2501
+ parent,
2502
+ font,
2503
+ debug,
2504
+ embedFont = true,
2505
+ graphemeImages,
2506
+ canLoadAdditionalAssets
2507
+ } = context;
2508
+ if (element === null || typeof element === "undefined") {
2509
+ yield;
2510
+ yield;
2511
+ return "";
2512
+ }
2513
+ if (!isReactElement(element) || typeof element.type === "function") {
2514
+ let iter;
2515
+ if (!isReactElement(element)) {
2516
+ iter = buildTextNodes(String(element), context);
2517
+ yield (await iter.next()).value;
2518
+ } else {
2519
+ if (isClass(element.type)) {
2520
+ throw new Error("Class component is not supported.");
2521
+ }
2522
+ iter = layout(element.type(element.props), context);
2523
+ yield (await iter.next()).value;
2524
+ }
2525
+ await iter.next();
2526
+ const offset = yield;
2527
+ return (await iter.next(offset)).value;
2528
+ }
2529
+ const { type, props } = element;
2530
+ const { style, children } = props || {};
2531
+ const node = Yoga3.Node.create();
2532
+ parent.insertChild(node, parent.getChildCount());
2533
+ const [computedStyle, newInheritableStyle] = handler(
2534
+ node,
2535
+ type,
2536
+ inheritedStyle,
2537
+ style,
2538
+ props
2539
+ );
2540
+ const isInheritingTransform = computedStyle.transform === inheritedStyle.transform;
2541
+ if (!isInheritingTransform) {
2542
+ ;
2543
+ computedStyle.transform.__parent = inheritedStyle.transform;
2544
+ }
2545
+ if (computedStyle.overflow === "hidden") {
2546
+ newInheritableStyle._inheritedClipPathId = `satori_cp-${id}`;
2547
+ }
2548
+ if (computedStyle.backgroundClip === "text") {
2549
+ const mutateRefValue = { value: "" };
2550
+ newInheritableStyle._inheritedBackgroundClipTextPath = mutateRefValue;
2551
+ computedStyle._inheritedBackgroundClipTextPath = mutateRefValue;
2552
+ }
2553
+ const normalizedChildren = typeof children === "undefined" ? [] : [].concat(children).flat(Infinity);
2554
+ const iterators = [];
2555
+ let i2 = 0;
2556
+ const segmentsMissingFont = [];
2557
+ for (const child of normalizedChildren) {
2558
+ const iter = layout(child, {
2559
+ id: id + "-" + i2++,
2560
+ parentStyle: computedStyle,
2561
+ inheritedStyle: newInheritableStyle,
2562
+ isInheritingTransform: true,
2563
+ parent: node,
2564
+ font,
2565
+ embedFont,
2566
+ debug,
2567
+ graphemeImages,
2568
+ canLoadAdditionalAssets
2569
+ });
2570
+ if (canLoadAdditionalAssets) {
2571
+ segmentsMissingFont.push(...(await iter.next()).value || []);
2572
+ } else {
2573
+ await iter.next();
2574
+ }
2575
+ iterators.push(iter);
2576
+ }
2577
+ yield segmentsMissingFont;
2578
+ for (const iter of iterators)
2579
+ await iter.next();
2580
+ const [x2, y] = yield;
2581
+ if (computedStyle.position === "absolute") {
2582
+ node.calculateLayout();
2583
+ }
2584
+ let { left, top, width, height } = node.getComputedLayout();
2585
+ left += x2;
2586
+ top += y;
2587
+ let childrenRenderResult = "";
2588
+ let baseRenderResult = "";
2589
+ let depsRenderResult = "";
2590
+ if (type === "img") {
2591
+ const src = await resolveImageData(props.src);
2592
+ baseRenderResult = image(
2593
+ {
2594
+ id,
2595
+ left,
2596
+ top,
2597
+ width,
2598
+ height,
2599
+ src,
2600
+ isInheritingTransform,
2601
+ debug
2602
+ },
2603
+ computedStyle
2604
+ );
2605
+ } else if (type === "svg") {
2606
+ const src = SVGNodeToImage(element);
2607
+ baseRenderResult = image(
2608
+ {
2609
+ id,
2610
+ left,
2611
+ top,
2612
+ width,
2613
+ height,
2614
+ src,
2615
+ isInheritingTransform,
2616
+ debug
2617
+ },
2618
+ computedStyle
2619
+ );
2620
+ } else {
2621
+ const display = (_a = style == null ? void 0 : style.display) != null ? _a : "block";
2622
+ if (type === "div" && children && typeof children !== "string" && display !== "flex" && display !== "none") {
2623
+ throw new Error(
2624
+ `Expected <div> to have style={{display: 'flex'}} but received style={{display: '${display}'}}`
2625
+ );
2626
+ }
2627
+ baseRenderResult = await rect(
2628
+ { id, left, top, width, height, isInheritingTransform, debug },
2629
+ computedStyle
2630
+ );
2631
+ }
2632
+ for (const iter of iterators) {
2633
+ childrenRenderResult += (await iter.next([left, top])).value;
2634
+ }
2635
+ if (computedStyle._inheritedBackgroundClipTextPath) {
2636
+ depsRenderResult += buildXMLString(
2637
+ "clipPath",
2638
+ {
2639
+ id: `satori_bct-${id}`,
2640
+ "clip-path": computedStyle._inheritedClipPathId ? `url(#${computedStyle._inheritedClipPathId})` : void 0
2641
+ },
2642
+ computedStyle._inheritedBackgroundClipTextPath.value
2643
+ );
2644
+ }
2645
+ return depsRenderResult + baseRenderResult + childrenRenderResult;
2646
+ }
2647
+
2648
+ // src/font.ts
2649
+ import opentype from "@shuding/opentype.js";
2650
+ function compareFont(weight, style, [weight1, style1], [weight2, style2]) {
2651
+ if (weight1 !== weight2) {
2652
+ if (!weight1)
2653
+ return 1;
2654
+ if (!weight2)
2655
+ return -1;
2656
+ if (weight1 === weight)
2657
+ return -1;
2658
+ if (weight2 === weight)
2659
+ return 1;
2660
+ if (weight === 400 && weight1 === 500)
2661
+ return -1;
2662
+ if (weight === 500 && weight1 === 400)
2663
+ return -1;
2664
+ if (weight === 400 && weight2 === 500)
2665
+ return 1;
2666
+ if (weight === 500 && weight2 === 400)
2667
+ return 1;
2668
+ if (weight < 400) {
2669
+ if (weight1 < weight && weight2 < weight)
2670
+ return weight2 - weight1;
2671
+ if (weight1 < weight)
2672
+ return -1;
2673
+ if (weight2 < weight)
2674
+ return 1;
2675
+ return weight1 - weight2;
2676
+ }
2677
+ if (weight < weight1 && weight < weight2)
2678
+ return weight1 - weight2;
2679
+ if (weight < weight1)
2680
+ return -1;
2681
+ if (weight < weight2)
2682
+ return 1;
2683
+ return weight2 - weight1;
2684
+ }
2685
+ if (style1 !== style2) {
2686
+ if (style1 === style)
2687
+ return -1;
2688
+ if (style2 === style)
2689
+ return 1;
2690
+ }
2691
+ return -1;
2692
+ }
2693
+ var FontLoader = class {
2694
+ constructor(fontOptions) {
2695
+ this.fonts = /* @__PURE__ */ new Map();
2696
+ this.addFonts(fontOptions);
2697
+ }
2698
+ get({
2699
+ name,
2700
+ weight,
2701
+ style
2702
+ }) {
2703
+ if (!this.fonts.has(name)) {
2704
+ return null;
2705
+ }
2706
+ if (weight === "normal")
2707
+ weight = 400;
2708
+ if (weight === "bold")
2709
+ weight = 700;
2710
+ const fonts = [...this.fonts.get(name)];
2711
+ let matchedFont = fonts[0];
2712
+ for (let i2 = 1; i2 < fonts.length; i2++) {
2713
+ const [, weight1, style1] = matchedFont;
2714
+ const [, weight2, style2] = fonts[i2];
2715
+ if (compareFont(weight, style, [weight1, style1], [weight2, style2]) > 0) {
2716
+ matchedFont = fonts[i2];
2717
+ }
2718
+ }
2719
+ return matchedFont[0];
2720
+ }
2721
+ addFonts(fontOptions) {
2722
+ for (const fontOption of fontOptions) {
2723
+ const data = fontOption.data;
2724
+ const font = opentype.parse(
2725
+ "buffer" in data ? data.buffer.slice(
2726
+ data.byteOffset,
2727
+ data.byteOffset + data.byteLength
2728
+ ) : data,
2729
+ { lowMemory: true }
2730
+ );
2731
+ const originalCharToGlyphIndex = font.charToGlyphIndex;
2732
+ font.charToGlyphIndex = (char) => {
2733
+ const index = originalCharToGlyphIndex.call(font, char);
2734
+ if (index === 0) {
2735
+ if (font._trackBrokenChars) {
2736
+ ;
2737
+ font._trackBrokenChars.push(char);
2738
+ }
2739
+ }
2740
+ return index;
2741
+ };
2742
+ if (!this.defaultFont)
2743
+ this.defaultFont = font;
2744
+ const name = fontOption.name.toLowerCase();
2745
+ if (!this.fonts.has(name)) {
2746
+ this.fonts.set(name, []);
2747
+ }
2748
+ this.fonts.get(name).push([font, fontOption.weight, fontOption.style]);
2749
+ }
2750
+ }
2751
+ getEngine(fontSize = 16, lineHeight = 1.2, {
2752
+ fontFamily,
2753
+ fontWeight = 400,
2754
+ fontStyle = "normal"
2755
+ }) {
2756
+ fontFamily = Array.isArray(fontFamily) ? fontFamily : [fontFamily];
2757
+ const fonts = fontFamily.map(
2758
+ (face) => this.get({
2759
+ name: face,
2760
+ weight: fontWeight,
2761
+ style: fontStyle
2762
+ })
2763
+ ).filter(Boolean);
2764
+ const keys = Array.from(this.fonts.keys());
2765
+ for (const name of keys) {
2766
+ if (fontFamily.includes(name))
2767
+ continue;
2768
+ fonts.push(
2769
+ this.get({
2770
+ name,
2771
+ weight: fontWeight,
2772
+ style: fontStyle
2773
+ })
2774
+ );
2775
+ }
2776
+ const cachedFontResolver = /* @__PURE__ */ new Map();
2777
+ const resolveFont = (word, fallback = true) => {
2778
+ const code2 = word.charCodeAt(0);
2779
+ if (cachedFontResolver.has(code2))
2780
+ return cachedFontResolver.get(code2);
2781
+ const font = fonts.find((font2, index) => {
2782
+ return !!font2.charToGlyphIndex(word) || fallback && index === fonts.length - 1;
2783
+ });
2784
+ if (font) {
2785
+ cachedFontResolver.set(code2, font);
2786
+ }
2787
+ return font;
2788
+ };
2789
+ const ascender = (resolvedFont, useOS2Table = false) => {
2790
+ var _a, _b;
2791
+ const ascender2 = (useOS2Table ? (_b = (_a = resolvedFont.tables) == null ? void 0 : _a.os2) == null ? void 0 : _b.sTypoAscender : 0) || resolvedFont.ascender;
2792
+ return ascender2 / resolvedFont.unitsPerEm * fontSize;
2793
+ };
2794
+ const descender = (resolvedFont, useOS2Table = false) => {
2795
+ var _a, _b;
2796
+ const descender2 = (useOS2Table ? (_b = (_a = resolvedFont.tables) == null ? void 0 : _a.os2) == null ? void 0 : _b.sTypoDescender : 0) || resolvedFont.descender;
2797
+ return descender2 / resolvedFont.unitsPerEm * fontSize;
2798
+ };
2799
+ const resolve = (s2) => {
2800
+ return resolveFont(s2, false);
2801
+ };
2802
+ const engine = {
2803
+ check: (s2) => {
2804
+ const font = resolve(s2);
2805
+ if (!font)
2806
+ return false;
2807
+ font._trackBrokenChars = [];
2808
+ font.stringToGlyphs(s2);
2809
+ if (!font._trackBrokenChars.length)
2810
+ return true;
2811
+ font._trackBrokenChars = void 0;
2812
+ return false;
2813
+ },
2814
+ baseline: (s2, resolvedFont = typeof s2 === "undefined" ? fonts[0] : resolveFont(s2)) => {
2815
+ const A = ascender(resolvedFont, true);
2816
+ const D2 = descender(resolvedFont, true);
2817
+ const glyphHeight = engine.height(s2, resolvedFont);
2818
+ const { yMax, yMin } = resolvedFont.tables.head;
2819
+ const sGlyphHeight = A - D2;
2820
+ const baselineOffset = (yMax / (yMax - yMin) - 1) * sGlyphHeight;
2821
+ return glyphHeight * ((1.2 / lineHeight + 1) / 2) + baselineOffset;
2822
+ },
2823
+ height: (s2, resolvedFont = typeof s2 === "undefined" ? fonts[0] : resolveFont(s2)) => {
2824
+ return (ascender(resolvedFont) - descender(resolvedFont)) * (lineHeight / 1.2);
2825
+ },
2826
+ measure: (s2, style) => {
2827
+ return this.measure(resolveFont, s2, style);
2828
+ },
2829
+ getSVG: (s2, style) => {
2830
+ return this.getSVG(resolveFont, s2, style);
2831
+ }
2832
+ };
2833
+ return engine;
2834
+ }
2835
+ patchFontFallbackResolver(font, resolveFont) {
2836
+ const brokenChars = [];
2837
+ font._trackBrokenChars = brokenChars;
2838
+ const originalStringToGlyphs = font.stringToGlyphs;
2839
+ font.stringToGlyphs = (s2, ...args) => {
2840
+ const glyphs = originalStringToGlyphs.call(font, s2, ...args);
2841
+ for (let i2 = 0; i2 < glyphs.length; i2++) {
2842
+ if (glyphs[i2].unicode === void 0) {
2843
+ const char = brokenChars.shift();
2844
+ const anotherFont = resolveFont(char);
2845
+ if (anotherFont !== font) {
2846
+ glyphs[i2] = anotherFont.charToGlyph(char);
2847
+ }
2848
+ }
2849
+ }
2850
+ return glyphs;
2851
+ };
2852
+ return () => {
2853
+ font.stringToGlyphs = originalStringToGlyphs;
2854
+ font._trackBrokenChars = void 0;
2855
+ };
2856
+ }
2857
+ measure(resolveFont, content, {
2858
+ fontSize,
2859
+ letterSpacing = 0
2860
+ }) {
2861
+ const font = resolveFont(content);
2862
+ const unpatch = this.patchFontFallbackResolver(font, resolveFont);
2863
+ try {
2864
+ return font.getAdvanceWidth(content, fontSize, {
2865
+ letterSpacing: letterSpacing / fontSize
2866
+ });
2867
+ } finally {
2868
+ unpatch();
2869
+ }
2870
+ }
2871
+ getSVG(resolveFont, content, {
2872
+ fontSize,
2873
+ top,
2874
+ left,
2875
+ letterSpacing = 0
2876
+ }) {
2877
+ const font = resolveFont(content);
2878
+ const unpatch = this.patchFontFallbackResolver(font, resolveFont);
2879
+ try {
2880
+ return font.getPath(content, left, top, fontSize, {
2881
+ letterSpacing: letterSpacing / fontSize
2882
+ }).toPathData(1);
2883
+ } finally {
2884
+ unpatch();
2885
+ }
2886
+ }
2887
+ };
2888
+
2889
+ // src/builder/svg.ts
2890
+ function svg({
2891
+ width,
2892
+ height,
2893
+ content
2894
+ }) {
2895
+ return buildXMLString(
2896
+ "svg",
2897
+ {
2898
+ width,
2899
+ height,
2900
+ viewBox: `0 0 ${width} ${height}`,
2901
+ xmlns: "http://www.w3.org/2000/svg"
2902
+ },
2903
+ content
2904
+ );
2905
+ }
2906
+
2907
+ // src/language.ts
2908
+ var code = {
2909
+ emoji: /\p{RI}\p{RI}|\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?(\u{200D}\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?)+|\p{EPres}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})?|\p{Emoji}(\p{EMod}+|\u{FE0F}\u{20E3}?|[\u{E0020}-\u{E007E}]+\u{E007F})/u,
2910
+ ja: /\p{scx=Hira}|\p{scx=Kana}|[,;:]/u,
2911
+ ko: /\p{scx=Hangul}/u,
2912
+ zh: /\p{scx=Han}/u,
2913
+ th: /\p{scx=Thai}/u,
2914
+ bn: /\p{scx=Bengali}/u,
2915
+ ar: /\p{scx=Arabic}/u,
2916
+ ta: /\p{scx=Tamil}/u,
2917
+ ml: /\p{scx=Malayalam}/u,
2918
+ he: /\p{scx=Hebrew}/u,
2919
+ te: /\p{scx=Telugu}/u,
2920
+ devanagari: /\p{scx=Devanagari}/u
2921
+ };
2922
+ function detectLanguageCode(segment2) {
2923
+ for (const c2 in code) {
2924
+ if (code[c2].test(segment2)) {
2925
+ return c2;
2926
+ }
2927
+ }
2928
+ return "unknown";
2929
+ }
2930
+
2931
+ // src/satori.ts
2932
+ var fontCache = /* @__PURE__ */ new WeakMap();
2933
+ async function satori(element, options) {
2934
+ const Yoga3 = getYoga();
2935
+ if (!Yoga3)
2936
+ throw new Error("Satori is not initialized.");
2937
+ let font;
2938
+ if (fontCache.has(options.fonts)) {
2939
+ font = fontCache.get(options.fonts);
2940
+ } else {
2941
+ fontCache.set(options.fonts, font = new FontLoader(options.fonts));
2942
+ }
2943
+ const root = Yoga3.Node.create();
2944
+ root.setWidth(options.width);
2945
+ root.setHeight(options.height);
2946
+ root.setFlexDirection(Yoga3.FLEX_DIRECTION_ROW);
2947
+ root.setFlexWrap(Yoga3.WRAP_WRAP);
2948
+ root.setAlignContent(Yoga3.ALIGN_AUTO);
2949
+ root.setAlignItems(Yoga3.ALIGN_FLEX_START);
2950
+ root.setJustifyContent(Yoga3.JUSTIFY_FLEX_START);
2951
+ root.setOverflow(Yoga3.OVERFLOW_HIDDEN);
2952
+ const graphemeImages = { ...options.graphemeImages };
2953
+ const handler2 = layout(element, {
2954
+ id: "id",
2955
+ parentStyle: {},
2956
+ inheritedStyle: {
2957
+ fontSize: 16,
2958
+ fontWeight: "normal",
2959
+ fontFamily: "serif",
2960
+ fontStyle: "normal",
2961
+ lineHeight: 1.2,
2962
+ color: "black",
2963
+ opacity: 1,
2964
+ whiteSpace: "normal",
2965
+ _viewportWidth: options.width,
2966
+ _viewportHeight: options.height
2967
+ },
2968
+ parent: root,
2969
+ font,
2970
+ embedFont: options.embedFont,
2971
+ debug: options.debug,
2972
+ graphemeImages,
2973
+ canLoadAdditionalAssets: !!options.loadAdditionalAsset
2974
+ });
2975
+ let segmentsMissingFont = (await handler2.next()).value;
2976
+ if (options.loadAdditionalAsset) {
2977
+ if (segmentsMissingFont.length) {
2978
+ segmentsMissingFont = Array.from(
2979
+ new Set(segment(segmentsMissingFont.join(""), "grapheme"))
2980
+ );
2981
+ const languageCodes = {};
2982
+ segmentsMissingFont.forEach((seg) => {
2983
+ const code2 = detectLanguageCode(seg);
2984
+ languageCodes[code2] = languageCodes[code2] || [];
2985
+ if (code2 === "emoji") {
2986
+ languageCodes[code2].push(seg);
2987
+ } else {
2988
+ languageCodes[code2][0] = (languageCodes[code2][0] || "") + seg;
2989
+ }
2990
+ });
2991
+ const fonts = [];
2992
+ const images = {};
2993
+ await Promise.all(
2994
+ Object.entries(languageCodes).flatMap(
2995
+ ([code2, segments]) => segments.map(
2996
+ (segment2) => options.loadAdditionalAsset(code2, segment2).then((asset) => {
2997
+ if (typeof asset === "string") {
2998
+ images[segment2] = asset;
2999
+ } else if (asset) {
3000
+ fonts.push(asset);
3001
+ }
3002
+ })
3003
+ )
3004
+ )
3005
+ );
3006
+ font.addFonts(fonts);
3007
+ Object.assign(graphemeImages, images);
3008
+ }
3009
+ }
3010
+ await handler2.next();
3011
+ root.calculateLayout(options.width, options.height, Yoga3.DIRECTION_LTR);
3012
+ const content = (await handler2.next([0, 0])).value;
3013
+ root.freeRecursive();
3014
+ return svg({ width: options.width, height: options.height, content });
3015
+ }
3016
+ export {
3017
+ satori as default,
3018
+ init
3019
+ };
5
3020
  //# sourceMappingURL=index.js.map