velloo 0.5.0 → 0.7.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.
Files changed (161) hide show
  1. package/README.md +116 -227
  2. package/THIRD-PARTY-NOTICES.md +3 -3
  3. package/canvas/assets/index-BQ5710lu.js +29 -0
  4. package/canvas/assets/index-GNLd0pCG.css +2 -0
  5. package/canvas/assets/lucide-all-DIRZdJPK.js +1 -0
  6. package/canvas/index.html +2 -2
  7. package/{chunk-qpv28z8d.js → chunk-0e5j6nqs.js} +1 -1
  8. package/{chunk-vrvkvb0v.js → chunk-0pxm5v0b.js} +3 -3
  9. package/{chunk-a16mz9zf.js → chunk-0vaff40g.js} +1 -1
  10. package/{chunk-42bj6r30.js → chunk-3m28pvzr.js} +1 -1
  11. package/{chunk-33t0csxs.js → chunk-4y2xy1kf.js} +2 -2
  12. package/{chunk-d4r0myxr.js → chunk-531xzfq5.js} +1 -1
  13. package/{chunk-1h3gqy7w.js → chunk-5s1wjhtj.js} +1 -1
  14. package/{chunk-4pkw6d9n.js → chunk-5x4nw0zz.js} +5 -5
  15. package/{chunk-b3x80jc1.js → chunk-5yhnnhkd.js} +1 -1
  16. package/{chunk-675tr675.js → chunk-64pex3mw.js} +1 -1
  17. package/chunk-667ag8ts.js +2 -0
  18. package/chunk-7gyzh0vq.js +5 -0
  19. package/{chunk-4sjvdakg.js → chunk-82x2jkfq.js} +1 -1
  20. package/{chunk-5y9hem1j.js → chunk-84n18xgx.js} +257 -3
  21. package/{chunk-edgwx026.js → chunk-abr2hgay.js} +1 -1
  22. package/{chunk-cqt1dpxd.js → chunk-acsv6m3n.js} +1 -1
  23. package/{chunk-j7tzbt3d.js → chunk-asfgvzse.js} +1 -1
  24. package/{chunk-0wqxb8r9.js → chunk-b8vcbbrg.js} +1 -1
  25. package/chunk-bms1sg4c.js +2 -0
  26. package/chunk-brnkprt5.js +723 -0
  27. package/{chunk-afe25dpr.js → chunk-bys7pqdb.js} +1 -1
  28. package/chunk-d0j8dg1e.js +3 -0
  29. package/chunk-d93kpv7s.js +12 -0
  30. package/chunk-dvh0b2r4.js +3 -0
  31. package/{chunk-5ma8zbty.js → chunk-eh2xp4v6.js} +1 -1
  32. package/{chunk-z78c1kf8.js → chunk-ejppcfa5.js} +1 -1
  33. package/{chunk-ngbqd7kb.js → chunk-ex36z3b3.js} +317 -119
  34. package/{chunk-6ytv1v2r.js → chunk-fmcm06xb.js} +1 -1
  35. package/{chunk-3ffs39e8.js → chunk-fvezyap4.js} +1 -1
  36. package/chunk-g7d065ek.js +2 -0
  37. package/{chunk-tw4kw4ps.js → chunk-g8xrwjvq.js} +2 -2
  38. package/{chunk-df557bn4.js → chunk-gbq5wv7x.js} +1 -1
  39. package/chunk-gcce587w.js +3 -0
  40. package/{chunk-cdqah1hy.js → chunk-gfppsgvv.js} +1 -1
  41. package/{chunk-5f0xv80x.js → chunk-j306gr0c.js} +1 -1
  42. package/chunk-j4fn2a2b.js +2 -0
  43. package/chunk-jbgde2v9.js +2 -0
  44. package/{chunk-wkqrb2tz.js → chunk-kkvf0xk2.js} +1 -1
  45. package/{chunk-d9kx7v12.js → chunk-md4mpvqc.js} +1 -1
  46. package/{chunk-vryadew3.js → chunk-mdgwdqnq.js} +2 -2
  47. package/chunk-p93x4pn2.js +3 -0
  48. package/chunk-pjkkp7xa.js +2 -0
  49. package/chunk-qp3wahg4.js +2 -0
  50. package/{chunk-f45p6kcb.js → chunk-qqrac4va.js} +1 -1
  51. package/chunk-qrnkrkkt.js +2 -0
  52. package/chunk-rqd4swxx.js +2 -0
  53. package/{chunk-xzkczmgg.js → chunk-rxkvjyst.js} +1 -1
  54. package/chunk-s84vxcdv.js +4 -0
  55. package/chunk-sjjnm4a1.js +2 -0
  56. package/chunk-skk6yvnw.js +3 -0
  57. package/{chunk-ahm4zd56.js → chunk-sme6hv6f.js} +1 -1
  58. package/chunk-snak5zpr.js +5 -0
  59. package/{chunk-gn9wcc1b.js → chunk-srp5gyr1.js} +1 -1
  60. package/{chunk-rd65xm6r.js → chunk-vdbr81a3.js} +1 -1
  61. package/chunk-vs8j3x6t.js +3 -0
  62. package/{chunk-hr3gbak5.js → chunk-xg71h7nb.js} +1 -1
  63. package/chunk-xzf52wvn.js +6 -0
  64. package/chunk-ykpctq15.js +6 -0
  65. package/chunk-zv17t1n7.js +3 -0
  66. package/cli.js +1 -1
  67. package/launcher.cjs +3 -1
  68. package/package.json +1 -1
  69. package/pkgs/helpers/src/box.tsx +12 -6
  70. package/pkgs/helpers/src/descriptors.ts +7 -0
  71. package/pkgs/helpers/src/icon.tsx +5 -3
  72. package/pkgs/helpers/src/index.ts +9 -6
  73. package/pkgs/helpers/src/lowering.ts +0 -24
  74. package/pkgs/helpers/src/primitive-classes.tsx +43 -0
  75. package/pkgs/helpers/src/text.tsx +29 -5
  76. package/pkgs/provider-antd/src/intro.ts +3 -3
  77. package/pkgs/provider-antd/src/manifest.ts +479 -57
  78. package/pkgs/provider-antd/src/registry.ts +8 -5
  79. package/pkgs/provider-antd/src/render-pass.ts +10 -4
  80. package/pkgs/provider-antd/src/reset-css.d.ts +5 -0
  81. package/pkgs/provider-antd/src/theme.ts +54 -11
  82. package/pkgs/provider-chakra/src/manifest.ts +6 -1
  83. package/pkgs/provider-mui/src/index.ts +4 -2
  84. package/pkgs/provider-mui/src/manifest.ts +11 -1
  85. package/pkgs/provider-mui/src/render-pass.ts +15 -1
  86. package/pkgs/provider-mui/src/theme.ts +10 -4
  87. package/pkgs/provider-none/src/components-inline.tsx +20 -14
  88. package/pkgs/provider-none/src/components.tsx +17 -54
  89. package/pkgs/provider-none/src/manifest.ts +1 -0
  90. package/pkgs/schema/src/annotation.ts +6 -3
  91. package/pkgs/schema/src/comment.ts +10 -1
  92. package/pkgs/schema/src/config.ts +4 -1
  93. package/pkgs/schema/src/index.ts +16 -1
  94. package/pkgs/schema/src/node-identity.ts +97 -0
  95. package/pkgs/schema/src/node.ts +49 -23
  96. package/pkgs/schema/src/snippet-resolve.ts +18 -12
  97. package/pkgs/schema/src/svg-sanitize.ts +3 -0
  98. package/pkgs/schema/src/theme.ts +6 -1
  99. package/pkgs/schema/src/typeset.ts +45 -21
  100. package/pkgs/shadcn-snapshot/dist/manifest.json +7 -0
  101. package/pkgs/shadcn-snapshot/src/components/ui/alert.tsx +2 -4
  102. package/pkgs/shadcn-snapshot/src/components/ui/aspect-ratio.tsx +2 -3
  103. package/pkgs/shadcn-snapshot/src/components/ui/attachment.tsx +3 -4
  104. package/pkgs/shadcn-snapshot/src/components/ui/avatar.tsx +2 -4
  105. package/pkgs/shadcn-snapshot/src/components/ui/badge.tsx +2 -4
  106. package/pkgs/shadcn-snapshot/src/components/ui/breadcrumb.tsx +2 -4
  107. package/pkgs/shadcn-snapshot/src/components/ui/bubble.tsx +2 -4
  108. package/pkgs/shadcn-snapshot/src/components/ui/button-group.tsx +3 -4
  109. package/pkgs/shadcn-snapshot/src/components/ui/button.tsx +2 -4
  110. package/pkgs/shadcn-snapshot/src/components/ui/card.tsx +2 -4
  111. package/pkgs/shadcn-snapshot/src/components/ui/carousel.tsx +3 -4
  112. package/pkgs/shadcn-snapshot/src/components/ui/chart.tsx +1 -1
  113. package/pkgs/shadcn-snapshot/src/components/ui/direction.tsx +2 -3
  114. package/pkgs/shadcn-snapshot/src/components/ui/empty.tsx +2 -4
  115. package/pkgs/shadcn-snapshot/src/components/ui/field.tsx +3 -4
  116. package/pkgs/shadcn-snapshot/src/components/ui/input-group.tsx +3 -4
  117. package/pkgs/shadcn-snapshot/src/components/ui/item.tsx +3 -4
  118. package/pkgs/shadcn-snapshot/src/components/ui/kbd.tsx +2 -3
  119. package/pkgs/shadcn-snapshot/src/components/ui/label.tsx +2 -4
  120. package/pkgs/shadcn-snapshot/src/components/ui/marker.tsx +2 -4
  121. package/pkgs/shadcn-snapshot/src/components/ui/message.tsx +2 -4
  122. package/pkgs/shadcn-snapshot/src/components/ui/native-select.tsx +2 -4
  123. package/pkgs/shadcn-snapshot/src/components/ui/navigation-menu.tsx +2 -4
  124. package/pkgs/shadcn-snapshot/src/components/ui/pagination.tsx +3 -4
  125. package/pkgs/shadcn-snapshot/src/components/ui/progress.tsx +2 -4
  126. package/pkgs/shadcn-snapshot/src/components/ui/radio-group.tsx +2 -4
  127. package/pkgs/shadcn-snapshot/src/components/ui/scroll-area.tsx +2 -4
  128. package/pkgs/shadcn-snapshot/src/components/ui/separator.tsx +2 -4
  129. package/pkgs/shadcn-snapshot/src/components/ui/skeleton.tsx +2 -3
  130. package/pkgs/shadcn-snapshot/src/components/ui/spinner.tsx +2 -3
  131. package/pkgs/shadcn-snapshot/src/components/ui/table.tsx +2 -4
  132. package/pkgs/shadcn-snapshot/src/components/ui/tabs.tsx +2 -4
  133. package/pkgs/shadcn-snapshot/src/components/ui/toggle.tsx +2 -4
  134. package/pkgs/shadcn-snapshot/src/shadcn-tailwind.css +1 -1
  135. package/pkgs/shadcn-snapshot/src/tailwind-entry.css +1 -1
  136. package/canvas/assets/index-BDBBHdHH.css +0 -2
  137. package/canvas/assets/index-QdsLJNY9.js +0 -29
  138. package/canvas/assets/lucide-all-R8DUyY-B.js +0 -1
  139. package/chunk-0rdf6trc.js +0 -2
  140. package/chunk-0wafc9aw.js +0 -4
  141. package/chunk-10hap8kc.js +0 -6
  142. package/chunk-18eqh3s1.js +0 -2
  143. package/chunk-19xyzep8.js +0 -2
  144. package/chunk-49w26e94.js +0 -5
  145. package/chunk-66qgm91k.js +0 -708
  146. package/chunk-6cgvzwec.js +0 -3
  147. package/chunk-75sc3adm.js +0 -2
  148. package/chunk-7cexzg71.js +0 -2
  149. package/chunk-98rann8t.js +0 -2
  150. package/chunk-asvdqkdp.js +0 -6
  151. package/chunk-emv1j50t.js +0 -2
  152. package/chunk-ewgdcgrk.js +0 -2
  153. package/chunk-mm8wv3bg.js +0 -3
  154. package/chunk-nkqtnwzz.js +0 -2
  155. package/chunk-q3kf8243.js +0 -3
  156. package/chunk-ryga3ny1.js +0 -3
  157. package/chunk-sb5h27w9.js +0 -3
  158. package/chunk-vgx47anc.js +0 -3
  159. package/chunk-w6f40y2x.js +0 -11
  160. package/chunk-we8hvy6e.js +0 -2
  161. package/chunk-ycrddh47.js +0 -5
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{isCssIdent,sanitizeCssTokenValue,neutralizeCssText,sanitizeGoogleFontSpec,isComponentNode,isSnippetInstance,isParamRef,isRepoNode,repoKey,ScreenSchema,resolveSnippetArgs,substituteSnippetParams,applySnippetOverrides,applySnippetExtraClassName,spacingCssTokens,ThemeSchema,typesetCss}from"./chunk-4pkw6d9n.js";import{__toESM,__commonJS,__exportCjs,__require}from"./chunk-2smsg2ct.js";var require_chunkstream=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),ChunkStream=module.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};util.inherits(ChunkStream,Stream);ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};ChunkStream.prototype.write=function(data,encoding){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let dataBuffer;if(Buffer.isBuffer(data))dataBuffer=data;else dataBuffer=Buffer.from(data,encoding||this._encoding);if(this._buffers.push(dataBuffer),this._buffered+=dataBuffer.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};ChunkStream.prototype.end=function(data,encoding){if(data)this.write(data,encoding);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};ChunkStream.prototype.destroySoon=ChunkStream.prototype.end;ChunkStream.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};ChunkStream.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();let smallerBuf=this._buffers[0];if(smallerBuf.length>read.length)this._buffered-=read.length,this._buffers[0]=smallerBuf.slice(read.length),read.func.call(this,smallerBuf.slice(0,read.length));else this._buffered-=smallerBuf.length,this._buffers.shift(),read.func.call(this,smallerBuf)};ChunkStream.prototype._processRead=function(read){this._reads.shift();let pos=0,count=0,data=Buffer.alloc(read.length);while(pos<read.length){let buf=this._buffers[count++],len=Math.min(buf.length,read.length-pos);if(buf.copy(data,pos,0,len),pos+=len,len!==buf.length)this._buffers[--count]=buf.slice(len)}if(count>0)this._buffers.splice(0,count);this._buffered-=read.length,read.func.call(this,data)};ChunkStream.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let read=this._reads[0];if(read.allowLess)this._processReadAllowingLess(read);else if(this._buffered>=read.length)this._processRead(read);else break}if(this._buffers&&!this.writable)this._end()}catch(ex){this.emit("error",ex)}}});var require_interlace=__commonJS(function(exports){var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(width,height){let images=[],xLeftOver=width%8,yLeftOver=height%8,xRepeats=(width-xLeftOver)/8,yRepeats=(height-yLeftOver)/8;for(let i=0;i<imagePasses.length;i++){let pass=imagePasses[i],passWidth=xRepeats*pass.x.length,passHeight=yRepeats*pass.y.length;for(let j=0;j<pass.x.length;j++)if(pass.x[j]<xLeftOver)passWidth++;else break;for(let j=0;j<pass.y.length;j++)if(pass.y[j]<yLeftOver)passHeight++;else break;if(passWidth>0&&passHeight>0)images.push({width:passWidth,height:passHeight,index:i})}return images};exports.getInterlaceIterator=function(width){return function(x,y,pass){let outerXLeftOver=x%imagePasses[pass].x.length,outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver],outerYLeftOver=y%imagePasses[pass].y.length,outerY=(y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver];return outerX*4+outerY*width*4}}});var require_paeth_predictor=__commonJS(function(exports,module){module.exports=function(left,above,upLeft){let paeth=left+above-upLeft,pLeft=Math.abs(paeth-left),pAbove=Math.abs(paeth-above),pUpLeft=Math.abs(paeth-upLeft);if(pLeft<=pAbove&&pLeft<=pUpLeft)return left;if(pAbove<=pUpLeft)return above;return upLeft}});var require_filter_parse=__commonJS(function(exports,module){var interlaceUtils=require_interlace(),paethPredictor=require_paeth_predictor();function getByteWidth(width,bpp,depth){let byteWidth=width*bpp;if(depth!==8)byteWidth=Math.ceil(byteWidth/(8/depth));return byteWidth}var Filter=module.exports=function(bitmapInfo,dependencies){let{width,height,interlace,bpp,depth}=bitmapInfo;if(this.read=dependencies.read,this.write=dependencies.write,this.complete=dependencies.complete,this._imageIndex=0,this._images=[],interlace){let passes=interlaceUtils.getImagePasses(width,height);for(let i=0;i<passes.length;i++)this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}else this._images.push({byteWidth:getByteWidth(width,bpp,depth),height,lineIndex:0});if(depth===8)this._xComparison=bpp;else if(depth===16)this._xComparison=bpp*2;else this._xComparison=1};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}};Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){let lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}};Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f3Up=lastLine?lastLine[x]:0,f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}};Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f4Up=lastLine?lastLine[x]:0,f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0,f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}};Filter.prototype._reverseFilterLine=function(rawData){let filter=rawData[0],unfilteredLine,currentImage=this._images[this._imageIndex],byteWidth=currentImage.byteWidth;if(filter===0)unfilteredLine=rawData.slice(1,byteWidth+1);else switch(unfilteredLine=Buffer.alloc(byteWidth),filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw Error("Unrecognised filter type - "+filter)}if(this.write(unfilteredLine),currentImage.lineIndex++,currentImage.lineIndex>=currentImage.height)this._lastLine=null,this._imageIndex++,currentImage=this._images[this._imageIndex];else this._lastLine=unfilteredLine;if(currentImage)this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var require_filter_parse_async=__commonJS(function(exports,module){var util=__require("util"),ChunkStream=require_chunkstream(),Filter=require_filter_parse(),FilterAsync=module.exports=function(bitmapInfo){ChunkStream.call(this);let buffers=[],that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}}),this._filter.start()};util.inherits(FilterAsync,ChunkStream)});var require_constants=__commonJS(function(exports,module){module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var require_crc=__commonJS(function(exports,module){var crcTable=[];(function(){for(let i=0;i<256;i++){let currentCrc=i;for(let j=0;j<8;j++)if(currentCrc&1)currentCrc=3988292384^currentCrc>>>1;else currentCrc=currentCrc>>>1;crcTable[i]=currentCrc}})();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(data){for(let i=0;i<data.length;i++)this._crc=crcTable[(this._crc^data[i])&255]^this._crc>>>8;return!0};CrcCalculator.prototype.crc32=function(){return this._crc^-1};CrcCalculator.crc32=function(buf){let crc=-1;for(let i=0;i<buf.length;i++)crc=crcTable[(crc^buf[i])&255]^crc>>>8;return crc^-1}});var require_parser=__commonJS(function(exports,module){var constants=require_constants(),CrcCalculator=require_crc(),Parser=module.exports=function(options,dependencies){this._options=options,options.checkCRC=options.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=dependencies.read,this.error=dependencies.error,this.metadata=dependencies.metadata,this.gamma=dependencies.gamma,this.transColor=dependencies.transColor,this.palette=dependencies.palette,this.parsed=dependencies.parsed,this.inflateData=dependencies.inflateData,this.finished=dependencies.finished,this.simpleTransparency=dependencies.simpleTransparency,this.headersFinished=dependencies.headersFinished||function(){}};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Parser.prototype._parseSignature=function(data){let signature=constants.PNG_SIGNATURE;for(let i=0;i<signature.length;i++)if(data[i]!==signature[i]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._parseChunkBegin=function(data){let length=data.readUInt32BE(0),type=data.readUInt32BE(4),name="";for(let i=4;i<8;i++)name+=String.fromCharCode(data[i]);let ancillary=Boolean(data[4]&32);if(!this._hasIHDR&&type!==constants.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new CrcCalculator,this._crc.write(Buffer.from(name)),this._chunks[type])return this._chunks[type](length);if(!ancillary){this.error(Error("Unsupported critical chunk type "+name));return}this.read(length+4,this._skipChunk.bind(this))};Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Parser.prototype._parseChunkEnd=function(data){let fileCrc=data.readInt32BE(0),calcCrc=this._crc.crc32();if(this._options.checkCRC&&calcCrc!==fileCrc){this.error(Error("Crc error - "+fileCrc+" - "+calcCrc));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))};Parser.prototype._parseIHDR=function(data){this._crc.write(data);let width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],colorType=data[9],compr=data[10],filter=data[11],interlace=data[12];if(depth!==8&&depth!==4&&depth!==2&&depth!==1&&depth!==16){this.error(Error("Unsupported bit depth "+depth));return}if(!(colorType in constants.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(compr!==0){this.error(Error("Unsupported compression method"));return}if(filter!==0){this.error(Error("Unsupported filter method"));return}if(interlace!==0&&interlace!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=colorType;let bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width,height,depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp,colorType}),this._handleChunkEnd()};Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))};Parser.prototype._parsePLTE=function(data){this._crc.write(data);let entries=Math.floor(data.length/3);for(let i=0;i<entries;i++)this._palette.push([data[i*3],data[i*3+1],data[i*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Parser.prototype._handleTRNS=function(length){this.simpleTransparency(),this.read(length,this._parseTRNS.bind(this))};Parser.prototype._parseTRNS=function(data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(data.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let i=0;i<data.length;i++)this._palette[i][3]=data[i];this.palette(this._palette)}if(this._colorType===constants.COLORTYPE_GRAYSCALE)this.transColor([data.readUInt16BE(0)]);if(this._colorType===constants.COLORTYPE_COLOR)this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)]);this._handleChunkEnd()};Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))};Parser.prototype._parseGAMA=function(data){this._crc.write(data),this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()};Parser.prototype._handleIDAT=function(length){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-length,this._parseIDAT.bind(this,length))};Parser.prototype._parseIDAT=function(length,data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(data);let leftOverLength=length-data.length;if(leftOverLength>0)this._handleIDAT(leftOverLength);else this._handleChunkEnd()};Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))};Parser.prototype._parseIEND=function(data){if(this._crc.write(data),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var require_bitmapper=__commonJS(function(exports){var interlaceUtils=require_interlace(),pixelBppMapper=[function(){},function(pxData,data,pxPos,rawPos){if(rawPos===data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+1>=data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=data[rawPos+1]},function(pxData,data,pxPos,rawPos){if(rawPos+2>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+3>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=data[rawPos+3]}],pixelBppCustomMapper=[function(){},function(pxData,pixelData,pxPos,maxBit){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=pixelData[1]},function(pxData,pixelData,pxPos,maxBit){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=pixelData[3]}];function bitRetriever(data,depth){let leftOver=[],i=0;function split(){if(i===data.length)throw Error("Ran out of data");let byte=data[i];i++;let byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1;switch(depth){default:throw Error("unrecognised depth");case 16:byte2=data[i],i++,leftOver.push((byte<<8)+byte2);break;case 4:byte2=byte&15,byte1=byte>>4,leftOver.push(byte1,byte2);break;case 2:byte4=byte&3,byte3=byte>>2&3,byte2=byte>>4&3,byte1=byte>>6&3,leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=byte&1,byte7=byte>>1&1,byte6=byte>>2&1,byte5=byte>>3&1,byte4=byte>>4&1,byte3=byte>>5&1,byte2=byte>>6&1,byte1=byte>>7&1,leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8);break}}return{get:function(count){while(leftOver.length<count)split();let returner=leftOver.slice(0,count);return leftOver=leftOver.slice(count),returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length)throw Error("extra data found")}}}function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++)for(let x=0;x<imageWidth;x++){let pxPos=getPxPos(x,y,imagePass);pixelBppMapper[bpp](pxData,data,pxPos,rawPos),rawPos+=bpp}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++){for(let x=0;x<imageWidth;x++){let pixelData=bits.get(bpp),pxPos=getPxPos(x,y,imagePass);pixelBppCustomMapper[bpp](pxData,pixelData,pxPos,maxBit)}bits.resetAfterLine()}}exports.dataToBitMap=function(data,bitmapInfo){let{width,height,depth,bpp,interlace}=bitmapInfo,bits;if(depth!==8)bits=bitRetriever(data,depth);let pxData;if(depth<=8)pxData=Buffer.alloc(width*height*4);else pxData=new Uint16Array(width*height*4);let maxBit=Math.pow(2,depth)-1,rawPos=0,images,getPxPos;if(interlace)images=interlaceUtils.getImagePasses(width,height),getPxPos=interlaceUtils.getInterlaceIterator(width,height);else{let nonInterlacedPxPos=0;getPxPos=function(){let returner=nonInterlacedPxPos;return nonInterlacedPxPos+=4,returner},images=[{width,height}]}for(let imageIndex=0;imageIndex<images.length;imageIndex++)if(depth===8)rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos);else mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit);if(depth===8){if(rawPos!==data.length)throw Error("extra data found")}else bits.end();return pxData}});var require_format_normaliser=__commonJS(function(exports,module){function dePalette(indata,outdata,width,height,palette){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let color=palette[indata[pxPos]];if(!color)throw Error("index "+indata[pxPos]+" not in palette");for(let i=0;i<4;i++)outdata[pxPos+i]=color[i];pxPos+=4}}function replaceTransparentColor(indata,outdata,width,height,transColor){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let makeTrans=!1;if(transColor.length===1){if(transColor[0]===indata[pxPos])makeTrans=!0}else if(transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2])makeTrans=!0;if(makeTrans)for(let i=0;i<4;i++)outdata[pxPos+i]=0;pxPos+=4}}function scaleDepth(indata,outdata,width,height,depth){let maxOutSample=255,maxInSample=Math.pow(2,depth)-1,pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){for(let i=0;i<4;i++)outdata[pxPos+i]=Math.floor(indata[pxPos+i]*maxOutSample/maxInSample+0.5);pxPos+=4}}module.exports=function(indata,imageData,skipRescale=!1){let{depth,width,height,colorType,transColor,palette}=imageData,outdata=indata;if(colorType===3)dePalette(indata,outdata,width,height,palette);else{if(transColor)replaceTransparentColor(indata,outdata,width,height,transColor);if(depth!==8&&!skipRescale){if(depth===16)outdata=Buffer.alloc(width*height*4);scaleDepth(indata,outdata,width,height,depth)}}return outdata}});var require_parser_async=__commonJS(function(exports,module){var util=__require("util"),zlib=__require("zlib"),ChunkStream=require_chunkstream(),FilterAsync=require_filter_parse_async(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser(),ParserAsync=module.exports=function(options){ChunkStream.call(this),this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=options,this.writable=!0,this._parser.start()};util.inherits(ParserAsync,ChunkStream);ParserAsync.prototype._handleError=function(err){if(this.emit("error",err),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ParserAsync.prototype._inflateData=function(data){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let imageSize=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,chunkSize=Math.max(imageSize,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize});let leftToInflate=imageSize,emitError=this.emit.bind(this,"error");this._inflate.on("error",function(err){if(!leftToInflate)return;emitError(err)}),this._filter.on("complete",this._complete.bind(this));let filterWrite=this._filter.write.bind(this._filter);this._inflate.on("data",function(chunk){if(!leftToInflate)return;if(chunk.length>leftToInflate)chunk=chunk.slice(0,leftToInflate);leftToInflate-=chunk.length,filterWrite(chunk)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(data)};ParserAsync.prototype._handleMetaData=function(metaData){this._metaData=metaData,this._bitmapInfo=Object.create(metaData),this._filter=new FilterAsync(this._bitmapInfo)};ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor};ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette};ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ParserAsync.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ParserAsync.prototype._complete=function(filteredData){if(this.errord)return;let normalisedBitmapData;try{let bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo,this._options.skipRescale),bitmapData=null}catch(ex){this._handleError(ex);return}this.emit("parsed",normalisedBitmapData)}});var require_bitpacker=__commonJS(function(exports,module){var constants=require_constants();module.exports=function(dataIn,width,height,options){let outHasAlpha=[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)!==-1;if(options.colorType===options.inputColorType){let bigEndian=function(){let buffer=new ArrayBuffer(2);return new DataView(buffer).setInt16(0,256,!0),new Int16Array(buffer)[0]!==256}();if(options.bitDepth===8||options.bitDepth===16&&bigEndian)return dataIn}let data=options.bitDepth!==16?dataIn:new Uint16Array(dataIn.buffer),maxValue=255,inBpp=constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];if(inBpp===4&&!options.inputHasAlpha)inBpp=3;let outBpp=constants.COLORTYPE_TO_BPP_MAP[options.colorType];if(options.bitDepth===16)maxValue=65535,outBpp*=2;let outData=Buffer.alloc(width*height*outBpp),inIndex=0,outIndex=0,bgColor=options.bgColor||{};if(bgColor.red===void 0)bgColor.red=maxValue;if(bgColor.green===void 0)bgColor.green=maxValue;if(bgColor.blue===void 0)bgColor.blue=maxValue;function getRGBA(){let red,green,blue,alpha=maxValue;switch(options.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:alpha=data[inIndex+3],red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_COLOR:red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_ALPHA:alpha=data[inIndex+1],red=data[inIndex],green=red,blue=red;break;case constants.COLORTYPE_GRAYSCALE:red=data[inIndex],green=red,blue=red;break;default:throw Error("input color type:"+options.inputColorType+" is not supported at present")}if(options.inputHasAlpha){if(!outHasAlpha)alpha/=maxValue,red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),maxValue),green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),maxValue),blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),maxValue)}return{red,green,blue,alpha}}for(let y=0;y<height;y++)for(let x=0;x<width;x++){let rgba=getRGBA(data,inIndex);switch(options.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:if(options.bitDepth===8){if(outData[outIndex]=rgba.red,outData[outIndex+1]=rgba.green,outData[outIndex+2]=rgba.blue,outHasAlpha)outData[outIndex+3]=rgba.alpha}else if(outData.writeUInt16BE(rgba.red,outIndex),outData.writeUInt16BE(rgba.green,outIndex+2),outData.writeUInt16BE(rgba.blue,outIndex+4),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+6);break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:{let grayscale=(rgba.red+rgba.green+rgba.blue)/3;if(options.bitDepth===8){if(outData[outIndex]=grayscale,outHasAlpha)outData[outIndex+1]=rgba.alpha}else if(outData.writeUInt16BE(grayscale,outIndex),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+2);break}default:throw Error("unrecognised color Type "+options.colorType)}inIndex+=inBpp,outIndex+=outBpp}return outData}});var require_filter_pack=__commonJS(function(exports,module){var paethPredictor=require_paeth_predictor();function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++)rawData[rawPos+x]=pxData[pxPos+x]}function filterSumNone(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let i=pxPos;i<length;i++)sum+=Math.abs(pxData[i]);return sum}function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}}function filterSumSub(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum}function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++){let up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}}function filterSumUp(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let x=pxPos;x<length;x++){let up=pxPos>0?pxData[x-byteWidth]:0,val=pxData[x]-up;sum+=Math.abs(val)}return sum}function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}}function filterSumAvg(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum}function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}function filterSumPaeth(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth},filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(pxData,width,height,options,bpp){let filterTypes;if(!("filterType"in options)||options.filterType===-1)filterTypes=[0,1,2,3,4];else if(typeof options.filterType==="number")filterTypes=[options.filterType];else throw Error("unrecognised filter types");if(options.bitDepth===16)bpp*=2;let byteWidth=width*bpp,rawPos=0,pxPos=0,rawData=Buffer.alloc((byteWidth+1)*height),sel=filterTypes[0];for(let y=0;y<height;y++){if(filterTypes.length>1){let min=1/0;for(let i=0;i<filterTypes.length;i++){let sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);if(sum<min)sel=filterTypes[i],min=sum}}rawData[rawPos]=sel,rawPos++,filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp),rawPos+=byteWidth,pxPos+=byteWidth}return rawData}});var require_packer=__commonJS(function(exports,module){var constants=require_constants(),CrcStream=require_crc(),bitPacker=require_bitpacker(),filter=require_filter_pack(),zlib=__require("zlib"),Packer=module.exports=function(options){if(this._options=options,options.deflateChunkSize=options.deflateChunkSize||32768,options.deflateLevel=options.deflateLevel!=null?options.deflateLevel:9,options.deflateStrategy=options.deflateStrategy!=null?options.deflateStrategy:3,options.inputHasAlpha=options.inputHasAlpha!=null?options.inputHasAlpha:!0,options.deflateFactory=options.deflateFactory||zlib.createDeflate,options.bitDepth=options.bitDepth||8,options.colorType=typeof options.colorType==="number"?options.colorType:constants.COLORTYPE_COLOR_ALPHA,options.inputColorType=typeof options.inputColorType==="number"?options.inputColorType:constants.COLORTYPE_COLOR_ALPHA,[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)===-1)throw Error("option color type:"+options.colorType+" is not supported at present");if([constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.inputColorType)===-1)throw Error("option input color type:"+options.inputColorType+" is not supported at present");if(options.bitDepth!==8&&options.bitDepth!==16)throw Error("option bit depth:"+options.bitDepth+" is not supported at present")};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Packer.prototype.filterData=function(data,width,height){let packedData=bitPacker(data,width,height,this._options),bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(packedData,width,height,this._options,bpp)};Packer.prototype._packChunk=function(type,data){let len=data?data.length:0,buf=Buffer.alloc(len+12);if(buf.writeUInt32BE(len,0),buf.writeUInt32BE(type,4),data)data.copy(buf,8);return buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4),buf};Packer.prototype.packGAMA=function(gamma){let buf=Buffer.alloc(4);return buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,buf)};Packer.prototype.packIHDR=function(width,height){let buf=Buffer.alloc(13);return buf.writeUInt32BE(width,0),buf.writeUInt32BE(height,4),buf[8]=this._options.bitDepth,buf[9]=this._options.colorType,buf[10]=0,buf[11]=0,buf[12]=0,this._packChunk(constants.TYPE_IHDR,buf)};Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)};Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)}});var require_packer_async=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),constants=require_constants(),Packer=require_packer(),PackerAsync=module.exports=function(opt){Stream.call(this);let options=opt||{};this._packer=new Packer(options),this._deflate=this._packer.createDeflate(),this.readable=!0};util.inherits(PackerAsync,Stream);PackerAsync.prototype.pack=function(data,width,height,gamma){if(this.emit("data",Buffer.from(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(width,height)),gamma)this.emit("data",this._packer.packGAMA(gamma));let filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(filteredData)}});var require_sync_inflate=__commonJS(function(exports,module){var assert=__require("assert").ok,zlib=__require("zlib"),util=__require("util"),kMaxLength=__require("buffer").kMaxLength;function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);if(opts&&opts.chunkSize<zlib.Z_MIN_CHUNK)opts.chunkSize=zlib.Z_MIN_CHUNK;if(zlib.Inflate.call(this,opts),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,opts&&opts.maxLength!=null)this._maxLength=opts.maxLength}function createInflate(opts){return new Inflate(opts)}function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}Inflate.prototype._processChunk=function(chunk,flushFlag,asyncCb){if(typeof asyncCb==="function")return zlib.Inflate._processChunk.call(this,chunk,flushFlag,asyncCb);let self=this,availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,leftToInflate=this._maxLength,inOff=0,buffers=[],nread=0,error;this.on("error",function(err){error=err});function handleChunk(availInAfter,availOutAfter){if(self._hadError)return;let have=availOutBefore-availOutAfter;if(assert(have>=0,"have should not go down"),have>0){let out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,out.length>leftToInflate)out=out.slice(0,leftToInflate);if(buffers.push(out),nread+=out.length,leftToInflate-=out.length,leftToInflate===0)return!1}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer.allocUnsafe(self._chunkSize);if(availOutAfter===0)return inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!0;return!1}assert(this._handle,"zlib binding closed");let res;do res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore),res=res||this._writeState;while(!this._hadError&&handleChunk(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)throw _close(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");let buf=Buffer.concat(buffers,nread);return _close(this),buf};util.inherits(Inflate,zlib.Inflate);function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=Buffer.from(buffer);if(!(buffer instanceof Buffer))throw TypeError("Not a string or buffer");let flushFlag=engine._finishFlushFlag;if(flushFlag==null)flushFlag=zlib.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function inflateSync(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)}module.exports=exports=inflateSync;exports.Inflate=Inflate;exports.createInflate=createInflate;exports.inflateSync=inflateSync});var require_sync_reader=__commonJS(function(exports,module){var SyncReader=module.exports=function(buffer){this._buffer=buffer,this._reads=[]};SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})};SyncReader.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let read=this._reads[0];if(this._buffer.length&&(this._buffer.length>=read.length||read.allowLess)){this._reads.shift();let buf=this._buffer;this._buffer=buf.slice(read.length),read.func.call(this,buf.slice(0,read.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var require_filter_parse_sync=__commonJS(function(exports){var SyncReader=require_sync_reader(),Filter=require_filter_parse();exports.process=function(inBuffer,bitmapInfo){let outBuffers=[],reader=new SyncReader(inBuffer);return new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}}).start(),reader.process(),Buffer.concat(outBuffers)}});var require_parser_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib"),inflateSync=require_sync_inflate();if(!zlib.deflateSync)hasSyncZlib=!1;var SyncReader=require_sync_reader(),FilterSync=require_filter_parse_sync(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser();module.exports=function(buffer,options){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let err;function handleError(_err_){err=_err_}let metaData;function handleMetaData(_metaData_){metaData=_metaData_}function handleTransColor(transColor){metaData.transColor=transColor}function handlePalette(palette){metaData.palette=palette}function handleSimpleTransparency(){metaData.alpha=!0}let gamma;function handleGamma(_gamma_){gamma=_gamma_}let inflateDataList=[];function handleInflateData(inflatedData){inflateDataList.push(inflatedData)}let reader=new SyncReader(buffer);if(new Parser(options,{read:reader.read.bind(reader),error:handleError,metadata:handleMetaData,gamma:handleGamma,palette:handlePalette,transColor:handleTransColor,inflateData:handleInflateData,simpleTransparency:handleSimpleTransparency}).start(),reader.process(),err)throw err;let inflateData=Buffer.concat(inflateDataList);inflateDataList.length=0;let inflatedData;if(metaData.interlace)inflatedData=zlib.inflateSync(inflateData);else{let imageSize=((metaData.width*metaData.bpp*metaData.depth+7>>3)+1)*metaData.height;inflatedData=inflateSync(inflateData,{chunkSize:imageSize,maxLength:imageSize})}if(inflateData=null,!inflatedData||!inflatedData.length)throw Error("bad png - invalid inflate data response");let unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;let bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;let normalisedBitmapData=formatNormaliser(bitmapData,metaData,options.skipRescale);return metaData.data=normalisedBitmapData,metaData.gamma=gamma||0,metaData}});var require_packer_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib");if(!zlib.deflateSync)hasSyncZlib=!1;var constants=require_constants(),Packer=require_packer();module.exports=function(metaData,opt){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let packer=new Packer(opt||{}),chunks=[];if(chunks.push(Buffer.from(constants.PNG_SIGNATURE)),chunks.push(packer.packIHDR(metaData.width,metaData.height)),metaData.gamma)chunks.push(packer.packGAMA(metaData.gamma));let filteredData=packer.filterData(metaData.data,metaData.width,metaData.height),compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());if(filteredData=null,!compressedData||!compressedData.length)throw Error("bad png - invalid compressed data response");return chunks.push(packer.packIDAT(compressedData)),chunks.push(packer.packIEND()),Buffer.concat(chunks)}});var require_png_sync=__commonJS(function(exports){var parse=require_parser_sync(),pack=require_packer_sync();exports.read=function(buffer,options){return parse(buffer,options||{})};exports.write=function(png,options){return pack(png,options)}});var require_png=__commonJS(function(exports){var util=__require("util"),Stream=__require("stream"),Parser=require_parser_async(),Packer=require_packer_async(),PNGSync=require_png_sync(),PNG=exports.PNG=function(options){if(Stream.call(this),options=options||{},this.width=options.width|0,this.height=options.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,options.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(options),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(data){this.data=data,this.emit("parsed",data)}.bind(this)),this._packer=new Packer(options),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream);PNG.sync=PNGSync;PNG.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};PNG.prototype.parse=function(data,callback){if(callback){let onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError),this.data=parsedData,callback(null,this)}.bind(this),onError=function(err){this.removeListener("parsed",onParsed),callback(err,null)}.bind(this),this.once("parsed",onParsed),this.once("error",onError)}return this.end(data),this};PNG.prototype.write=function(data){return this._parser.write(data),!0};PNG.prototype.end=function(data){this._parser.end(data)};PNG.prototype._metadata=function(metadata){this.width=metadata.width,this.height=metadata.height,this.emit("metadata",metadata)};PNG.prototype._gamma=function(gamma){this.gamma=gamma};PNG.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){if(srcX|=0,srcY|=0,width|=0,height|=0,deltaX|=0,deltaY|=0,srcX>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height)throw Error("bitblt reading outside image");if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height)throw Error("bitblt writing outside image");for(let y=0;y<height;y++)src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)};PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){return PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY),this};PNG.adjustGamma=function(src){if(src.gamma){for(let y=0;y<src.height;y++)for(let x=0;x<src.width;x++){let idx=src.width*y+x<<2;for(let i=0;i<3;i++){let sample=src.data[idx+i]/255;sample=Math.pow(sample,0.45454545454545453/src.gamma),src.data[idx+i]=Math.round(sample*255)}}src.gamma=0}};PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)}});var require_react_development=__commonJS(function(exports,module){(function(){function defineDeprecationWarning(methodName,info){Object.defineProperty(Component.prototype,methodName,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",info[0],info[1])}})}function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}function warnNoop(publicInstance,callerName){publicInstance=(publicInstance=publicInstance.constructor)&&(publicInstance.displayName||publicInstance.name)||"ReactClass";var warningKey=publicInstance+"."+callerName;didWarnStateUpdateForUnmountedComponent[warningKey]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",callerName,publicInstance),didWarnStateUpdateForUnmountedComponent[warningKey]=!0)}function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function noop(){}function testStringCoercion(value){return""+value}function checkKeyStringCoercion(value){try{testStringCoercion(value);var JSCompiler_inline_result=!1}catch(e){JSCompiler_inline_result=!0}if(JSCompiler_inline_result){JSCompiler_inline_result=console;var JSCompiler_temp_const=JSCompiler_inline_result.error,JSCompiler_inline_result$jscomp$0=typeof Symbol==="function"&&Symbol.toStringTag&&value[Symbol.toStringTag]||value.constructor.name||"Object";return JSCompiler_temp_const.call(JSCompiler_inline_result,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",JSCompiler_inline_result$jscomp$0),testStringCoercion(value)}}function getComponentNameFromType(type){if(type==null)return null;if(typeof type==="function")return type.$$typeof===REACT_CLIENT_REFERENCE?null:type.displayName||type.name||null;if(typeof type==="string")return type;switch(type){case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_ACTIVITY_TYPE:return"Activity"}if(typeof type==="object")switch(typeof type.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),type.$$typeof){case REACT_PORTAL_TYPE:return"Portal";case REACT_CONTEXT_TYPE:return type.displayName||"Context";case REACT_CONSUMER_TYPE:return(type._context.displayName||"Context")+".Consumer";case REACT_FORWARD_REF_TYPE:var innerType=type.render;return type=type.displayName,type||(type=innerType.displayName||innerType.name||"",type=type!==""?"ForwardRef("+type+")":"ForwardRef"),type;case REACT_MEMO_TYPE:return innerType=type.displayName||null,innerType!==null?innerType:getComponentNameFromType(type.type)||"Memo";case REACT_LAZY_TYPE:innerType=type._payload,type=type._init;try{return getComponentNameFromType(type(innerType))}catch(x){}}return null}function getTaskName(type){if(type===REACT_FRAGMENT_TYPE)return"<>";if(typeof type==="object"&&type!==null&&type.$$typeof===REACT_LAZY_TYPE)return"<...>";try{var name=getComponentNameFromType(type);return name?"<"+name+">":"<...>"}catch(x){return"<...>"}}function getOwner(){var dispatcher=ReactSharedInternals.A;return dispatcher===null?null:dispatcher.getOwner()}function UnknownOwner(){return Error("react-stack-top-frame")}function hasValidKey(config){if(hasOwnProperty.call(config,"key")){var getter=Object.getOwnPropertyDescriptor(config,"key").get;if(getter&&getter.isReactWarning)return!1}return config.key!==void 0}function defineKeyPropWarningGetter(props,displayName){function warnAboutAccessingKey(){specialPropKeyWarningShown||(specialPropKeyWarningShown=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",displayName))}warnAboutAccessingKey.isReactWarning=!0,Object.defineProperty(props,"key",{get:warnAboutAccessingKey,configurable:!0})}function elementRefGetterWithDeprecationWarning(){var componentName=getComponentNameFromType(this.type);return didWarnAboutElementRef[componentName]||(didWarnAboutElementRef[componentName]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),componentName=this.props.ref,componentName!==void 0?componentName:null}function ReactElement(type,key,props,owner,debugStack,debugTask){var refProp=props.ref;return type={$$typeof:REACT_ELEMENT_TYPE,type,key,props,_owner:owner},(refProp!==void 0?refProp:null)!==null?Object.defineProperty(type,"ref",{enumerable:!1,get:elementRefGetterWithDeprecationWarning}):Object.defineProperty(type,"ref",{enumerable:!1,value:null}),type._store={},Object.defineProperty(type._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(type,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(type,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:debugStack}),Object.defineProperty(type,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:debugTask}),Object.freeze&&(Object.freeze(type.props),Object.freeze(type)),type}function cloneAndReplaceKey(oldElement,newKey){return newKey=ReactElement(oldElement.type,newKey,oldElement.props,oldElement._owner,oldElement._debugStack,oldElement._debugTask),oldElement._store&&(newKey._store.validated=oldElement._store.validated),newKey}function validateChildKeys(node){isValidElement(node)?node._store&&(node._store.validated=1):typeof node==="object"&&node!==null&&node.$$typeof===REACT_LAZY_TYPE&&(node._payload.status==="fulfilled"?isValidElement(node._payload.value)&&node._payload.value._store&&(node._payload.value._store.validated=1):node._store&&(node._store.validated=1))}function isValidElement(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}function getElementKey(element,index){return typeof element==="object"&&element!==null&&element.key!=null?(checkKeyStringCoercion(element.key),escape(""+element.key)):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch(typeof thenable.status==="string"?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){thenable.status==="pending"&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){thenable.status==="pending"&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;if(type==="undefined"||type==="boolean")children=null;var invokeCallback=!1;if(children===null)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return invokeCallback=children._init,mapIntoArray(invokeCallback(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback){invokeCallback=children,callback=callback(invokeCallback);var childKey=nameSoFar===""?"."+getElementKey(invokeCallback,0):nameSoFar;return isArrayImpl(callback)?(escapedPrefix="",childKey!=null&&(escapedPrefix=childKey.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):callback!=null&&(isValidElement(callback)&&(callback.key!=null&&(invokeCallback&&invokeCallback.key===callback.key||checkKeyStringCoercion(callback.key)),escapedPrefix=cloneAndReplaceKey(callback,escapedPrefix+(callback.key==null||invokeCallback&&invokeCallback.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+childKey),nameSoFar!==""&&invokeCallback!=null&&isValidElement(invokeCallback)&&invokeCallback.key==null&&invokeCallback._store&&!invokeCallback._store.validated&&(escapedPrefix._store.validated=2),callback=escapedPrefix),array.push(callback)),1}if(invokeCallback=0,childKey=nameSoFar===""?".":nameSoFar+":",isArrayImpl(children))for(var i=0;i<children.length;i++)nameSoFar=children[i],type=childKey+getElementKey(nameSoFar,i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(i=getIteratorFn(children),typeof i==="function")for(i===children.entries&&(didWarnAboutMaps||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),didWarnAboutMaps=!0),children=i.call(children),i=0;!(nameSoFar=children.next()).done;)nameSoFar=nameSoFar.value,type=childKey+getElementKey(nameSoFar,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(type==="object"){if(typeof children.then==="function")return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw array=String(children),Error("Objects are not valid as a React child (found: "+(array==="[object Object]"?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(children==null)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(payload._status===-1){var ioInfo=payload._ioInfo;ioInfo!=null&&(ioInfo.start=ioInfo.end=performance.now()),ioInfo=payload._result;var thenable=ioInfo();if(thenable.then(function(moduleObject){if(payload._status===0||payload._status===-1){payload._status=1,payload._result=moduleObject;var _ioInfo=payload._ioInfo;_ioInfo!=null&&(_ioInfo.end=performance.now()),thenable.status===void 0&&(thenable.status="fulfilled",thenable.value=moduleObject)}},function(error){if(payload._status===0||payload._status===-1){payload._status=2,payload._result=error;var _ioInfo2=payload._ioInfo;_ioInfo2!=null&&(_ioInfo2.end=performance.now()),thenable.status===void 0&&(thenable.status="rejected",thenable.reason=error)}}),ioInfo=payload._ioInfo,ioInfo!=null){ioInfo.value=thenable;var displayName=thenable.displayName;typeof displayName==="string"&&(ioInfo.name=displayName)}payload._status===-1&&(payload._status=0,payload._result=thenable)}if(payload._status===1)return ioInfo=payload._result,ioInfo===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
2
+ import{isCssIdent,sanitizeCssTokenValue,neutralizeCssText,sanitizeGoogleFontSpec,isComponentNode,isSnippetInstance,isParamRef,isTextNode,repoKey,PARAM_TAG_REF,STATIC_REF,nodeShape,isNode,ScreenSchema,resolveSnippetArgs,substituteSnippetParams,applySnippetOverrides,applySnippetExtraClassName,spacingCssTokens,ThemeSchema,typesetCss}from"./chunk-5x4nw0zz.js";import{__toESM,__commonJS,__exportCjs,__require}from"./chunk-2smsg2ct.js";var require_chunkstream=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),ChunkStream=module.exports=function(){Stream.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding="utf8",this.writable=!0};util.inherits(ChunkStream,Stream);ChunkStream.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback}),process.nextTick(function(){if(this._process(),this._paused&&this._reads&&this._reads.length>0)this._paused=!1,this.emit("drain")}.bind(this))};ChunkStream.prototype.write=function(data,encoding){if(!this.writable)return this.emit("error",Error("Stream not writable")),!1;let dataBuffer;if(Buffer.isBuffer(data))dataBuffer=data;else dataBuffer=Buffer.from(data,encoding||this._encoding);if(this._buffers.push(dataBuffer),this._buffered+=dataBuffer.length,this._process(),this._reads&&this._reads.length===0)this._paused=!0;return this.writable&&!this._paused};ChunkStream.prototype.end=function(data,encoding){if(data)this.write(data,encoding);if(this.writable=!1,!this._buffers)return;if(this._buffers.length===0)this._end();else this._buffers.push(null),this._process()};ChunkStream.prototype.destroySoon=ChunkStream.prototype.end;ChunkStream.prototype._end=function(){if(this._reads.length>0)this.emit("error",Error("Unexpected end of input"));this.destroy()};ChunkStream.prototype.destroy=function(){if(!this._buffers)return;this.writable=!1,this._reads=null,this._buffers=null,this.emit("close")};ChunkStream.prototype._processReadAllowingLess=function(read){this._reads.shift();let smallerBuf=this._buffers[0];if(smallerBuf.length>read.length)this._buffered-=read.length,this._buffers[0]=smallerBuf.slice(read.length),read.func.call(this,smallerBuf.slice(0,read.length));else this._buffered-=smallerBuf.length,this._buffers.shift(),read.func.call(this,smallerBuf)};ChunkStream.prototype._processRead=function(read){this._reads.shift();let pos=0,count=0,data=Buffer.alloc(read.length);while(pos<read.length){let buf=this._buffers[count++],len=Math.min(buf.length,read.length-pos);if(buf.copy(data,pos,0,len),pos+=len,len!==buf.length)this._buffers[--count]=buf.slice(len)}if(count>0)this._buffers.splice(0,count);this._buffered-=read.length,read.func.call(this,data)};ChunkStream.prototype._process=function(){try{while(this._buffered>0&&this._reads&&this._reads.length>0){let read=this._reads[0];if(read.allowLess)this._processReadAllowingLess(read);else if(this._buffered>=read.length)this._processRead(read);else break}if(this._buffers&&!this.writable)this._end()}catch(ex){this.emit("error",ex)}}});var require_interlace=__commonJS(function(exports){var imagePasses=[{x:[0],y:[0]},{x:[4],y:[0]},{x:[0,4],y:[4]},{x:[2,6],y:[0,4]},{x:[0,2,4,6],y:[2,6]},{x:[1,3,5,7],y:[0,2,4,6]},{x:[0,1,2,3,4,5,6,7],y:[1,3,5,7]}];exports.getImagePasses=function(width,height){let images=[],xLeftOver=width%8,yLeftOver=height%8,xRepeats=(width-xLeftOver)/8,yRepeats=(height-yLeftOver)/8;for(let i=0;i<imagePasses.length;i++){let pass=imagePasses[i],passWidth=xRepeats*pass.x.length,passHeight=yRepeats*pass.y.length;for(let j=0;j<pass.x.length;j++)if(pass.x[j]<xLeftOver)passWidth++;else break;for(let j=0;j<pass.y.length;j++)if(pass.y[j]<yLeftOver)passHeight++;else break;if(passWidth>0&&passHeight>0)images.push({width:passWidth,height:passHeight,index:i})}return images};exports.getInterlaceIterator=function(width){return function(x,y,pass){let outerXLeftOver=x%imagePasses[pass].x.length,outerX=(x-outerXLeftOver)/imagePasses[pass].x.length*8+imagePasses[pass].x[outerXLeftOver],outerYLeftOver=y%imagePasses[pass].y.length,outerY=(y-outerYLeftOver)/imagePasses[pass].y.length*8+imagePasses[pass].y[outerYLeftOver];return outerX*4+outerY*width*4}}});var require_paeth_predictor=__commonJS(function(exports,module){module.exports=function(left,above,upLeft){let paeth=left+above-upLeft,pLeft=Math.abs(paeth-left),pAbove=Math.abs(paeth-above),pUpLeft=Math.abs(paeth-upLeft);if(pLeft<=pAbove&&pLeft<=pUpLeft)return left;if(pAbove<=pUpLeft)return above;return upLeft}});var require_filter_parse=__commonJS(function(exports,module){var interlaceUtils=require_interlace(),paethPredictor=require_paeth_predictor();function getByteWidth(width,bpp,depth){let byteWidth=width*bpp;if(depth!==8)byteWidth=Math.ceil(byteWidth/(8/depth));return byteWidth}var Filter=module.exports=function(bitmapInfo,dependencies){let{width,height,interlace,bpp,depth}=bitmapInfo;if(this.read=dependencies.read,this.write=dependencies.write,this.complete=dependencies.complete,this._imageIndex=0,this._images=[],interlace){let passes=interlaceUtils.getImagePasses(width,height);for(let i=0;i<passes.length;i++)this._images.push({byteWidth:getByteWidth(passes[i].width,bpp,depth),height:passes[i].height,lineIndex:0})}else this._images.push({byteWidth:getByteWidth(width,bpp,depth),height,lineIndex:0});if(depth===8)this._xComparison=bpp;else if(depth===16)this._xComparison=bpp*2;else this._xComparison=1};Filter.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))};Filter.prototype._unFilterType1=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f1Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0;unfilteredLine[x]=rawByte+f1Left}};Filter.prototype._unFilterType2=function(rawData,unfilteredLine,byteWidth){let lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f2Up=lastLine?lastLine[x]:0;unfilteredLine[x]=rawByte+f2Up}};Filter.prototype._unFilterType3=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f3Up=lastLine?lastLine[x]:0,f3Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f3Add=Math.floor((f3Left+f3Up)/2);unfilteredLine[x]=rawByte+f3Add}};Filter.prototype._unFilterType4=function(rawData,unfilteredLine,byteWidth){let xComparison=this._xComparison,xBiggerThan=xComparison-1,lastLine=this._lastLine;for(let x=0;x<byteWidth;x++){let rawByte=rawData[1+x],f4Up=lastLine?lastLine[x]:0,f4Left=x>xBiggerThan?unfilteredLine[x-xComparison]:0,f4UpLeft=x>xBiggerThan&&lastLine?lastLine[x-xComparison]:0,f4Add=paethPredictor(f4Left,f4Up,f4UpLeft);unfilteredLine[x]=rawByte+f4Add}};Filter.prototype._reverseFilterLine=function(rawData){let filter=rawData[0],unfilteredLine,currentImage=this._images[this._imageIndex],byteWidth=currentImage.byteWidth;if(filter===0)unfilteredLine=rawData.slice(1,byteWidth+1);else switch(unfilteredLine=Buffer.alloc(byteWidth),filter){case 1:this._unFilterType1(rawData,unfilteredLine,byteWidth);break;case 2:this._unFilterType2(rawData,unfilteredLine,byteWidth);break;case 3:this._unFilterType3(rawData,unfilteredLine,byteWidth);break;case 4:this._unFilterType4(rawData,unfilteredLine,byteWidth);break;default:throw Error("Unrecognised filter type - "+filter)}if(this.write(unfilteredLine),currentImage.lineIndex++,currentImage.lineIndex>=currentImage.height)this._lastLine=null,this._imageIndex++,currentImage=this._images[this._imageIndex];else this._lastLine=unfilteredLine;if(currentImage)this.read(currentImage.byteWidth+1,this._reverseFilterLine.bind(this));else this._lastLine=null,this.complete()}});var require_filter_parse_async=__commonJS(function(exports,module){var util=__require("util"),ChunkStream=require_chunkstream(),Filter=require_filter_parse(),FilterAsync=module.exports=function(bitmapInfo){ChunkStream.call(this);let buffers=[],that=this;this._filter=new Filter(bitmapInfo,{read:this.read.bind(this),write:function(buffer){buffers.push(buffer)},complete:function(){that.emit("complete",Buffer.concat(buffers))}}),this._filter.start()};util.inherits(FilterAsync,ChunkStream)});var require_constants=__commonJS(function(exports,module){module.exports={PNG_SIGNATURE:[137,80,78,71,13,10,26,10],TYPE_IHDR:1229472850,TYPE_IEND:1229278788,TYPE_IDAT:1229209940,TYPE_PLTE:1347179589,TYPE_tRNS:1951551059,TYPE_gAMA:1732332865,COLORTYPE_GRAYSCALE:0,COLORTYPE_PALETTE:1,COLORTYPE_COLOR:2,COLORTYPE_ALPHA:4,COLORTYPE_PALETTE_COLOR:3,COLORTYPE_COLOR_ALPHA:6,COLORTYPE_TO_BPP_MAP:{0:1,2:3,3:1,4:2,6:4},GAMMA_DIVISION:1e5}});var require_crc=__commonJS(function(exports,module){var crcTable=[];(function(){for(let i=0;i<256;i++){let currentCrc=i;for(let j=0;j<8;j++)if(currentCrc&1)currentCrc=3988292384^currentCrc>>>1;else currentCrc=currentCrc>>>1;crcTable[i]=currentCrc}})();var CrcCalculator=module.exports=function(){this._crc=-1};CrcCalculator.prototype.write=function(data){for(let i=0;i<data.length;i++)this._crc=crcTable[(this._crc^data[i])&255]^this._crc>>>8;return!0};CrcCalculator.prototype.crc32=function(){return this._crc^-1};CrcCalculator.crc32=function(buf){let crc=-1;for(let i=0;i<buf.length;i++)crc=crcTable[(crc^buf[i])&255]^crc>>>8;return crc^-1}});var require_parser=__commonJS(function(exports,module){var constants=require_constants(),CrcCalculator=require_crc(),Parser=module.exports=function(options,dependencies){this._options=options,options.checkCRC=options.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[constants.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[constants.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[constants.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[constants.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[constants.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[constants.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=dependencies.read,this.error=dependencies.error,this.metadata=dependencies.metadata,this.gamma=dependencies.gamma,this.transColor=dependencies.transColor,this.palette=dependencies.palette,this.parsed=dependencies.parsed,this.inflateData=dependencies.inflateData,this.finished=dependencies.finished,this.simpleTransparency=dependencies.simpleTransparency,this.headersFinished=dependencies.headersFinished||function(){}};Parser.prototype.start=function(){this.read(constants.PNG_SIGNATURE.length,this._parseSignature.bind(this))};Parser.prototype._parseSignature=function(data){let signature=constants.PNG_SIGNATURE;for(let i=0;i<signature.length;i++)if(data[i]!==signature[i]){this.error(Error("Invalid file signature"));return}this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._parseChunkBegin=function(data){let length=data.readUInt32BE(0),type=data.readUInt32BE(4),name="";for(let i=4;i<8;i++)name+=String.fromCharCode(data[i]);let ancillary=Boolean(data[4]&32);if(!this._hasIHDR&&type!==constants.TYPE_IHDR){this.error(Error("Expected IHDR on beggining"));return}if(this._crc=new CrcCalculator,this._crc.write(Buffer.from(name)),this._chunks[type])return this._chunks[type](length);if(!ancillary){this.error(Error("Unsupported critical chunk type "+name));return}this.read(length+4,this._skipChunk.bind(this))};Parser.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))};Parser.prototype._parseChunkEnd=function(data){let fileCrc=data.readInt32BE(0),calcCrc=this._crc.crc32();if(this._options.checkCRC&&calcCrc!==fileCrc){this.error(Error("Crc error - "+fileCrc+" - "+calcCrc));return}if(!this._hasIEND)this.read(8,this._parseChunkBegin.bind(this))};Parser.prototype._handleIHDR=function(length){this.read(length,this._parseIHDR.bind(this))};Parser.prototype._parseIHDR=function(data){this._crc.write(data);let width=data.readUInt32BE(0),height=data.readUInt32BE(4),depth=data[8],colorType=data[9],compr=data[10],filter=data[11],interlace=data[12];if(depth!==8&&depth!==4&&depth!==2&&depth!==1&&depth!==16){this.error(Error("Unsupported bit depth "+depth));return}if(!(colorType in constants.COLORTYPE_TO_BPP_MAP)){this.error(Error("Unsupported color type"));return}if(compr!==0){this.error(Error("Unsupported compression method"));return}if(filter!==0){this.error(Error("Unsupported filter method"));return}if(interlace!==0&&interlace!==1){this.error(Error("Unsupported interlace method"));return}this._colorType=colorType;let bpp=constants.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width,height,depth,interlace:Boolean(interlace),palette:Boolean(colorType&constants.COLORTYPE_PALETTE),color:Boolean(colorType&constants.COLORTYPE_COLOR),alpha:Boolean(colorType&constants.COLORTYPE_ALPHA),bpp,colorType}),this._handleChunkEnd()};Parser.prototype._handlePLTE=function(length){this.read(length,this._parsePLTE.bind(this))};Parser.prototype._parsePLTE=function(data){this._crc.write(data);let entries=Math.floor(data.length/3);for(let i=0;i<entries;i++)this._palette.push([data[i*3],data[i*3+1],data[i*3+2],255]);this.palette(this._palette),this._handleChunkEnd()};Parser.prototype._handleTRNS=function(length){this.simpleTransparency(),this.read(length,this._parseTRNS.bind(this))};Parser.prototype._parseTRNS=function(data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error("Transparency chunk must be after palette"));return}if(data.length>this._palette.length){this.error(Error("More transparent colors than palette size"));return}for(let i=0;i<data.length;i++)this._palette[i][3]=data[i];this.palette(this._palette)}if(this._colorType===constants.COLORTYPE_GRAYSCALE)this.transColor([data.readUInt16BE(0)]);if(this._colorType===constants.COLORTYPE_COLOR)this.transColor([data.readUInt16BE(0),data.readUInt16BE(2),data.readUInt16BE(4)]);this._handleChunkEnd()};Parser.prototype._handleGAMA=function(length){this.read(length,this._parseGAMA.bind(this))};Parser.prototype._parseGAMA=function(data){this._crc.write(data),this.gamma(data.readUInt32BE(0)/constants.GAMMA_DIVISION),this._handleChunkEnd()};Parser.prototype._handleIDAT=function(length){if(!this._emittedHeadersFinished)this._emittedHeadersFinished=!0,this.headersFinished();this.read(-length,this._parseIDAT.bind(this,length))};Parser.prototype._parseIDAT=function(length,data){if(this._crc.write(data),this._colorType===constants.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error("Expected palette not found");this.inflateData(data);let leftOverLength=length-data.length;if(leftOverLength>0)this._handleIDAT(leftOverLength);else this._handleChunkEnd()};Parser.prototype._handleIEND=function(length){this.read(length,this._parseIEND.bind(this))};Parser.prototype._parseIEND=function(data){if(this._crc.write(data),this._hasIEND=!0,this._handleChunkEnd(),this.finished)this.finished()}});var require_bitmapper=__commonJS(function(exports){var interlaceUtils=require_interlace(),pixelBppMapper=[function(){},function(pxData,data,pxPos,rawPos){if(rawPos===data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+1>=data.length)throw Error("Ran out of data");let pixel=data[rawPos];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=data[rawPos+1]},function(pxData,data,pxPos,rawPos){if(rawPos+2>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=255},function(pxData,data,pxPos,rawPos){if(rawPos+3>=data.length)throw Error("Ran out of data");pxData[pxPos]=data[rawPos],pxData[pxPos+1]=data[rawPos+1],pxData[pxPos+2]=data[rawPos+2],pxData[pxPos+3]=data[rawPos+3]}],pixelBppCustomMapper=[function(){},function(pxData,pixelData,pxPos,maxBit){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){let pixel=pixelData[0];pxData[pxPos]=pixel,pxData[pxPos+1]=pixel,pxData[pxPos+2]=pixel,pxData[pxPos+3]=pixelData[1]},function(pxData,pixelData,pxPos,maxBit){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=maxBit},function(pxData,pixelData,pxPos){pxData[pxPos]=pixelData[0],pxData[pxPos+1]=pixelData[1],pxData[pxPos+2]=pixelData[2],pxData[pxPos+3]=pixelData[3]}];function bitRetriever(data,depth){let leftOver=[],i=0;function split(){if(i===data.length)throw Error("Ran out of data");let byte=data[i];i++;let byte8,byte7,byte6,byte5,byte4,byte3,byte2,byte1;switch(depth){default:throw Error("unrecognised depth");case 16:byte2=data[i],i++,leftOver.push((byte<<8)+byte2);break;case 4:byte2=byte&15,byte1=byte>>4,leftOver.push(byte1,byte2);break;case 2:byte4=byte&3,byte3=byte>>2&3,byte2=byte>>4&3,byte1=byte>>6&3,leftOver.push(byte1,byte2,byte3,byte4);break;case 1:byte8=byte&1,byte7=byte>>1&1,byte6=byte>>2&1,byte5=byte>>3&1,byte4=byte>>4&1,byte3=byte>>5&1,byte2=byte>>6&1,byte1=byte>>7&1,leftOver.push(byte1,byte2,byte3,byte4,byte5,byte6,byte7,byte8);break}}return{get:function(count){while(leftOver.length<count)split();let returner=leftOver.slice(0,count);return leftOver=leftOver.slice(count),returner},resetAfterLine:function(){leftOver.length=0},end:function(){if(i!==data.length)throw Error("extra data found")}}}function mapImage8Bit(image,pxData,getPxPos,bpp,data,rawPos){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++)for(let x=0;x<imageWidth;x++){let pxPos=getPxPos(x,y,imagePass);pixelBppMapper[bpp](pxData,data,pxPos,rawPos),rawPos+=bpp}return rawPos}function mapImageCustomBit(image,pxData,getPxPos,bpp,bits,maxBit){let{width:imageWidth,height:imageHeight,index:imagePass}=image;for(let y=0;y<imageHeight;y++){for(let x=0;x<imageWidth;x++){let pixelData=bits.get(bpp),pxPos=getPxPos(x,y,imagePass);pixelBppCustomMapper[bpp](pxData,pixelData,pxPos,maxBit)}bits.resetAfterLine()}}exports.dataToBitMap=function(data,bitmapInfo){let{width,height,depth,bpp,interlace}=bitmapInfo,bits;if(depth!==8)bits=bitRetriever(data,depth);let pxData;if(depth<=8)pxData=Buffer.alloc(width*height*4);else pxData=new Uint16Array(width*height*4);let maxBit=Math.pow(2,depth)-1,rawPos=0,images,getPxPos;if(interlace)images=interlaceUtils.getImagePasses(width,height),getPxPos=interlaceUtils.getInterlaceIterator(width,height);else{let nonInterlacedPxPos=0;getPxPos=function(){let returner=nonInterlacedPxPos;return nonInterlacedPxPos+=4,returner},images=[{width,height}]}for(let imageIndex=0;imageIndex<images.length;imageIndex++)if(depth===8)rawPos=mapImage8Bit(images[imageIndex],pxData,getPxPos,bpp,data,rawPos);else mapImageCustomBit(images[imageIndex],pxData,getPxPos,bpp,bits,maxBit);if(depth===8){if(rawPos!==data.length)throw Error("extra data found")}else bits.end();return pxData}});var require_format_normaliser=__commonJS(function(exports,module){function dePalette(indata,outdata,width,height,palette){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let color=palette[indata[pxPos]];if(!color)throw Error("index "+indata[pxPos]+" not in palette");for(let i=0;i<4;i++)outdata[pxPos+i]=color[i];pxPos+=4}}function replaceTransparentColor(indata,outdata,width,height,transColor){let pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let makeTrans=!1;if(transColor.length===1){if(transColor[0]===indata[pxPos])makeTrans=!0}else if(transColor[0]===indata[pxPos]&&transColor[1]===indata[pxPos+1]&&transColor[2]===indata[pxPos+2])makeTrans=!0;if(makeTrans)for(let i=0;i<4;i++)outdata[pxPos+i]=0;pxPos+=4}}function scaleDepth(indata,outdata,width,height,depth){let maxOutSample=255,maxInSample=Math.pow(2,depth)-1,pxPos=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){for(let i=0;i<4;i++)outdata[pxPos+i]=Math.floor(indata[pxPos+i]*maxOutSample/maxInSample+0.5);pxPos+=4}}module.exports=function(indata,imageData,skipRescale=!1){let{depth,width,height,colorType,transColor,palette}=imageData,outdata=indata;if(colorType===3)dePalette(indata,outdata,width,height,palette);else{if(transColor)replaceTransparentColor(indata,outdata,width,height,transColor);if(depth!==8&&!skipRescale){if(depth===16)outdata=Buffer.alloc(width*height*4);scaleDepth(indata,outdata,width,height,depth)}}return outdata}});var require_parser_async=__commonJS(function(exports,module){var util=__require("util"),zlib=__require("zlib"),ChunkStream=require_chunkstream(),FilterAsync=require_filter_parse_async(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser(),ParserAsync=module.exports=function(options){ChunkStream.call(this),this._parser=new Parser(options,{read:this.read.bind(this),error:this._handleError.bind(this),metadata:this._handleMetaData.bind(this),gamma:this.emit.bind(this,"gamma"),palette:this._handlePalette.bind(this),transColor:this._handleTransColor.bind(this),finished:this._finished.bind(this),inflateData:this._inflateData.bind(this),simpleTransparency:this._simpleTransparency.bind(this),headersFinished:this._headersFinished.bind(this)}),this._options=options,this.writable=!0,this._parser.start()};util.inherits(ParserAsync,ChunkStream);ParserAsync.prototype._handleError=function(err){if(this.emit("error",err),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy)this._inflate.destroy();if(this._filter)this._filter.destroy(),this._filter.on("error",function(){});this.errord=!0};ParserAsync.prototype._inflateData=function(data){if(!this._inflate)if(this._bitmapInfo.interlace)this._inflate=zlib.createInflate(),this._inflate.on("error",this.emit.bind(this,"error")),this._filter.on("complete",this._complete.bind(this)),this._inflate.pipe(this._filter);else{let imageSize=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,chunkSize=Math.max(imageSize,zlib.Z_MIN_CHUNK);this._inflate=zlib.createInflate({chunkSize});let leftToInflate=imageSize,emitError=this.emit.bind(this,"error");this._inflate.on("error",function(err){if(!leftToInflate)return;emitError(err)}),this._filter.on("complete",this._complete.bind(this));let filterWrite=this._filter.write.bind(this._filter);this._inflate.on("data",function(chunk){if(!leftToInflate)return;if(chunk.length>leftToInflate)chunk=chunk.slice(0,leftToInflate);leftToInflate-=chunk.length,filterWrite(chunk)}),this._inflate.on("end",this._filter.end.bind(this._filter))}this._inflate.write(data)};ParserAsync.prototype._handleMetaData=function(metaData){this._metaData=metaData,this._bitmapInfo=Object.create(metaData),this._filter=new FilterAsync(this._bitmapInfo)};ParserAsync.prototype._handleTransColor=function(transColor){this._bitmapInfo.transColor=transColor};ParserAsync.prototype._handlePalette=function(palette){this._bitmapInfo.palette=palette};ParserAsync.prototype._simpleTransparency=function(){this._metaData.alpha=!0};ParserAsync.prototype._headersFinished=function(){this.emit("metadata",this._metaData)};ParserAsync.prototype._finished=function(){if(this.errord)return;if(!this._inflate)this.emit("error","No Inflate block");else this._inflate.end()};ParserAsync.prototype._complete=function(filteredData){if(this.errord)return;let normalisedBitmapData;try{let bitmapData=bitmapper.dataToBitMap(filteredData,this._bitmapInfo);normalisedBitmapData=formatNormaliser(bitmapData,this._bitmapInfo,this._options.skipRescale),bitmapData=null}catch(ex){this._handleError(ex);return}this.emit("parsed",normalisedBitmapData)}});var require_bitpacker=__commonJS(function(exports,module){var constants=require_constants();module.exports=function(dataIn,width,height,options){let outHasAlpha=[constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)!==-1;if(options.colorType===options.inputColorType){let bigEndian=function(){let buffer=new ArrayBuffer(2);return new DataView(buffer).setInt16(0,256,!0),new Int16Array(buffer)[0]!==256}();if(options.bitDepth===8||options.bitDepth===16&&bigEndian)return dataIn}let data=options.bitDepth!==16?dataIn:new Uint16Array(dataIn.buffer),maxValue=255,inBpp=constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];if(inBpp===4&&!options.inputHasAlpha)inBpp=3;let outBpp=constants.COLORTYPE_TO_BPP_MAP[options.colorType];if(options.bitDepth===16)maxValue=65535,outBpp*=2;let outData=Buffer.alloc(width*height*outBpp),inIndex=0,outIndex=0,bgColor=options.bgColor||{};if(bgColor.red===void 0)bgColor.red=maxValue;if(bgColor.green===void 0)bgColor.green=maxValue;if(bgColor.blue===void 0)bgColor.blue=maxValue;function getRGBA(){let red,green,blue,alpha=maxValue;switch(options.inputColorType){case constants.COLORTYPE_COLOR_ALPHA:alpha=data[inIndex+3],red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_COLOR:red=data[inIndex],green=data[inIndex+1],blue=data[inIndex+2];break;case constants.COLORTYPE_ALPHA:alpha=data[inIndex+1],red=data[inIndex],green=red,blue=red;break;case constants.COLORTYPE_GRAYSCALE:red=data[inIndex],green=red,blue=red;break;default:throw Error("input color type:"+options.inputColorType+" is not supported at present")}if(options.inputHasAlpha){if(!outHasAlpha)alpha/=maxValue,red=Math.min(Math.max(Math.round((1-alpha)*bgColor.red+alpha*red),0),maxValue),green=Math.min(Math.max(Math.round((1-alpha)*bgColor.green+alpha*green),0),maxValue),blue=Math.min(Math.max(Math.round((1-alpha)*bgColor.blue+alpha*blue),0),maxValue)}return{red,green,blue,alpha}}for(let y=0;y<height;y++)for(let x=0;x<width;x++){let rgba=getRGBA(data,inIndex);switch(options.colorType){case constants.COLORTYPE_COLOR_ALPHA:case constants.COLORTYPE_COLOR:if(options.bitDepth===8){if(outData[outIndex]=rgba.red,outData[outIndex+1]=rgba.green,outData[outIndex+2]=rgba.blue,outHasAlpha)outData[outIndex+3]=rgba.alpha}else if(outData.writeUInt16BE(rgba.red,outIndex),outData.writeUInt16BE(rgba.green,outIndex+2),outData.writeUInt16BE(rgba.blue,outIndex+4),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+6);break;case constants.COLORTYPE_ALPHA:case constants.COLORTYPE_GRAYSCALE:{let grayscale=(rgba.red+rgba.green+rgba.blue)/3;if(options.bitDepth===8){if(outData[outIndex]=grayscale,outHasAlpha)outData[outIndex+1]=rgba.alpha}else if(outData.writeUInt16BE(grayscale,outIndex),outHasAlpha)outData.writeUInt16BE(rgba.alpha,outIndex+2);break}default:throw Error("unrecognised color Type "+options.colorType)}inIndex+=inBpp,outIndex+=outBpp}return outData}});var require_filter_pack=__commonJS(function(exports,module){var paethPredictor=require_paeth_predictor();function filterNone(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++)rawData[rawPos+x]=pxData[pxPos+x]}function filterSumNone(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let i=pxPos;i<length;i++)sum+=Math.abs(pxData[i]);return sum}function filterSub(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;rawData[rawPos+x]=val}}function filterSumSub(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,val=pxData[pxPos+x]-left;sum+=Math.abs(val)}return sum}function filterUp(pxData,pxPos,byteWidth,rawData,rawPos){for(let x=0;x<byteWidth;x++){let up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-up;rawData[rawPos+x]=val}}function filterSumUp(pxData,pxPos,byteWidth){let sum=0,length=pxPos+byteWidth;for(let x=pxPos;x<length;x++){let up=pxPos>0?pxData[x-byteWidth]:0,val=pxData[x]-up;sum+=Math.abs(val)}return sum}function filterAvg(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);rawData[rawPos+x]=val}}function filterSumAvg(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,val=pxData[pxPos+x]-(left+up>>1);sum+=Math.abs(val)}return sum}function filterPaeth(pxData,pxPos,byteWidth,rawData,rawPos,bpp){for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);rawData[rawPos+x]=val}}function filterSumPaeth(pxData,pxPos,byteWidth,bpp){let sum=0;for(let x=0;x<byteWidth;x++){let left=x>=bpp?pxData[pxPos+x-bpp]:0,up=pxPos>0?pxData[pxPos+x-byteWidth]:0,upleft=pxPos>0&&x>=bpp?pxData[pxPos+x-(byteWidth+bpp)]:0,val=pxData[pxPos+x]-paethPredictor(left,up,upleft);sum+=Math.abs(val)}return sum}var filters={0:filterNone,1:filterSub,2:filterUp,3:filterAvg,4:filterPaeth},filterSums={0:filterSumNone,1:filterSumSub,2:filterSumUp,3:filterSumAvg,4:filterSumPaeth};module.exports=function(pxData,width,height,options,bpp){let filterTypes;if(!("filterType"in options)||options.filterType===-1)filterTypes=[0,1,2,3,4];else if(typeof options.filterType==="number")filterTypes=[options.filterType];else throw Error("unrecognised filter types");if(options.bitDepth===16)bpp*=2;let byteWidth=width*bpp,rawPos=0,pxPos=0,rawData=Buffer.alloc((byteWidth+1)*height),sel=filterTypes[0];for(let y=0;y<height;y++){if(filterTypes.length>1){let min=1/0;for(let i=0;i<filterTypes.length;i++){let sum=filterSums[filterTypes[i]](pxData,pxPos,byteWidth,bpp);if(sum<min)sel=filterTypes[i],min=sum}}rawData[rawPos]=sel,rawPos++,filters[sel](pxData,pxPos,byteWidth,rawData,rawPos,bpp),rawPos+=byteWidth,pxPos+=byteWidth}return rawData}});var require_packer=__commonJS(function(exports,module){var constants=require_constants(),CrcStream=require_crc(),bitPacker=require_bitpacker(),filter=require_filter_pack(),zlib=__require("zlib"),Packer=module.exports=function(options){if(this._options=options,options.deflateChunkSize=options.deflateChunkSize||32768,options.deflateLevel=options.deflateLevel!=null?options.deflateLevel:9,options.deflateStrategy=options.deflateStrategy!=null?options.deflateStrategy:3,options.inputHasAlpha=options.inputHasAlpha!=null?options.inputHasAlpha:!0,options.deflateFactory=options.deflateFactory||zlib.createDeflate,options.bitDepth=options.bitDepth||8,options.colorType=typeof options.colorType==="number"?options.colorType:constants.COLORTYPE_COLOR_ALPHA,options.inputColorType=typeof options.inputColorType==="number"?options.inputColorType:constants.COLORTYPE_COLOR_ALPHA,[constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.colorType)===-1)throw Error("option color type:"+options.colorType+" is not supported at present");if([constants.COLORTYPE_GRAYSCALE,constants.COLORTYPE_COLOR,constants.COLORTYPE_COLOR_ALPHA,constants.COLORTYPE_ALPHA].indexOf(options.inputColorType)===-1)throw Error("option input color type:"+options.inputColorType+" is not supported at present");if(options.bitDepth!==8&&options.bitDepth!==16)throw Error("option bit depth:"+options.bitDepth+" is not supported at present")};Packer.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}};Packer.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())};Packer.prototype.filterData=function(data,width,height){let packedData=bitPacker(data,width,height,this._options),bpp=constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];return filter(packedData,width,height,this._options,bpp)};Packer.prototype._packChunk=function(type,data){let len=data?data.length:0,buf=Buffer.alloc(len+12);if(buf.writeUInt32BE(len,0),buf.writeUInt32BE(type,4),data)data.copy(buf,8);return buf.writeInt32BE(CrcStream.crc32(buf.slice(4,buf.length-4)),buf.length-4),buf};Packer.prototype.packGAMA=function(gamma){let buf=Buffer.alloc(4);return buf.writeUInt32BE(Math.floor(gamma*constants.GAMMA_DIVISION),0),this._packChunk(constants.TYPE_gAMA,buf)};Packer.prototype.packIHDR=function(width,height){let buf=Buffer.alloc(13);return buf.writeUInt32BE(width,0),buf.writeUInt32BE(height,4),buf[8]=this._options.bitDepth,buf[9]=this._options.colorType,buf[10]=0,buf[11]=0,buf[12]=0,this._packChunk(constants.TYPE_IHDR,buf)};Packer.prototype.packIDAT=function(data){return this._packChunk(constants.TYPE_IDAT,data)};Packer.prototype.packIEND=function(){return this._packChunk(constants.TYPE_IEND,null)}});var require_packer_async=__commonJS(function(exports,module){var util=__require("util"),Stream=__require("stream"),constants=require_constants(),Packer=require_packer(),PackerAsync=module.exports=function(opt){Stream.call(this);let options=opt||{};this._packer=new Packer(options),this._deflate=this._packer.createDeflate(),this.readable=!0};util.inherits(PackerAsync,Stream);PackerAsync.prototype.pack=function(data,width,height,gamma){if(this.emit("data",Buffer.from(constants.PNG_SIGNATURE)),this.emit("data",this._packer.packIHDR(width,height)),gamma)this.emit("data",this._packer.packGAMA(gamma));let filteredData=this._packer.filterData(data,width,height);this._deflate.on("error",this.emit.bind(this,"error")),this._deflate.on("data",function(compressedData){this.emit("data",this._packer.packIDAT(compressedData))}.bind(this)),this._deflate.on("end",function(){this.emit("data",this._packer.packIEND()),this.emit("end")}.bind(this)),this._deflate.end(filteredData)}});var require_sync_inflate=__commonJS(function(exports,module){var assert=__require("assert").ok,zlib=__require("zlib"),util=__require("util"),kMaxLength=__require("buffer").kMaxLength;function Inflate(opts){if(!(this instanceof Inflate))return new Inflate(opts);if(opts&&opts.chunkSize<zlib.Z_MIN_CHUNK)opts.chunkSize=zlib.Z_MIN_CHUNK;if(zlib.Inflate.call(this,opts),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,opts&&opts.maxLength!=null)this._maxLength=opts.maxLength}function createInflate(opts){return new Inflate(opts)}function _close(engine,callback){if(callback)process.nextTick(callback);if(!engine._handle)return;engine._handle.close(),engine._handle=null}Inflate.prototype._processChunk=function(chunk,flushFlag,asyncCb){if(typeof asyncCb==="function")return zlib.Inflate._processChunk.call(this,chunk,flushFlag,asyncCb);let self=this,availInBefore=chunk&&chunk.length,availOutBefore=this._chunkSize-this._offset,leftToInflate=this._maxLength,inOff=0,buffers=[],nread=0,error;this.on("error",function(err){error=err});function handleChunk(availInAfter,availOutAfter){if(self._hadError)return;let have=availOutBefore-availOutAfter;if(assert(have>=0,"have should not go down"),have>0){let out=self._buffer.slice(self._offset,self._offset+have);if(self._offset+=have,out.length>leftToInflate)out=out.slice(0,leftToInflate);if(buffers.push(out),nread+=out.length,leftToInflate-=out.length,leftToInflate===0)return!1}if(availOutAfter===0||self._offset>=self._chunkSize)availOutBefore=self._chunkSize,self._offset=0,self._buffer=Buffer.allocUnsafe(self._chunkSize);if(availOutAfter===0)return inOff+=availInBefore-availInAfter,availInBefore=availInAfter,!0;return!1}assert(this._handle,"zlib binding closed");let res;do res=this._handle.writeSync(flushFlag,chunk,inOff,availInBefore,this._buffer,this._offset,availOutBefore),res=res||this._writeState;while(!this._hadError&&handleChunk(res[0],res[1]));if(this._hadError)throw error;if(nread>=kMaxLength)throw _close(this),RangeError("Cannot create final Buffer. It would be larger than 0x"+kMaxLength.toString(16)+" bytes");let buf=Buffer.concat(buffers,nread);return _close(this),buf};util.inherits(Inflate,zlib.Inflate);function zlibBufferSync(engine,buffer){if(typeof buffer==="string")buffer=Buffer.from(buffer);if(!(buffer instanceof Buffer))throw TypeError("Not a string or buffer");let flushFlag=engine._finishFlushFlag;if(flushFlag==null)flushFlag=zlib.Z_FINISH;return engine._processChunk(buffer,flushFlag)}function inflateSync(buffer,opts){return zlibBufferSync(new Inflate(opts),buffer)}module.exports=exports=inflateSync;exports.Inflate=Inflate;exports.createInflate=createInflate;exports.inflateSync=inflateSync});var require_sync_reader=__commonJS(function(exports,module){var SyncReader=module.exports=function(buffer){this._buffer=buffer,this._reads=[]};SyncReader.prototype.read=function(length,callback){this._reads.push({length:Math.abs(length),allowLess:length<0,func:callback})};SyncReader.prototype.process=function(){while(this._reads.length>0&&this._buffer.length){let read=this._reads[0];if(this._buffer.length&&(this._buffer.length>=read.length||read.allowLess)){this._reads.shift();let buf=this._buffer;this._buffer=buf.slice(read.length),read.func.call(this,buf.slice(0,read.length))}else break}if(this._reads.length>0)throw Error("There are some read requests waitng on finished stream");if(this._buffer.length>0)throw Error("unrecognised content at end of stream")}});var require_filter_parse_sync=__commonJS(function(exports){var SyncReader=require_sync_reader(),Filter=require_filter_parse();exports.process=function(inBuffer,bitmapInfo){let outBuffers=[],reader=new SyncReader(inBuffer);return new Filter(bitmapInfo,{read:reader.read.bind(reader),write:function(bufferPart){outBuffers.push(bufferPart)},complete:function(){}}).start(),reader.process(),Buffer.concat(outBuffers)}});var require_parser_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib"),inflateSync=require_sync_inflate();if(!zlib.deflateSync)hasSyncZlib=!1;var SyncReader=require_sync_reader(),FilterSync=require_filter_parse_sync(),Parser=require_parser(),bitmapper=require_bitmapper(),formatNormaliser=require_format_normaliser();module.exports=function(buffer,options){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let err;function handleError(_err_){err=_err_}let metaData;function handleMetaData(_metaData_){metaData=_metaData_}function handleTransColor(transColor){metaData.transColor=transColor}function handlePalette(palette){metaData.palette=palette}function handleSimpleTransparency(){metaData.alpha=!0}let gamma;function handleGamma(_gamma_){gamma=_gamma_}let inflateDataList=[];function handleInflateData(inflatedData){inflateDataList.push(inflatedData)}let reader=new SyncReader(buffer);if(new Parser(options,{read:reader.read.bind(reader),error:handleError,metadata:handleMetaData,gamma:handleGamma,palette:handlePalette,transColor:handleTransColor,inflateData:handleInflateData,simpleTransparency:handleSimpleTransparency}).start(),reader.process(),err)throw err;let inflateData=Buffer.concat(inflateDataList);inflateDataList.length=0;let inflatedData;if(metaData.interlace)inflatedData=zlib.inflateSync(inflateData);else{let imageSize=((metaData.width*metaData.bpp*metaData.depth+7>>3)+1)*metaData.height;inflatedData=inflateSync(inflateData,{chunkSize:imageSize,maxLength:imageSize})}if(inflateData=null,!inflatedData||!inflatedData.length)throw Error("bad png - invalid inflate data response");let unfilteredData=FilterSync.process(inflatedData,metaData);inflateData=null;let bitmapData=bitmapper.dataToBitMap(unfilteredData,metaData);unfilteredData=null;let normalisedBitmapData=formatNormaliser(bitmapData,metaData,options.skipRescale);return metaData.data=normalisedBitmapData,metaData.gamma=gamma||0,metaData}});var require_packer_sync=__commonJS(function(exports,module){var hasSyncZlib=!0,zlib=__require("zlib");if(!zlib.deflateSync)hasSyncZlib=!1;var constants=require_constants(),Packer=require_packer();module.exports=function(metaData,opt){if(!hasSyncZlib)throw Error("To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0");let packer=new Packer(opt||{}),chunks=[];if(chunks.push(Buffer.from(constants.PNG_SIGNATURE)),chunks.push(packer.packIHDR(metaData.width,metaData.height)),metaData.gamma)chunks.push(packer.packGAMA(metaData.gamma));let filteredData=packer.filterData(metaData.data,metaData.width,metaData.height),compressedData=zlib.deflateSync(filteredData,packer.getDeflateOptions());if(filteredData=null,!compressedData||!compressedData.length)throw Error("bad png - invalid compressed data response");return chunks.push(packer.packIDAT(compressedData)),chunks.push(packer.packIEND()),Buffer.concat(chunks)}});var require_png_sync=__commonJS(function(exports){var parse=require_parser_sync(),pack=require_packer_sync();exports.read=function(buffer,options){return parse(buffer,options||{})};exports.write=function(png,options){return pack(png,options)}});var require_png=__commonJS(function(exports){var util=__require("util"),Stream=__require("stream"),Parser=require_parser_async(),Packer=require_packer_async(),PNGSync=require_png_sync(),PNG=exports.PNG=function(options){if(Stream.call(this),options=options||{},this.width=options.width|0,this.height=options.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,options.fill&&this.data)this.data.fill(0);this.gamma=0,this.readable=this.writable=!0,this._parser=new Parser(options),this._parser.on("error",this.emit.bind(this,"error")),this._parser.on("close",this._handleClose.bind(this)),this._parser.on("metadata",this._metadata.bind(this)),this._parser.on("gamma",this._gamma.bind(this)),this._parser.on("parsed",function(data){this.data=data,this.emit("parsed",data)}.bind(this)),this._packer=new Packer(options),this._packer.on("data",this.emit.bind(this,"data")),this._packer.on("end",this.emit.bind(this,"end")),this._parser.on("close",this._handleClose.bind(this)),this._packer.on("error",this.emit.bind(this,"error"))};util.inherits(PNG,Stream);PNG.sync=PNGSync;PNG.prototype.pack=function(){if(!this.data||!this.data.length)return this.emit("error","No data provided"),this;return process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this};PNG.prototype.parse=function(data,callback){if(callback){let onParsed,onError;onParsed=function(parsedData){this.removeListener("error",onError),this.data=parsedData,callback(null,this)}.bind(this),onError=function(err){this.removeListener("parsed",onParsed),callback(err,null)}.bind(this),this.once("parsed",onParsed),this.once("error",onError)}return this.end(data),this};PNG.prototype.write=function(data){return this._parser.write(data),!0};PNG.prototype.end=function(data){this._parser.end(data)};PNG.prototype._metadata=function(metadata){this.width=metadata.width,this.height=metadata.height,this.emit("metadata",metadata)};PNG.prototype._gamma=function(gamma){this.gamma=gamma};PNG.prototype._handleClose=function(){if(!this._parser.writable&&!this._packer.readable)this.emit("close")};PNG.bitblt=function(src,dst,srcX,srcY,width,height,deltaX,deltaY){if(srcX|=0,srcY|=0,width|=0,height|=0,deltaX|=0,deltaY|=0,srcX>src.width||srcY>src.height||srcX+width>src.width||srcY+height>src.height)throw Error("bitblt reading outside image");if(deltaX>dst.width||deltaY>dst.height||deltaX+width>dst.width||deltaY+height>dst.height)throw Error("bitblt writing outside image");for(let y=0;y<height;y++)src.data.copy(dst.data,(deltaY+y)*dst.width+deltaX<<2,(srcY+y)*src.width+srcX<<2,(srcY+y)*src.width+srcX+width<<2)};PNG.prototype.bitblt=function(dst,srcX,srcY,width,height,deltaX,deltaY){return PNG.bitblt(this,dst,srcX,srcY,width,height,deltaX,deltaY),this};PNG.adjustGamma=function(src){if(src.gamma){for(let y=0;y<src.height;y++)for(let x=0;x<src.width;x++){let idx=src.width*y+x<<2;for(let i=0;i<3;i++){let sample=src.data[idx+i]/255;sample=Math.pow(sample,0.45454545454545453/src.gamma),src.data[idx+i]=Math.round(sample*255)}}src.gamma=0}};PNG.prototype.adjustGamma=function(){PNG.adjustGamma(this)}});var require_react_development=__commonJS(function(exports,module){(function(){function defineDeprecationWarning(methodName,info){Object.defineProperty(Component.prototype,methodName,{get:function(){console.warn("%s(...) is deprecated in plain JavaScript React classes. %s",info[0],info[1])}})}function getIteratorFn(maybeIterable){if(maybeIterable===null||typeof maybeIterable!=="object")return null;return maybeIterable=MAYBE_ITERATOR_SYMBOL&&maybeIterable[MAYBE_ITERATOR_SYMBOL]||maybeIterable["@@iterator"],typeof maybeIterable==="function"?maybeIterable:null}function warnNoop(publicInstance,callerName){publicInstance=(publicInstance=publicInstance.constructor)&&(publicInstance.displayName||publicInstance.name)||"ReactClass";var warningKey=publicInstance+"."+callerName;didWarnStateUpdateForUnmountedComponent[warningKey]||(console.error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.",callerName,publicInstance),didWarnStateUpdateForUnmountedComponent[warningKey]=!0)}function Component(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function ComponentDummy(){}function PureComponent(props,context,updater){this.props=props,this.context=context,this.refs=emptyObject,this.updater=updater||ReactNoopUpdateQueue}function noop(){}function testStringCoercion(value){return""+value}function checkKeyStringCoercion(value){try{testStringCoercion(value);var JSCompiler_inline_result=!1}catch(e){JSCompiler_inline_result=!0}if(JSCompiler_inline_result){JSCompiler_inline_result=console;var JSCompiler_temp_const=JSCompiler_inline_result.error,JSCompiler_inline_result$jscomp$0=typeof Symbol==="function"&&Symbol.toStringTag&&value[Symbol.toStringTag]||value.constructor.name||"Object";return JSCompiler_temp_const.call(JSCompiler_inline_result,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",JSCompiler_inline_result$jscomp$0),testStringCoercion(value)}}function getComponentNameFromType(type){if(type==null)return null;if(typeof type==="function")return type.$$typeof===REACT_CLIENT_REFERENCE?null:type.displayName||type.name||null;if(typeof type==="string")return type;switch(type){case REACT_FRAGMENT_TYPE:return"Fragment";case REACT_PROFILER_TYPE:return"Profiler";case REACT_STRICT_MODE_TYPE:return"StrictMode";case REACT_SUSPENSE_TYPE:return"Suspense";case REACT_SUSPENSE_LIST_TYPE:return"SuspenseList";case REACT_ACTIVITY_TYPE:return"Activity"}if(typeof type==="object")switch(typeof type.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),type.$$typeof){case REACT_PORTAL_TYPE:return"Portal";case REACT_CONTEXT_TYPE:return type.displayName||"Context";case REACT_CONSUMER_TYPE:return(type._context.displayName||"Context")+".Consumer";case REACT_FORWARD_REF_TYPE:var innerType=type.render;return type=type.displayName,type||(type=innerType.displayName||innerType.name||"",type=type!==""?"ForwardRef("+type+")":"ForwardRef"),type;case REACT_MEMO_TYPE:return innerType=type.displayName||null,innerType!==null?innerType:getComponentNameFromType(type.type)||"Memo";case REACT_LAZY_TYPE:innerType=type._payload,type=type._init;try{return getComponentNameFromType(type(innerType))}catch(x){}}return null}function getTaskName(type){if(type===REACT_FRAGMENT_TYPE)return"<>";if(typeof type==="object"&&type!==null&&type.$$typeof===REACT_LAZY_TYPE)return"<...>";try{var name=getComponentNameFromType(type);return name?"<"+name+">":"<...>"}catch(x){return"<...>"}}function getOwner(){var dispatcher=ReactSharedInternals.A;return dispatcher===null?null:dispatcher.getOwner()}function UnknownOwner(){return Error("react-stack-top-frame")}function hasValidKey(config){if(hasOwnProperty.call(config,"key")){var getter=Object.getOwnPropertyDescriptor(config,"key").get;if(getter&&getter.isReactWarning)return!1}return config.key!==void 0}function defineKeyPropWarningGetter(props,displayName){function warnAboutAccessingKey(){specialPropKeyWarningShown||(specialPropKeyWarningShown=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",displayName))}warnAboutAccessingKey.isReactWarning=!0,Object.defineProperty(props,"key",{get:warnAboutAccessingKey,configurable:!0})}function elementRefGetterWithDeprecationWarning(){var componentName=getComponentNameFromType(this.type);return didWarnAboutElementRef[componentName]||(didWarnAboutElementRef[componentName]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),componentName=this.props.ref,componentName!==void 0?componentName:null}function ReactElement(type,key,props,owner,debugStack,debugTask){var refProp=props.ref;return type={$$typeof:REACT_ELEMENT_TYPE,type,key,props,_owner:owner},(refProp!==void 0?refProp:null)!==null?Object.defineProperty(type,"ref",{enumerable:!1,get:elementRefGetterWithDeprecationWarning}):Object.defineProperty(type,"ref",{enumerable:!1,value:null}),type._store={},Object.defineProperty(type._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(type,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(type,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:debugStack}),Object.defineProperty(type,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:debugTask}),Object.freeze&&(Object.freeze(type.props),Object.freeze(type)),type}function cloneAndReplaceKey(oldElement,newKey){return newKey=ReactElement(oldElement.type,newKey,oldElement.props,oldElement._owner,oldElement._debugStack,oldElement._debugTask),oldElement._store&&(newKey._store.validated=oldElement._store.validated),newKey}function validateChildKeys(node){isValidElement(node)?node._store&&(node._store.validated=1):typeof node==="object"&&node!==null&&node.$$typeof===REACT_LAZY_TYPE&&(node._payload.status==="fulfilled"?isValidElement(node._payload.value)&&node._payload.value._store&&(node._payload.value._store.validated=1):node._store&&(node._store.validated=1))}function isValidElement(object){return typeof object==="object"&&object!==null&&object.$$typeof===REACT_ELEMENT_TYPE}function escape(key){var escaperLookup={"=":"=0",":":"=2"};return"$"+key.replace(/[=:]/g,function(match){return escaperLookup[match]})}function getElementKey(element,index){return typeof element==="object"&&element!==null&&element.key!=null?(checkKeyStringCoercion(element.key),escape(""+element.key)):index.toString(36)}function resolveThenable(thenable){switch(thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason;default:switch(typeof thenable.status==="string"?thenable.then(noop,noop):(thenable.status="pending",thenable.then(function(fulfilledValue){thenable.status==="pending"&&(thenable.status="fulfilled",thenable.value=fulfilledValue)},function(error){thenable.status==="pending"&&(thenable.status="rejected",thenable.reason=error)})),thenable.status){case"fulfilled":return thenable.value;case"rejected":throw thenable.reason}}throw thenable}function mapIntoArray(children,array,escapedPrefix,nameSoFar,callback){var type=typeof children;if(type==="undefined"||type==="boolean")children=null;var invokeCallback=!1;if(children===null)invokeCallback=!0;else switch(type){case"bigint":case"string":case"number":invokeCallback=!0;break;case"object":switch(children.$$typeof){case REACT_ELEMENT_TYPE:case REACT_PORTAL_TYPE:invokeCallback=!0;break;case REACT_LAZY_TYPE:return invokeCallback=children._init,mapIntoArray(invokeCallback(children._payload),array,escapedPrefix,nameSoFar,callback)}}if(invokeCallback){invokeCallback=children,callback=callback(invokeCallback);var childKey=nameSoFar===""?"."+getElementKey(invokeCallback,0):nameSoFar;return isArrayImpl(callback)?(escapedPrefix="",childKey!=null&&(escapedPrefix=childKey.replace(userProvidedKeyEscapeRegex,"$&/")+"/"),mapIntoArray(callback,array,escapedPrefix,"",function(c){return c})):callback!=null&&(isValidElement(callback)&&(callback.key!=null&&(invokeCallback&&invokeCallback.key===callback.key||checkKeyStringCoercion(callback.key)),escapedPrefix=cloneAndReplaceKey(callback,escapedPrefix+(callback.key==null||invokeCallback&&invokeCallback.key===callback.key?"":(""+callback.key).replace(userProvidedKeyEscapeRegex,"$&/")+"/")+childKey),nameSoFar!==""&&invokeCallback!=null&&isValidElement(invokeCallback)&&invokeCallback.key==null&&invokeCallback._store&&!invokeCallback._store.validated&&(escapedPrefix._store.validated=2),callback=escapedPrefix),array.push(callback)),1}if(invokeCallback=0,childKey=nameSoFar===""?".":nameSoFar+":",isArrayImpl(children))for(var i=0;i<children.length;i++)nameSoFar=children[i],type=childKey+getElementKey(nameSoFar,i),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(i=getIteratorFn(children),typeof i==="function")for(i===children.entries&&(didWarnAboutMaps||console.warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."),didWarnAboutMaps=!0),children=i.call(children),i=0;!(nameSoFar=children.next()).done;)nameSoFar=nameSoFar.value,type=childKey+getElementKey(nameSoFar,i++),invokeCallback+=mapIntoArray(nameSoFar,array,escapedPrefix,type,callback);else if(type==="object"){if(typeof children.then==="function")return mapIntoArray(resolveThenable(children),array,escapedPrefix,nameSoFar,callback);throw array=String(children),Error("Objects are not valid as a React child (found: "+(array==="[object Object]"?"object with keys {"+Object.keys(children).join(", ")+"}":array)+"). If you meant to render a collection of children, use an array instead.")}return invokeCallback}function mapChildren(children,func,context){if(children==null)return children;var result=[],count=0;return mapIntoArray(children,result,"","",function(child){return func.call(context,child,count++)}),result}function lazyInitializer(payload){if(payload._status===-1){var ioInfo=payload._ioInfo;ioInfo!=null&&(ioInfo.start=ioInfo.end=performance.now()),ioInfo=payload._result;var thenable=ioInfo();if(thenable.then(function(moduleObject){if(payload._status===0||payload._status===-1){payload._status=1,payload._result=moduleObject;var _ioInfo=payload._ioInfo;_ioInfo!=null&&(_ioInfo.end=performance.now()),thenable.status===void 0&&(thenable.status="fulfilled",thenable.value=moduleObject)}},function(error){if(payload._status===0||payload._status===-1){payload._status=2,payload._result=error;var _ioInfo2=payload._ioInfo;_ioInfo2!=null&&(_ioInfo2.end=performance.now()),thenable.status===void 0&&(thenable.status="rejected",thenable.reason=error)}}),ioInfo=payload._ioInfo,ioInfo!=null){ioInfo.value=thenable;var displayName=thenable.displayName;typeof displayName==="string"&&(ioInfo.name=displayName)}payload._status===-1&&(payload._status=0,payload._result=thenable)}if(payload._status===1)return ioInfo=payload._result,ioInfo===void 0&&console.error(`lazy: Expected the result of a dynamic import() call. Instead received: %s
3
3
 
4
4
  Your code should look like:
5
5
  const MyComponent = lazy(() => import('./MyComponent'))
@@ -76,7 +76,7 @@ Check the top-level render call using <`+componentName+">."),componentName="",di
76
76
  `,VALID_TAG_REGEX=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,validatedTagCache=new Map,endTagCache=new Map,shellTimeRuntimeScript="requestAnimationFrame(function(){$RT=performance.now()});",placeholder1='<template id="',placeholder2='"></template>',startCompletedSuspenseBoundary="<!--$-->",startPendingSuspenseBoundary1='<!--$?--><template id="',startPendingSuspenseBoundary2='"></template>',startClientRenderedSuspenseBoundary="<!--$!-->",endSuspenseBoundary="<!--/$-->",clientRenderedSuspenseBoundaryError1="<template",clientRenderedSuspenseBoundaryErrorAttrInterstitial='"',clientRenderedSuspenseBoundaryError1A=' data-dgst="',clientRenderedSuspenseBoundaryError1B=' data-msg="',clientRenderedSuspenseBoundaryError1C=' data-stck="',clientRenderedSuspenseBoundaryError1D=' data-cstck="',clientRenderedSuspenseBoundaryError2="></template>",startSegmentHTML='<div hidden id="',startSegmentHTML2='">',endSegmentHTML="</div>",startSegmentSVG='<svg aria-hidden="true" style="display:none" id="',startSegmentSVG2='">',endSegmentSVG="</svg>",startSegmentMathML='<math aria-hidden="true" style="display:none" id="',startSegmentMathML2='">',endSegmentMathML="</math>",startSegmentTable='<table hidden id="',startSegmentTable2='">',endSegmentTable="</table>",startSegmentTableBody='<table hidden><tbody id="',startSegmentTableBody2='">',endSegmentTableBody="</tbody></table>",startSegmentTableRow='<table hidden><tr id="',startSegmentTableRow2='">',endSegmentTableRow="</tr></table>",startSegmentColGroup='<table hidden><colgroup id="',startSegmentColGroup2='">',endSegmentColGroup="</colgroup></table>",completeSegmentScript1Full='$RS=function(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)};$RS("',completeSegmentScript1Partial='$RS("',completeSegmentScript2='","',completeSegmentScriptEnd='")</script>',completeBoundaryScriptFunctionOnly=`$RB=[];$RV=function(a){$RT=performance.now();for(var b=0;b<a.length;b+=2){var c=a[b],e=a[b+1];null!==e.parentNode&&e.parentNode.removeChild(e);var f=c.parentNode;if(f){var g=c.previousSibling,h=0;do{if(c&&8===c.nodeType){var d=c.data;if("/$"===d||"/&"===d)if(0===h)break;else h--;else"$"!==d&&"$?"!==d&&"$~"!==d&&"$!"!==d&&"&"!==d||h++}d=c.nextSibling;f.removeChild(c);c=d}while(c);for(;e.firstChild;)f.insertBefore(e.firstChild,c);g.data="$";g._reactRetry&&requestAnimationFrame(g._reactRetry)}}a.length=0};
77
77
  $RC=function(a,b){if(b=document.getElementById(b))(a=document.getElementById(a))?(a.previousSibling.data="$~",$RB.push(a,b),2===$RB.length&&("number"!==typeof $RT?requestAnimationFrame($RV.bind(null,$RB)):(a=performance.now(),setTimeout($RV.bind(null,$RB),2300>a&&2E3<a?2300-a:$RT+300-a)))):b.parentNode.removeChild(b)};`,completeBoundaryScript1Partial='$RC("',completeBoundaryWithStylesScript1FullPartial=`$RM=new Map;$RR=function(n,w,p){function u(q){this._p=null;q()}for(var r=new Map,t=document,h,b,e=t.querySelectorAll("link[data-precedence],style[data-precedence]"),v=[],k=0;b=e[k++];)"not all"===b.getAttribute("media")?v.push(b):("LINK"===b.tagName&&$RM.set(b.getAttribute("href"),b),r.set(b.dataset.precedence,h=b));e=0;b=[];var l,a;for(k=!0;;){if(k){var f=p[e++];if(!f){k=!1;e=0;continue}var c=!1,m=0;var d=f[m++];if(a=$RM.get(d)){var g=a._p;c=!0}else{a=t.createElement("link");a.href=d;a.rel=
78
78
  "stylesheet";for(a.dataset.precedence=l=f[m++];g=f[m++];)a.setAttribute(g,f[m++]);g=a._p=new Promise(function(q,x){a.onload=u.bind(a,q);a.onerror=u.bind(a,x)});$RM.set(d,a)}d=a.getAttribute("media");!g||d&&!matchMedia(d).matches||b.push(g);if(c)continue}else{a=v[e++];if(!a)break;l=a.getAttribute("data-precedence");a.removeAttribute("media")}c=r.get(l)||h;c===h&&(h=a);r.set(l,a);c?c.parentNode.insertBefore(a,c.nextSibling):(c=t.head,c.insertBefore(a,c.firstChild))}if(p=document.getElementById(n))p.previousSibling.data=
79
- "$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("`,completeBoundaryWithStylesScript1Partial='$RR("',completeBoundaryScript2='","',completeBoundaryScript3a='",',completeBoundaryScript3b='"',completeBoundaryScriptEnd=")</script>",clientRenderScriptFunctionOnly='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};',clientRenderScript1Full='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("',clientRenderScript1Partial='$RX("',clientRenderScript1A='"',clientRenderErrorScriptArgInterstitial=",",clientRenderScriptEnd=")</script>",regexForJSStringsInInstructionScripts=/[<\u2028\u2029]/g,regexForJSStringsInScripts=/[&><\u2028\u2029]/g,lateStyleTagResourceOpen1=' media="not all" data-precedence="',lateStyleTagResourceOpen2='" data-href="',lateStyleTagResourceOpen3='">',lateStyleTagTemplateClose="</style>",currentlyRenderingBoundaryHasStylesToHoist=!1,destinationHasCapacity=!0,stylesheetFlushingQueue=[],styleTagResourceOpen1=' data-precedence="',styleTagResourceOpen2='" data-href="',spaceSeparator=" ",styleTagResourceOpen3='">',styleTagResourceClose="</style>",completedShellIdAttributeStart=' id="',arrayFirstOpenBracket="[",arraySubsequentOpenBracket=",[",arrayInterstitial=",",arrayCloseBracket="]",PENDING$1=0,PRELOADED=1,PREAMBLE=2,LATE=3,regexForHrefInLinkHeaderURLContext=/[<>\r\n]/g,regexForLinkHeaderQuotedParamValueContext=/["';,\r\n]/g,doctypeChunk="",bind=Function.prototype.bind,REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference"),emptyContextObject={};Object.freeze(emptyContextObject);var rendererSigil={},currentActiveSnapshot=null,didWarnAboutNoopUpdateForComponent={},didWarnAboutDeprecatedWillMount={},didWarnAboutUninitializedState=new Set,didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set,didWarnAboutLegacyLifecyclesAndDerivedState=new Set,didWarnAboutDirectlyAssigningPropsToState=new Set,didWarnAboutUndefinedDerivedState=new Set,didWarnAboutContextTypes$1=new Set,didWarnAboutChildContextTypes=new Set,didWarnAboutInvalidateContextType=new Set,didWarnOnInvalidCallback=new Set,classComponentUpdater={enqueueSetState:function(inst,payload,callback){var internals=inst._reactInternals;internals.queue===null?warnNoop(inst,"setState"):(internals.queue.push(payload),callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback))},enqueueReplaceState:function(inst,payload,callback){inst=inst._reactInternals,inst.replace=!0,inst.queue=[payload],callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)},enqueueForceUpdate:function(inst,callback){inst._reactInternals.queue===null?warnNoop(inst,"forceUpdate"):callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)}},emptyTreeContext={id:1,overflow:""},clz32=Math.clz32?Math.clz32:clz32Fallback,{log,LN2}=Math,SuspenseException=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."),suspendedThenable=null,objectIs=typeof Object.is==="function"?Object.is:is,currentlyRenderingComponent=null,currentlyRenderingTask=null,currentlyRenderingRequest=null,currentlyRenderingKeyPath=null,firstWorkInProgressHook=null,workInProgressHook=null,isReRender=!1,didScheduleRenderPhaseUpdate=!1,localIdCounter=0,actionStateCounter=0,actionStateMatchingIndex=-1,thenableIndexCounter=0,thenableState=null,renderPhaseUpdates=null,numberOfReRenders=0,isInHookUserCodeInDev=!1,currentHookNameInDev,HooksDispatcher={readContext,use:function(usable){if(usable!==null&&typeof usable==="object"){if(typeof usable.then==="function")return unwrapThenable(usable);if(usable.$$typeof===REACT_CONTEXT_TYPE)return readContext(usable)}throw Error("An unsupported type was passed to use(): "+String(usable))},useContext:function(context){return currentHookNameInDev="useContext",resolveCurrentlyRenderingComponent(),context._currentValue2},useMemo,useReducer,useRef:function(initialValue){currentlyRenderingComponent=resolveCurrentlyRenderingComponent(),workInProgressHook=createWorkInProgressHook();var previousRef=workInProgressHook.memoizedState;return previousRef===null?(initialValue={current:initialValue},Object.seal(initialValue),workInProgressHook.memoizedState=initialValue):previousRef},useState:function(initialState){return currentHookNameInDev="useState",useReducer(basicStateReducer,initialState)},useInsertionEffect:noop,useLayoutEffect:noop,useCallback:function(callback,deps){return useMemo(function(){return callback},deps)},useImperativeHandle:noop,useEffect:noop,useDebugValue:noop,useDeferredValue:function(value,initialValue){return resolveCurrentlyRenderingComponent(),initialValue!==void 0?initialValue:value},useTransition:function(){return resolveCurrentlyRenderingComponent(),[!1,unsupportedStartTransition]},useId:function(){var treeId=currentlyRenderingTask.treeContext,overflow=treeId.overflow;treeId=treeId.id,treeId=(treeId&~(1<<32-clz32(treeId)-1)).toString(32)+overflow;var resumableState=currentResumableState;if(resumableState===null)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");return overflow=localIdCounter++,treeId="_"+resumableState.idPrefix+"R_"+treeId,0<overflow&&(treeId+="H"+overflow.toString(32)),treeId+"_"},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){if(getServerSnapshot===void 0)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");return getServerSnapshot()},useOptimistic:function(passthrough){return resolveCurrentlyRenderingComponent(),[passthrough,unsupportedSetOptimisticState]},useActionState,useFormState:useActionState,useHostTransitionStatus:function(){return resolveCurrentlyRenderingComponent(),NotPending},useMemoCache:function(size){for(var data=Array(size),i=0;i<size;i++)data[i]=REACT_MEMO_CACHE_SENTINEL;return data},useCacheRefresh:function(){return unsupportedRefresh},useEffectEvent:function(){return throwOnUseEffectEventCall}},currentResumableState=null,currentTaskInDEV=null,DefaultAsyncDispatcher={getCacheForType:function(){throw Error("Not implemented.")},cacheSignal:function(){throw Error("Not implemented.")},getOwner:function(){return currentTaskInDEV===null?null:currentTaskInDEV.componentStack}},disabledDepth=0,prevLog,prevInfo,prevWarn,prevError,prevGroup,prevGroupCollapsed,prevGroupEnd;disabledLog.__reactDisabledLog=!0;var prefix,suffix,reentry=!1,componentFrameCache=new(typeof WeakMap==="function"?WeakMap:Map),callComponent={react_stack_bottom_frame:function(Component,props,secondArg){return Component(props,secondArg)}},callComponentInDEV=callComponent.react_stack_bottom_frame.bind(callComponent),callRender={react_stack_bottom_frame:function(instance){return instance.render()}},callRenderInDEV=callRender.react_stack_bottom_frame.bind(callRender),callLazyInit={react_stack_bottom_frame:function(lazy){var init=lazy._init;return init(lazy._payload)}},callLazyInitInDEV=callLazyInit.react_stack_bottom_frame.bind(callLazyInit),lastResetTime=0;if(typeof performance==="object"&&typeof performance.now==="function")var localPerformance=performance,getCurrentTime=function(){return localPerformance.now()};else{var localDate=Date;getCurrentTime=function(){return localDate.now()}}var CLIENT_RENDERED=4,PENDING=0,COMPLETED=1,FLUSHED=2,ABORTED=3,ERRORED=4,POSTPONED=5,CLOSED=14,currentRequest=null,didWarnAboutBadClass={},didWarnAboutContextTypes={},didWarnAboutContextTypeOnFunctionComponent={},didWarnAboutGetDerivedStateOnFunctionComponent={},didWarnAboutReassigningProps=!1,didWarnAboutGenerators=!1,didWarnAboutMaps=!1,flushedByteSize=0,flushingPartialBoundaries=!1;exports.renderToStaticMarkup=function(children,options){return renderToStringImpl(children,options,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.renderToString=function(children,options){return renderToStringImpl(children,options,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.version="19.2.8"})()});import{existsSync,readdirSync}from"fs";import{join}from"path";var package_default={name:"@velloo/renderer",version:"0.0.0",license:"Apache-2.0",private:!0,type:"module",description:"Headless renderer: design JSON \u2192 HTML + screenshot",exports:{".":"./src/index.ts","./iframe-protocol":"./src/iframe-protocol.ts"},dependencies:{"@velloo/provider":"workspace:*","@velloo/schema":"workspace:*",pixelmatch:"7.2.0",pngjs:"7.0.0",react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@types/pngjs":"6.0.5","@types/react":"19.2.18","@types/react-dom":"19.2.7","@velloo/shadcn-snapshot":"workspace:*",playwright:"1.62.1","playwright-core":"1.62.1"}};var PLAYWRIGHT_VERSION=package_default.devDependencies["playwright-core"],PLAYWRIGHT_PIN=`playwright@${PLAYWRIGHT_VERSION}`,CHROMIUM_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium","--only-shell"],CHROMIUM_INSTALL_CMD="velloo browser install",CHROMIUM_FULL_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium"],CHROMIUM_FULL_INSTALL_CMD="velloo browser install --full",CHROMIUM_DEPS_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install-deps","chromium"],CHROMIUM_DEPS_INSTALL_CMD="velloo browser install --with-deps",INSTALL_HINT=`Velloo screenshots need a headless browser. Install it once with:
79
+ "$~";Promise.all(b).then($RC.bind(null,n,w),$RX.bind(null,n,"CSS failed to load"))};$RR("`,completeBoundaryWithStylesScript1Partial='$RR("',completeBoundaryScript2='","',completeBoundaryScript3a='",',completeBoundaryScript3b='"',completeBoundaryScriptEnd=")</script>",clientRenderScriptFunctionOnly='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};',clientRenderScript1Full='$RX=function(b,c,d,e,f){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),f&&(a.cstck=f),b._reactRetry&&b._reactRetry())};;$RX("',clientRenderScript1Partial='$RX("',clientRenderScript1A='"',clientRenderErrorScriptArgInterstitial=",",clientRenderScriptEnd=")</script>",regexForJSStringsInInstructionScripts=/[<\u2028\u2029]/g,regexForJSStringsInScripts=/[&><\u2028\u2029]/g,lateStyleTagResourceOpen1=' media="not all" data-precedence="',lateStyleTagResourceOpen2='" data-href="',lateStyleTagResourceOpen3='">',lateStyleTagTemplateClose="</style>",currentlyRenderingBoundaryHasStylesToHoist=!1,destinationHasCapacity=!0,stylesheetFlushingQueue=[],styleTagResourceOpen1=' data-precedence="',styleTagResourceOpen2='" data-href="',spaceSeparator=" ",styleTagResourceOpen3='">',styleTagResourceClose="</style>",completedShellIdAttributeStart=' id="',arrayFirstOpenBracket="[",arraySubsequentOpenBracket=",[",arrayInterstitial=",",arrayCloseBracket="]",PENDING$1=0,PRELOADED=1,PREAMBLE=2,LATE=3,regexForHrefInLinkHeaderURLContext=/[<>\r\n]/g,regexForLinkHeaderQuotedParamValueContext=/["';,\r\n]/g,doctypeChunk="",bind=Function.prototype.bind,REACT_CLIENT_REFERENCE=Symbol.for("react.client.reference"),emptyContextObject={};Object.freeze(emptyContextObject);var rendererSigil={},currentActiveSnapshot=null,didWarnAboutNoopUpdateForComponent={},didWarnAboutDeprecatedWillMount={},didWarnAboutUninitializedState=new Set,didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate=new Set,didWarnAboutLegacyLifecyclesAndDerivedState=new Set,didWarnAboutDirectlyAssigningPropsToState=new Set,didWarnAboutUndefinedDerivedState=new Set,didWarnAboutContextTypes$1=new Set,didWarnAboutChildContextTypes=new Set,didWarnAboutInvalidateContextType=new Set,didWarnOnInvalidCallback=new Set,classComponentUpdater={enqueueSetState:function(inst,payload,callback){var internals=inst._reactInternals;internals.queue===null?warnNoop(inst,"setState"):(internals.queue.push(payload),callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback))},enqueueReplaceState:function(inst,payload,callback){inst=inst._reactInternals,inst.replace=!0,inst.queue=[payload],callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)},enqueueForceUpdate:function(inst,callback){inst._reactInternals.queue===null?warnNoop(inst,"forceUpdate"):callback!==void 0&&callback!==null&&warnOnInvalidCallback(callback)}},emptyTreeContext={id:1,overflow:""},clz32=Math.clz32?Math.clz32:clz32Fallback,{log,LN2}=Math,SuspenseException=Error("Suspense Exception: This is not a real error! It's an implementation detail of `use` to interrupt the current render. You must either rethrow it immediately, or move the `use` call outside of the `try/catch` block. Capturing without rethrowing will lead to unexpected behavior.\n\nTo handle async errors, wrap your component in an error boundary, or call the promise's `.catch` method and pass the result to `use`."),suspendedThenable=null,objectIs=typeof Object.is==="function"?Object.is:is,currentlyRenderingComponent=null,currentlyRenderingTask=null,currentlyRenderingRequest=null,currentlyRenderingKeyPath=null,firstWorkInProgressHook=null,workInProgressHook=null,isReRender=!1,didScheduleRenderPhaseUpdate=!1,localIdCounter=0,actionStateCounter=0,actionStateMatchingIndex=-1,thenableIndexCounter=0,thenableState=null,renderPhaseUpdates=null,numberOfReRenders=0,isInHookUserCodeInDev=!1,currentHookNameInDev,HooksDispatcher={readContext,use:function(usable){if(usable!==null&&typeof usable==="object"){if(typeof usable.then==="function")return unwrapThenable(usable);if(usable.$$typeof===REACT_CONTEXT_TYPE)return readContext(usable)}throw Error("An unsupported type was passed to use(): "+String(usable))},useContext:function(context){return currentHookNameInDev="useContext",resolveCurrentlyRenderingComponent(),context._currentValue2},useMemo,useReducer,useRef:function(initialValue){currentlyRenderingComponent=resolveCurrentlyRenderingComponent(),workInProgressHook=createWorkInProgressHook();var previousRef=workInProgressHook.memoizedState;return previousRef===null?(initialValue={current:initialValue},Object.seal(initialValue),workInProgressHook.memoizedState=initialValue):previousRef},useState:function(initialState){return currentHookNameInDev="useState",useReducer(basicStateReducer,initialState)},useInsertionEffect:noop,useLayoutEffect:noop,useCallback:function(callback,deps){return useMemo(function(){return callback},deps)},useImperativeHandle:noop,useEffect:noop,useDebugValue:noop,useDeferredValue:function(value,initialValue){return resolveCurrentlyRenderingComponent(),initialValue!==void 0?initialValue:value},useTransition:function(){return resolveCurrentlyRenderingComponent(),[!1,unsupportedStartTransition]},useId:function(){var treeId=currentlyRenderingTask.treeContext,overflow=treeId.overflow;treeId=treeId.id,treeId=(treeId&~(1<<32-clz32(treeId)-1)).toString(32)+overflow;var resumableState=currentResumableState;if(resumableState===null)throw Error("Invalid hook call. Hooks can only be called inside of the body of a function component.");return overflow=localIdCounter++,treeId="_"+resumableState.idPrefix+"R_"+treeId,0<overflow&&(treeId+="H"+overflow.toString(32)),treeId+"_"},useSyncExternalStore:function(subscribe,getSnapshot,getServerSnapshot){if(getServerSnapshot===void 0)throw Error("Missing getServerSnapshot, which is required for server-rendered content. Will revert to client rendering.");return getServerSnapshot()},useOptimistic:function(passthrough){return resolveCurrentlyRenderingComponent(),[passthrough,unsupportedSetOptimisticState]},useActionState,useFormState:useActionState,useHostTransitionStatus:function(){return resolveCurrentlyRenderingComponent(),NotPending},useMemoCache:function(size){for(var data=Array(size),i=0;i<size;i++)data[i]=REACT_MEMO_CACHE_SENTINEL;return data},useCacheRefresh:function(){return unsupportedRefresh},useEffectEvent:function(){return throwOnUseEffectEventCall}},currentResumableState=null,currentTaskInDEV=null,DefaultAsyncDispatcher={getCacheForType:function(){throw Error("Not implemented.")},cacheSignal:function(){throw Error("Not implemented.")},getOwner:function(){return currentTaskInDEV===null?null:currentTaskInDEV.componentStack}},disabledDepth=0,prevLog,prevInfo,prevWarn,prevError,prevGroup,prevGroupCollapsed,prevGroupEnd;disabledLog.__reactDisabledLog=!0;var prefix,suffix,reentry=!1,componentFrameCache=new(typeof WeakMap==="function"?WeakMap:Map),callComponent={react_stack_bottom_frame:function(Component,props,secondArg){return Component(props,secondArg)}},callComponentInDEV=callComponent.react_stack_bottom_frame.bind(callComponent),callRender={react_stack_bottom_frame:function(instance){return instance.render()}},callRenderInDEV=callRender.react_stack_bottom_frame.bind(callRender),callLazyInit={react_stack_bottom_frame:function(lazy){var init=lazy._init;return init(lazy._payload)}},callLazyInitInDEV=callLazyInit.react_stack_bottom_frame.bind(callLazyInit),lastResetTime=0;if(typeof performance==="object"&&typeof performance.now==="function")var localPerformance=performance,getCurrentTime=function(){return localPerformance.now()};else{var localDate=Date;getCurrentTime=function(){return localDate.now()}}var CLIENT_RENDERED=4,PENDING=0,COMPLETED=1,FLUSHED=2,ABORTED=3,ERRORED=4,POSTPONED=5,CLOSED=14,currentRequest=null,didWarnAboutBadClass={},didWarnAboutContextTypes={},didWarnAboutContextTypeOnFunctionComponent={},didWarnAboutGetDerivedStateOnFunctionComponent={},didWarnAboutReassigningProps=!1,didWarnAboutGenerators=!1,didWarnAboutMaps=!1,flushedByteSize=0,flushingPartialBoundaries=!1;exports.renderToStaticMarkup=function(children,options){return renderToStringImpl(children,options,!0,'The server used "renderToStaticMarkup" which does not support Suspense. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.renderToString=function(children,options){return renderToStringImpl(children,options,!1,'The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToReadableStream" which supports Suspense on the server')},exports.version="19.2.8"})()});var TAILWIND_CLASSNAME={kind:"tailwind-classname",prop:"className",needsTailwindJit:!0,editorLabel:"Tailwind classes"},SX_PROP={kind:"sx",prop:"sx",needsTailwindJit:!1,editorLabel:"sx props"},STYLE_PROP={kind:"style",prop:"style",needsTailwindJit:!1,editorLabel:"Inline styles"},STYLE_CHANNELS={"tailwind-classname":TAILWIND_CLASSNAME,sx:SX_PROP,style:STYLE_PROP},CSS_FRAMEWORK_CHANNEL={tailwind:"tailwind-classname",none:"style"};function catalogFromManifest(manifest,opts){return manifest.map((descriptor)=>({id:descriptor.id,installed:opts.installed??!0,importPath:opts.importPath}))}function identifierRef(path){if(!/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(path))throw Error(`identifierRef: "${path}" is not a bare identifier path`);return{$identifier:path}}function styleChannelOf(p,folderCss){let adapter=p,allowed=adapter.styleChannels??[adapter.styleChannel?.kind??"tailwind-classname"],fallback=allowed[0]??"tailwind-classname";if(folderCss){let wanted=CSS_FRAMEWORK_CHANNEL[folderCss];if(allowed.includes(wanted))return STYLE_CHANNELS[wanted]}return STYLE_CHANNELS[fallback]}class UnknownProviderError extends Error{id;constructor(id,message){super(message??`Unknown component provider: "${id}"`);this.name="UnknownProviderError",this.id=id}}function createProviderLoader(factories){return async(library)=>{let factory=factories[library.id];if(!factory){let known=Object.keys(factories).sort();throw new UnknownProviderError(library.id,`Unknown component provider: "${library.id}". Known providers: ${known.join(", ")}.`)}return factory(library)}}var COMPONENT_GROUPS=[{id:"actions",label:"Actions"},{id:"forms",label:"Forms & Inputs"},{id:"display",label:"Display"},{id:"feedback",label:"Feedback"},{id:"navigation",label:"Navigation"},{id:"overlays",label:"Overlays"},{id:"layout",label:"Layout"},{id:"typography",label:"Typography"},{id:"visuals",label:"Visuals"},{id:"chat",label:"Chat & AI"}],UNGROUPED_LABEL="Components";function ownEntry(record,key){return Object.hasOwn(record,key)?record[key]:void 0}function lookup(library,ref,node){return typeof library==="function"?library(ref,node):ownEntry(library,ref)}function resolveNodeIdentity(value,ctx){let shape=nodeShape(value);if(shape.kind!=="named")return shape;let{node,ref}=shape,extension=ctx.extensions?ownEntry(ctx.extensions,ref):void 0;if(extension)return{kind:"extension",node,ref,extension};let entry=lookup(ctx.library,ref,node);if(entry===void 0)return{kind:"unresolved",node,ref};return{kind:"component",node,ref,entry}}import{existsSync,readdirSync}from"fs";import{join}from"path";var package_default={name:"@velloo/renderer",version:"0.0.0",license:"Apache-2.0",private:!0,type:"module",description:"Headless renderer: design JSON \u2192 HTML + screenshot",exports:{".":"./src/index.ts","./iframe-protocol":"./src/iframe-protocol.ts"},dependencies:{"@velloo/provider":"workspace:*","@velloo/schema":"workspace:*",pixelmatch:"7.2.0",pngjs:"7.0.0",react:"19.2.8","react-dom":"19.2.8"},devDependencies:{"@types/pngjs":"6.0.5","@types/react":"19.2.18","@types/react-dom":"19.2.7","@velloo/shadcn-snapshot":"workspace:*",playwright:"1.62.1","playwright-core":"1.62.1"}};var PLAYWRIGHT_VERSION=package_default.devDependencies["playwright-core"],PLAYWRIGHT_PIN=`playwright@${PLAYWRIGHT_VERSION}`,CHROMIUM_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium","--only-shell"],CHROMIUM_INSTALL_CMD="velloo browser install",CHROMIUM_FULL_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install","chromium"],CHROMIUM_FULL_INSTALL_CMD="velloo browser install --full",CHROMIUM_DEPS_INSTALL_ARGV=[process.execPath,"x",PLAYWRIGHT_PIN,"install-deps","chromium"],CHROMIUM_DEPS_INSTALL_CMD="velloo browser install --with-deps",INSTALL_HINT=`Velloo screenshots need a headless browser. Install it once with:
80
80
  ${CHROMIUM_INSTALL_CMD}
81
81
  `+"Then just retry the tool \u2014 the browser is picked up on the next call, no server restart needed. "+"(It's an on-demand extra; the canvas itself never needs it.)";class BrowserMissingError extends Error{constructor(message=INSTALL_HINT){super(message);this.name="BrowserMissingError"}}async function chromiumExecutable(){try{let{chromium}=await import("playwright-core"),path=chromium.executablePath();if(!path)return null;if(existsSync(path))return path;let m=path.match(/^(.*)[/\\]chromium-(\d+)[/\\]/);if(!m?.[1]||!m[2])return null;let shellRoot=join(m[1],`chromium_headless_shell-${m[2]}`);if(!existsSync(shellRoot))return null;let bin=process.platform==="win32"?"chrome-headless-shell.exe":"chrome-headless-shell";for(let sub of readdirSync(shellRoot)){let candidate=join(shellRoot,sub,bin);if(existsSync(candidate))return candidate}return null}catch{return null}}async function launchBrowser(){let chromium;try{({chromium}=await import("playwright-core"))}catch{throw new BrowserMissingError}try{return await chromium.launch()}catch(e){let msg=e instanceof Error?e.message:String(e);if(/Executable doesn't exist|playwright install|browserType\.launch/i.test(msg))throw new BrowserMissingError;let firstLine=msg.split(`
82
82
  `).find((l)=>l.trim()!=="")?.trim()??msg;throw new BrowserMissingError(`Chromium failed to launch: ${firstLine}
@@ -84,7 +84,7 @@ If the browser isn't installed, run:
84
84
  ${CHROMIUM_INSTALL_CMD}
85
85
  Then retry \u2014 no server restart needed.`)}}var MAX_CONCURRENT_RENDERS=3,renderSlots=MAX_CONCURRENT_RENDERS,renderQueue=[];async function acquireRenderSlot(){if(renderSlots>0)renderSlots-=1;else await new Promise((resolve)=>renderQueue.push(resolve));let released=!1;return()=>{if(released)return;released=!0;let next=renderQueue.shift();if(next)next();else renderSlots+=1}}var pooledBrowser=null,browserLaunch=null;async function closePooledBrowser(){let browser=pooledBrowser??(browserLaunch?await browserLaunch.catch(()=>null):null);pooledBrowser=null,await browser?.close().catch(()=>{return})}async function pooledChromium(){if(pooledBrowser?.isConnected())return pooledBrowser;if(!browserLaunch)browserLaunch=launchBrowser().then((b)=>(pooledBrowser=b,b.on("disconnected",()=>{if(pooledBrowser===b)pooledBrowser=null}),b)).finally(()=>{browserLaunch=null});return browserLaunch}function isBrowserGone(err){let m=err instanceof Error?err.message:String(err);return/has been closed|Target closed|browser closed|Connection closed|crashed/i.test(m)}async function withContext(options,fn){let release=await acquireRenderSlot();try{return await runInContext(options,fn)}catch(err){if(!isBrowserGone(err))throw err;return pooledBrowser=null,await runInContext(options,fn)}finally{release()}}async function runInContext(options,fn){let context=await(await pooledChromium()).newContext(options);try{return await fn(context)}finally{await context.close().catch(()=>{return})}}var CAPTURE_TIMEOUT_MS=20000;function isCaptureTimeout(err){return err instanceof Error&&err.name==="TimeoutError"}import{createHash}from"crypto";import{existsSync as existsSync2,mkdirSync,readdirSync as readdirSync2,readFileSync,realpathSync,rmSync,statSync,writeFileSync}from"fs";import{homedir}from"os";import{join as join2,resolve}from"path";var SECOND_LEVEL_SUFFIXES=new Set(["ac","asn","biz","co","com","edu","gov","govt","id","in","info","int","ltd","me","mil","ne","net","nom","or","org","plc","sch","web"]);function isHostLiteral(host){if(host.includes(":"))return!0;if(/^\d+(\.\d+){3}$/.test(host))return!0;return!host.includes(".")}function registrableDomain(host){let h=host.replace(/^\.+/,"").toLowerCase();if(isHostLiteral(h))return h;let labels=h.split(".").filter((l)=>l.length>0);if(labels.length<=2)return labels.join(".");let tld=labels[labels.length-1]??"",sld=labels[labels.length-2]??"",take=tld.length<=3&&SECOND_LEVEL_SUFFIXES.has(sld)?3:2;return labels.slice(-take).join(".")}function withinRegistrableDomain(host,base){let h=host.replace(/^\.+/,"").toLowerCase();return h===base||h.endsWith(`.${base}`)}function scopeStorageState(state,capturedOrigins,now=Date.now()){let bases=new Set;for(let origin of capturedOrigins)try{bases.add(registrableDomain(new URL(origin).hostname))}catch{}let nowSec=Math.floor(now/1000),cookies=state.cookies.filter((c)=>{if(c.expires!==-1&&c.expires<=nowSec)return!1;let host=c.domain.replace(/^\./,"").toLowerCase();for(let base of bases)if(withinRegistrableDomain(host,base))return!0;return!1}),origins=state.origins.filter((o)=>{try{let host=new URL(o.origin).hostname;for(let base of bases)if(withinRegistrableDomain(host,base))return!0}catch{return!1}return!1});return{cookies,origins}}var SESSION_TTL_MS=1209600000;function sessionExpired(writtenAt,now=Date.now()){return now-writtenAt>SESSION_TTL_MS}function vellooHome(){return process.env.VELLOO_HOME??join2(homedir(),".velloo")}function folderKey(root,folderId){if(folderId)return folderId;let real=root;try{real=realpathSync(root)}catch{real=resolve(root)}return createHash("sha256").update(real).digest("hex").slice(0,16)}function capturesDir(root,folderId){return join2(vellooHome(),"captures",folderKey(root,folderId))}function sessionsDir(root,folderId){return join2(vellooHome(),"sessions",folderKey(root,folderId))}function sessionStatePath(root,origin,folderId){let key=createHash("sha256").update(origin).digest("hex").slice(0,12);return join2(sessionsDir(root,folderId),`${key}.json`)}var MANIFEST="capture.json";function ensureDir(dir){mkdirSync(dir,{recursive:!0,mode:448})}function captureDir(root,id,folderId){return join2(capturesDir(root,folderId),id)}function writeCaptureManifest(dir,manifest){ensureDir(dir),writeFileSync(join2(dir,MANIFEST),`${JSON.stringify(manifest,null,2)}
86
86
  `,{mode:384})}function listCaptures(root,folderId){let dir=capturesDir(root,folderId);if(!existsSync2(dir))return[];let out=[];for(let entry of readdirSync2(dir))try{let raw=readFileSync(join2(dir,entry,MANIFEST),"utf8");out.push(JSON.parse(raw))}catch{}return out.sort((a,b)=>b.capturedAt.localeCompare(a.capturedAt))}function readCaptureManifest(root,id,folderId){try{let raw=readFileSync(join2(captureDir(root,id,folderId),MANIFEST),"utf8");return JSON.parse(raw)}catch{return null}}function deleteCapture(root,id,folderId){if(!isSafeCaptureId(id))return!1;let dir=captureDir(root,id,folderId);if(!existsSync2(dir))return!1;return rmSync(dir,{recursive:!0,force:!0}),!0}function isSafeCaptureId(id){return/^[A-Za-z0-9_-]{1,64}$/.test(id)}function isSafeCaptureFile(file){return/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(file)&&!file.includes("..")}function newCaptureId(){return`${new Date().toISOString().replace(/[-:.TZ]/g,"").slice(0,14)}-${createHash("sha256").update(`${Math.random()}${Date.now()}`).digest("hex").slice(0,6)}`}function writeSessionState(path,state,capturedOrigins){let scoped=scopeStorageState(state,capturedOrigins);return ensureDir(join2(path,"..")),writeFileSync(path,`${JSON.stringify(scoped,null,2)}
87
- `,{mode:384}),path}function readSessionState(path){try{if(!existsSync2(path))return null;let age=statSync(path).mtimeMs;if(sessionExpired(age))return rmSync(path,{force:!0}),null;let parsed=JSON.parse(readFileSync(path,"utf8"));if(!Array.isArray(parsed.cookies)||!Array.isArray(parsed.origins))return null;return parsed}catch{return null}}import{randomBytes}from"crypto";import{existsSync as existsSync3,mkdirSync as mkdirSync3}from"fs";import{createHash as createHash2}from"crypto";import{mkdirSync as mkdirSync2,writeFileSync as writeFileSync2}from"fs";import{join as join3}from"path";function pixelmatch(img1,img2,output,width,height,options={}){let{threshold=0.1,alpha=0.1,aaColor=[255,255,0],diffColor=[255,0,0],checkerboard=!0,includeAA,diffColorAlt,diffMask}=options;if(!isPixelData(img1)||!isPixelData(img2)||output&&!isPixelData(output))throw Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(img1.length!==img2.length||output&&output.length!==img1.length)throw Error(`Image sizes do not match. Image 1 size: ${img1.length}, image 2 size: ${img2.length}`);if(img1.length!==width*height*4)throw Error(`Image data size does not match width/height. Expecting ${width*height*4}. Got ${img1.length}`);let len=width*height,a32=new Uint32Array(img1.buffer,img1.byteOffset,len),b32=new Uint32Array(img2.buffer,img2.byteOffset,len),identical=!0;for(let i=0;i<len;i++)if(a32[i]!==b32[i]){identical=!1;break}if(identical){if(output&&!diffMask)for(let i=0,pos=0;i<len;i++,pos+=4)drawGrayPixel(img1,pos,alpha,output);return 0}let maxDelta=35215*threshold*threshold,[aaR,aaG,aaB]=aaColor,[diffR,diffG,diffB]=diffColor,[altR,altG,altB]=diffColorAlt||diffColor,diff=0;for(let i=0,pos=0;i<len;i++,pos+=4){let delta=a32[i]===b32[i]?0:colorDelta(img1,img2,pos,pos,checkerboard);if(Math.abs(delta)>maxDelta){let x=i%width,y=i/width|0;if(!includeAA&&(antialiased(img1,x,y,width,height,a32,b32,checkerboard)||antialiased(img2,x,y,width,height,b32,a32,checkerboard))){if(output&&!diffMask)drawPixel(output,pos,aaR,aaG,aaB)}else{if(output)if(delta<0)drawPixel(output,pos,altR,altG,altB);else drawPixel(output,pos,diffR,diffG,diffB);diff++}}else if(output&&!diffMask)drawGrayPixel(img1,pos,alpha,output)}return diff}function isPixelData(arr){return ArrayBuffer.isView(arr)&&arr.BYTES_PER_ELEMENT===1}function antialiased(img,x1,y1,width,height,a32,b32,checkerboard){let x0=Math.max(x1-1,0),y0=Math.max(y1-1,0),x2=Math.min(x1+1,width-1),y2=Math.min(y1+1,height-1),pos4=(y1*width+x1)*4,cr=img[pos4],cg=img[pos4+1],cb=img[pos4+2],ca=img[pos4+3],zeroes=x1===x0||x1===x2||y1===y0||y1===y2?1:0,min=0,max=0,minX=0,minY=0,maxX=0,maxY=0;for(let x=x0;x<=x2;x++)for(let y=y0;y<=y2;y++){if(x===x1&&y===y1)continue;let delta=brightnessDelta(img,pos4,(y*width+x)*4,cr,cg,cb,ca,checkerboard);if(delta===0){if(zeroes++,zeroes>2)return!1}else if(delta<min)min=delta,minX=x,minY=y;else if(delta>max)max=delta,maxX=x,maxY=y}if(min===0||max===0)return!1;return hasManySiblings(a32,minX,minY,width,height)&&hasManySiblings(b32,minX,minY,width,height)||hasManySiblings(a32,maxX,maxY,width,height)&&hasManySiblings(b32,maxX,maxY,width,height)}function hasManySiblings(img,x1,y1,width,height){let x0=Math.max(x1-1,0),y0=Math.max(y1-1,0),x2=Math.min(x1+1,width-1),y2=Math.min(y1+1,height-1),val=img[y1*width+x1],zeroes=x1===x0||x1===x2||y1===y0||y1===y2?1:0;for(let x=x0;x<=x2;x++)for(let y=y0;y<=y2;y++){if(x===x1&&y===y1)continue;if(zeroes+=+(val===img[y*width+x]),zeroes>2)return!0}return!1}function colorDelta(img1,img2,k,m,checkerboard){let r1=img1[k],g1=img1[k+1],b1=img1[k+2],a1=img1[k+3],r2=img2[m],g2=img2[m+1],b2=img2[m+2],a2=img2[m+3],dr=r1-r2,dg=g1-g2,db=b1-b2,da=a1-a2;if(a1<255||a2<255){let rb=255,gb=255,bb=255;if(checkerboard)rb=48+159*(k%2),gb=48+159*((k/1.618033988749895|0)%2),bb=48+159*((k/2.618033988749895|0)%2);dr=(r1*a1-r2*a2-rb*da)/255,dg=(g1*a1-g2*a2-gb*da)/255,db=(b1*a1-b2*a2-bb*da)/255}let y=dr*0.29889531+dg*0.58662247+db*0.11448223,i=dr*0.59597799-dg*0.2741761-db*0.32180189,q=dr*0.21147017-dg*0.52261711+db*0.31114694,delta=0.5053*y*y+0.299*i*i+0.1957*q*q;return y>0?-delta:delta}function brightnessDelta(img,k,m,r1,g1,b1,a1,checkerboard){let r2=img[m],g2=img[m+1],b2=img[m+2],a2=img[m+3],dr=r1-r2,dg=g1-g2,db=b1-b2,da=a1-a2;if(!dr&&!dg&&!db&&!da)return 0;if(a1<255||a2<255){let rb=255,gb=255,bb=255;if(checkerboard)rb=48+159*(k%2),gb=48+159*((k/1.618033988749895|0)%2),bb=48+159*((k/2.618033988749895|0)%2);dr=(r1*a1-r2*a2-rb*da)/255,dg=(g1*a1-g2*a2-gb*da)/255,db=(b1*a1-b2*a2-bb*da)/255}return dr*0.29889531+dg*0.58662247+db*0.11448223}function drawPixel(output,pos,r,g,b){output[pos]=r,output[pos+1]=g,output[pos+2]=b,output[pos+3]=255}function drawGrayPixel(img,i,alpha,output){let val=255+(img[i]*0.29889531+img[i+1]*0.58662247+img[i+2]*0.11448223-255)*alpha*img[i+3]/255;drawPixel(output,i,val,val,val)}var import_pngjs=__toESM(require_png(),1);function padToUnion(png,width,height){if(png.width===width&&png.height===height)return png;let out=new import_pngjs.PNG({width,height,fill:!0});return import_pngjs.PNG.bitblt(png,out,0,0,png.width,png.height,0,0),out}function clusterRegions(mask,width,height,cellSize,maxRegions){let cols=Math.ceil(width/cellSize),rows=Math.ceil(height/cellSize),dirty=new Uint8Array(cols*rows);for(let y=0;y<height;y++)for(let x=0;x<width;x++)if(mask[y*width+x])dirty[Math.floor(y/cellSize)*cols+Math.floor(x/cellSize)]=1;let seen=new Uint8Array(cols*rows),regions=[];for(let cy=0;cy<rows;cy++)for(let cx=0;cx<cols;cx++){let idx=cy*cols+cx;if(!dirty[idx]||seen[idx])continue;let minX=cx,maxX=cx,minY=cy,maxY=cy,queue=[idx];seen[idx]=1;while(queue.length>0){let cur=queue.pop(),x=cur%cols,y=Math.floor(cur/cols);minX=Math.min(minX,x),maxX=Math.max(maxX,x),minY=Math.min(minY,y),maxY=Math.max(maxY,y);for(let[dx,dy]of[[1,0],[-1,0],[0,1],[0,-1]]){let nx=x+dx,ny=y+dy;if(nx<0||ny<0||nx>=cols||ny>=rows)continue;let nIdx=ny*cols+nx;if(dirty[nIdx]&&!seen[nIdx])seen[nIdx]=1,queue.push(nIdx)}}regions.push({x:minX*cellSize,y:minY*cellSize,w:Math.min((maxX+1)*cellSize,width)-minX*cellSize,h:Math.min((maxY+1)*cellSize,height)-minY*cellSize})}if(regions.sort((a,b)=>b.w*b.h-a.w*a.h),regions.length>maxRegions){let tail=regions.slice(maxRegions-1),minX=Math.min(...tail.map((r)=>r.x)),minY=Math.min(...tail.map((r)=>r.y)),maxX=Math.max(...tail.map((r)=>r.x+r.w)),maxY=Math.max(...tail.map((r)=>r.y+r.h));return[...regions.slice(0,maxRegions-1),{x:minX,y:minY,w:maxX-minX,h:maxY-minY}]}return regions}function diffPngs(before,after,options={}){let a=import_pngjs.PNG.sync.read(before),b=import_pngjs.PNG.sync.read(after),width=Math.max(a.width,b.width),height=Math.max(a.height,b.height),pa=padToUnion(a,width,height),pb=padToUnion(b,width,height),diff=new import_pngjs.PNG({width,height}),changedPixels=pixelmatch(pa.data,pb.data,diff.data,width,height,{threshold:options.threshold??0.1,includeAA:!1,alpha:0.6}),mask=new Uint8Array(width*height);if(changedPixels>0){let d=diff.data;for(let i=0;i<width*height;i++){let r=d[i*4],g=d[i*4+1],bch=d[i*4+2];if(r>200&&g<120&&bch<120)mask[i]=1}}let regions=changedPixels===0?[]:clusterRegions(mask,width,height,options.cellSize??16,options.maxRegions??10);for(let r of regions){let n=0;for(let y=r.y;y<r.y+r.h;y++){let row=y*width;for(let x=r.x;x<r.x+r.w;x++)n+=mask[row+x]}r.changedPixels=n}regions.sort((a,b)=>(b.changedPixels??0)-(a.changedPixels??0));let contentHeight=Math.min(a.height,b.height),contentLen=width*contentHeight*4,contentChangedPixels=contentHeight===height?changedPixels:pixelmatch(pa.data.subarray(0,contentLen),pb.data.subarray(0,contentLen),void 0,width,contentHeight,{threshold:options.threshold??0.1,includeAA:!1,alpha:0.6});return{changedPixels,changedRatio:changedPixels/(width*height),alignedChangedRatio:changedPixels===0?0:alignedChanged(pa.data,pb.data,mask,width,height,options.threshold??0.1)/(width*height),contentChangedRatio:contentChangedPixels/(width*contentHeight),heightDelta:b.height-a.height,width,height,regions,diffPng:import_pngjs.PNG.sync.write(diff)}}function alignedChanged(a,b,mask,width,height,threshold){let maxDelta=35215*threshold*threshold,remaining=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){if(!mask[y*width+x])continue;let here=(y*width+x)*4,matched=!1;for(let dy=-1;dy<=1&&!matched;dy++){let ny=y+dy;if(ny<0||ny>=height)continue;for(let dx=-1;dx<=1&&!matched;dx++){let nx=x+dx;if(nx<0||nx>=width||dx===0&&dy===0)continue;let there=(ny*width+nx)*4;if(colorDelta2(b,a,here,there)<=maxDelta)matched=!0;else if(colorDelta2(a,b,here,there)<=maxDelta)matched=!0}}if(!matched)remaining++}return remaining}function colorDelta2(a,b,ai,bi){let r1=a[ai],g1=a[ai+1],b1=a[ai+2],r2=b[bi],g2=b[bi+1],b2=b[bi+2],y=0.29889531*(r1-r2)+0.58662247*(g1-g2)+0.11448223*(b1-b2),i=0.59597799*(r1-r2)-0.2741761*(g1-g2)-0.32180189*(b1-b2),q=0.21147017*(r1-r2)-0.52261711*(g1-g2)+0.31114694*(b1-b2);return 0.5053*y*y+0.299*i*i+0.1957*q*q}function downscalePng(png,factor){if(!Number.isInteger(factor)||factor<=1)return png;let src=import_pngjs.PNG.sync.read(png),width=Math.max(1,Math.floor(src.width/factor)),height=Math.max(1,Math.floor(src.height/factor)),out=new import_pngjs.PNG({width,height});for(let y=0;y<height;y++)for(let x=0;x<width;x++){let r=0,g=0,b=0,a=0,n=0;for(let dy=0;dy<factor;dy++){let sy=y*factor+dy;if(sy>=src.height)break;for(let dx=0;dx<factor;dx++){let sx=x*factor+dx;if(sx>=src.width)break;let i=sy*src.width+sx<<2;r+=src.data[i]??0,g+=src.data[i+1]??0,b+=src.data[i+2]??0,a+=src.data[i+3]??0,n++}}let o=y*width+x<<2;out.data[o]=Math.round(r/n),out.data[o+1]=Math.round(g/n),out.data[o+2]=Math.round(b/n),out.data[o+3]=Math.round(a/n)}return import_pngjs.PNG.sync.write(out)}function resizePng(png,width,height){let src=import_pngjs.PNG.sync.read(png),outWidth=Math.max(1,Math.round(width)),outHeight=Math.max(1,Math.round(height));if(src.width===outWidth&&src.height===outHeight)return png;let out=new import_pngjs.PNG({width:outWidth,height:outHeight});for(let y=0;y<outHeight;y++){let sy=Math.max(0,Math.min(src.height-1,(y+0.5)*src.height/outHeight-0.5)),y0=Math.floor(sy),y1=Math.min(src.height-1,y0+1),fy=sy-y0;for(let x=0;x<outWidth;x++){let sx=Math.max(0,Math.min(src.width-1,(x+0.5)*src.width/outWidth-0.5)),x0=Math.floor(sx),x1=Math.min(src.width-1,x0+1),fx=sx-x0,dst=y*outWidth+x<<2;for(let channel=0;channel<4;channel++){let a=src.data[(y0*src.width+x0)*4+channel]??0,b=src.data[(y0*src.width+x1)*4+channel]??0,c=src.data[(y1*src.width+x0)*4+channel]??0,d=src.data[(y1*src.width+x1)*4+channel]??0,top=a+(b-a)*fx,bottom=c+(d-c)*fx;out.data[dst+channel]=Math.round(top+(bottom-top)*fy)}}}return import_pngjs.PNG.sync.write(out)}function pngSize(png){let p=import_pngjs.PNG.sync.read(png);return{width:p.width,height:p.height}}function cropPng(png,region,pad=24){let src=import_pngjs.PNG.sync.read(png),x=Math.max(0,region.x-pad),y=Math.max(0,region.y-pad),w=Math.min(src.width-x,region.w+pad*2),h=Math.min(src.height-y,region.h+pad*2),out=new import_pngjs.PNG({width:w,height:h});return import_pngjs.PNG.bitblt(src,out,x,y,w,h,0,0),import_pngjs.PNG.sync.write(out)}function sideBySidePng(left,right,gutter=12){let a=import_pngjs.PNG.sync.read(left),b=import_pngjs.PNG.sync.read(right),width=a.width+gutter+b.width,height=Math.max(a.height,b.height),out=new import_pngjs.PNG({width,height});return out.data.fill(255),import_pngjs.PNG.bitblt(a,out,0,0,a.width,a.height,0,0),import_pngjs.PNG.bitblt(b,out,0,0,b.width,b.height,a.width+gutter,0),import_pngjs.PNG.sync.write(out)}function unionRegion(regions){let minX=Math.min(...regions.map((r)=>r.x)),minY=Math.min(...regions.map((r)=>r.y)),maxX=Math.max(...regions.map((r)=>r.x+r.w)),maxY=Math.max(...regions.map((r)=>r.y+r.h));return{x:minX,y:minY,w:maxX-minX,h:maxY-minY}}var TOOLBAR_TAG="velloo-capture-toolbar",MAX_NODES=20000,MAX_DEPTH=24,MAX_TEXT=240,TRANSIENT_SCREENSHOT_ERROR=/Protocol error \(Page\.captureScreenshot\):\s*Unable to capture screenshot/i;async function capturePagePng(page,fullPage){let screenshot=()=>page.screenshot({fullPage,animations:"disabled",caret:"hide"});try{return await screenshot()}catch(err){let message=err instanceof Error?err.message:String(err);if(!TRANSIENT_SCREENSHOT_ERROR.test(message))throw err;return await new Promise((resolve)=>setTimeout(resolve,100)),await screenshot()}}var STYLE_PROPS=["display","position","flexDirection","flexWrap","alignItems","justifyContent","gap","gridTemplateColumns","padding","margin","width","maxWidth","height","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","textAlign","textTransform","color","backgroundColor","backgroundImage","borderRadius","borderWidth","borderColor","borderStyle","boxShadow","opacity","zIndex"];async function extractDom(page,limits={maxNodes:MAX_NODES,maxDepth:MAX_DEPTH,maxText:MAX_TEXT},toolbarTag=TOOLBAR_TAG){return page.evaluate(({props,maxNodes,maxDepth,maxText,toolbar})=>{let nodes=[],truncated=!1,ownText=(el)=>{let s="";for(let child of Array.from(el.childNodes))if(child.nodeType===3)s+=child.textContent??"";return s.replace(/\s+/g," ").trim().slice(0,maxText)},signatureOf=(el)=>{let cls=(el.getAttribute("class")??"").trim();return`${el.tagName.toLowerCase()}|${cls}|${el.children.length}`},walk=(el,parent,depth)=>{if(nodes.length>=maxNodes){truncated=!0;return}if(depth>maxDepth){truncated=!0;return}if(el.tagName.toLowerCase()===toolbar)return;let cs=getComputedStyle(el);if(cs.display==="none"||cs.visibility==="hidden")return;let r=el.getBoundingClientRect(),scrollX2=window.scrollX,scrollY2=window.scrollY;if(r.width===0&&r.height===0)return;let style={};for(let p of props){let v=cs[p];if(typeof v==="string"&&v!==""&&v!=="none"&&v!=="normal")style[p]=v}let i=nodes.length,entry={i,parent,depth,tag:el.tagName.toLowerCase(),rect:{x:Math.round(r.x+scrollX2),y:Math.round(r.y+scrollY2),w:Math.round(r.width),h:Math.round(r.height)},style},id=el.getAttribute("id");if(id)entry.id=id;let cls=el.getAttribute("class");if(cls)entry.class=cls.trim().slice(0,400);let role=el.getAttribute("role")??el.getAttribute("aria-label");if(role)entry.role=role;let t=ownText(el);if(t)entry.text=t;let src=el.getAttribute("src");if(src)entry.src=src;let href=el.getAttribute("href");if(href)entry.href=href.slice(0,300);let nodePath=el.getAttribute("data-node-path");if(nodePath!==null)entry.nodePath=nodePath;nodes.push(entry);let children=Array.from(el.children),counts=new Map;for(let c of children){let sig=signatureOf(c);counts.set(sig,(counts.get(sig)??0)+1)}let seen=new Set;for(let c of children){let before=nodes.length;walk(c,i,depth+1);let sig=signatureOf(c),n=counts.get(sig)??0;if(n>=3&&!seen.has(sig)&&nodes.length>before){seen.add(sig);let added=nodes[before];if(added)added.repeat={count:n,signature:sig}}}};if(document.body)walk(document.body,null,0);return{url:location.href,title:document.title,viewport:{w:window.innerWidth,h:window.innerHeight},documentHeight:Math.max(document.documentElement?.scrollHeight??0,document.body?.scrollHeight??0),nodes,truncated}},{props:STYLE_PROPS,maxNodes:limits.maxNodes,maxDepth:limits.maxDepth,maxText:limits.maxText,toolbar:toolbarTag})}async function extractThemeVars(page){return page.evaluate(()=>{let light={},dark={},fonts=new Set,isDarkSelector=(sel)=>/(^|[\s,>])(\.dark|\[data-theme["'=\s]*dark|\.theme-dark)/i.test(sel),readRule=(rule,intoDark)=>{let{style,selectorText:selector}=rule;if(!style||typeof selector!=="string")return;if(!/(^|,)\s*(:root|html|body|\.dark|\[data-theme)/i.test(selector))return;let target=intoDark||isDarkSelector(selector)?dark:light;for(let i=0;i<style.length;i++){let prop=style.item(i);if(!prop.startsWith("--"))continue;let value=style.getPropertyValue(prop).trim();if(value)target[prop]=value}let ff=style.getPropertyValue("font-family").trim();if(ff)fonts.add(ff)},walkRules=(rules,intoDark)=>{for(let rule of Array.from(rules)){let asStyle=rule;if(typeof asStyle.selectorText==="string"&&asStyle.style)readRule(rule,intoDark);let nested=rule.cssRules;if(nested&&nested.length>0){let cond=rule instanceof CSSConditionRule?rule.conditionText:"";walkRules(nested,intoDark||/prefers-color-scheme\s*:\s*dark/i.test(cond))}}};for(let sheet of Array.from(document.styleSheets))try{let rules=sheet.cssRules;if(rules)walkRules(rules,!1)}catch{}let rootStyle=getComputedStyle(document.documentElement);for(let prop of Array.from(rootStyle)){if(!prop.startsWith("--"))continue;if(light[prop]!==void 0)continue;let value=rootStyle.getPropertyValue(prop).trim();if(value)light[prop]=value}let bodyFont=getComputedStyle(document.body??document.documentElement).fontFamily;if(bodyFont)fonts.add(bodyFont);let block=(sel,vars)=>{let entries=Object.entries(vars);if(entries.length===0)return"";return`${sel} {
87
+ `,{mode:384}),path}function readSessionState(path){try{if(!existsSync2(path))return null;let age=statSync(path).mtimeMs;if(sessionExpired(age))return rmSync(path,{force:!0}),null;let parsed=JSON.parse(readFileSync(path,"utf8"));if(!Array.isArray(parsed.cookies)||!Array.isArray(parsed.origins))return null;return parsed}catch{return null}}import{randomBytes}from"crypto";import{existsSync as existsSync3,mkdirSync as mkdirSync3}from"fs";import{createHash as createHash2}from"crypto";import{mkdirSync as mkdirSync2,writeFileSync as writeFileSync2}from"fs";import{join as join3}from"path";function pixelmatch(img1,img2,output,width,height,options={}){let{threshold=0.1,alpha=0.1,aaColor=[255,255,0],diffColor=[255,0,0],checkerboard=!0,includeAA,diffColorAlt,diffMask}=options;if(!isPixelData(img1)||!isPixelData(img2)||output&&!isPixelData(output))throw Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");if(img1.length!==img2.length||output&&output.length!==img1.length)throw Error(`Image sizes do not match. Image 1 size: ${img1.length}, image 2 size: ${img2.length}`);if(img1.length!==width*height*4)throw Error(`Image data size does not match width/height. Expecting ${width*height*4}. Got ${img1.length}`);let len=width*height,a32=new Uint32Array(img1.buffer,img1.byteOffset,len),b32=new Uint32Array(img2.buffer,img2.byteOffset,len),identical=!0;for(let i=0;i<len;i++)if(a32[i]!==b32[i]){identical=!1;break}if(identical){if(output&&!diffMask)for(let i=0,pos=0;i<len;i++,pos+=4)drawGrayPixel(img1,pos,alpha,output);return 0}let maxDelta=35215*threshold*threshold,[aaR,aaG,aaB]=aaColor,[diffR,diffG,diffB]=diffColor,[altR,altG,altB]=diffColorAlt||diffColor,diff=0;for(let i=0,pos=0;i<len;i++,pos+=4){let delta=a32[i]===b32[i]?0:colorDelta(img1,img2,pos,pos,checkerboard);if(Math.abs(delta)>maxDelta){let x=i%width,y=i/width|0;if(!includeAA&&(antialiased(img1,x,y,width,height,a32,b32,checkerboard)||antialiased(img2,x,y,width,height,b32,a32,checkerboard))){if(output&&!diffMask)drawPixel(output,pos,aaR,aaG,aaB)}else{if(output)if(delta<0)drawPixel(output,pos,altR,altG,altB);else drawPixel(output,pos,diffR,diffG,diffB);diff++}}else if(output&&!diffMask)drawGrayPixel(img1,pos,alpha,output)}return diff}function isPixelData(arr){return ArrayBuffer.isView(arr)&&arr.BYTES_PER_ELEMENT===1}function antialiased(img,x1,y1,width,height,a32,b32,checkerboard){let x0=Math.max(x1-1,0),y0=Math.max(y1-1,0),x2=Math.min(x1+1,width-1),y2=Math.min(y1+1,height-1),pos4=(y1*width+x1)*4,cr=img[pos4],cg=img[pos4+1],cb=img[pos4+2],ca=img[pos4+3],zeroes=x1===x0||x1===x2||y1===y0||y1===y2?1:0,min=0,max=0,minX=0,minY=0,maxX=0,maxY=0;for(let x=x0;x<=x2;x++)for(let y=y0;y<=y2;y++){if(x===x1&&y===y1)continue;let delta=brightnessDelta(img,pos4,(y*width+x)*4,cr,cg,cb,ca,checkerboard);if(delta===0){if(zeroes++,zeroes>2)return!1}else if(delta<min)min=delta,minX=x,minY=y;else if(delta>max)max=delta,maxX=x,maxY=y}if(min===0||max===0)return!1;return hasManySiblings(a32,minX,minY,width,height)&&hasManySiblings(b32,minX,minY,width,height)||hasManySiblings(a32,maxX,maxY,width,height)&&hasManySiblings(b32,maxX,maxY,width,height)}function hasManySiblings(img,x1,y1,width,height){let x0=Math.max(x1-1,0),y0=Math.max(y1-1,0),x2=Math.min(x1+1,width-1),y2=Math.min(y1+1,height-1),val=img[y1*width+x1],zeroes=x1===x0||x1===x2||y1===y0||y1===y2?1:0;for(let x=x0;x<=x2;x++)for(let y=y0;y<=y2;y++){if(x===x1&&y===y1)continue;if(zeroes+=+(val===img[y*width+x]),zeroes>2)return!0}return!1}function colorDelta(img1,img2,k,m,checkerboard){let r1=img1[k],g1=img1[k+1],b1=img1[k+2],a1=img1[k+3],r2=img2[m],g2=img2[m+1],b2=img2[m+2],a2=img2[m+3],dr=r1-r2,dg=g1-g2,db=b1-b2,da=a1-a2;if(a1<255||a2<255){let rb=255,gb=255,bb=255;if(checkerboard)rb=48+159*(k%2),gb=48+159*((k/1.618033988749895|0)%2),bb=48+159*((k/2.618033988749895|0)%2);dr=(r1*a1-r2*a2-rb*da)/255,dg=(g1*a1-g2*a2-gb*da)/255,db=(b1*a1-b2*a2-bb*da)/255}let y=dr*0.29889531+dg*0.58662247+db*0.11448223,i=dr*0.59597799-dg*0.2741761-db*0.32180189,q=dr*0.21147017-dg*0.52261711+db*0.31114694,delta=0.5053*y*y+0.299*i*i+0.1957*q*q;return y>0?-delta:delta}function brightnessDelta(img,k,m,r1,g1,b1,a1,checkerboard){let r2=img[m],g2=img[m+1],b2=img[m+2],a2=img[m+3],dr=r1-r2,dg=g1-g2,db=b1-b2,da=a1-a2;if(!dr&&!dg&&!db&&!da)return 0;if(a1<255||a2<255){let rb=255,gb=255,bb=255;if(checkerboard)rb=48+159*(k%2),gb=48+159*((k/1.618033988749895|0)%2),bb=48+159*((k/2.618033988749895|0)%2);dr=(r1*a1-r2*a2-rb*da)/255,dg=(g1*a1-g2*a2-gb*da)/255,db=(b1*a1-b2*a2-bb*da)/255}return dr*0.29889531+dg*0.58662247+db*0.11448223}function drawPixel(output,pos,r,g,b){output[pos]=r,output[pos+1]=g,output[pos+2]=b,output[pos+3]=255}function drawGrayPixel(img,i,alpha,output){let val=255+(img[i]*0.29889531+img[i+1]*0.58662247+img[i+2]*0.11448223-255)*alpha*img[i+3]/255;drawPixel(output,i,val,val,val)}var import_pngjs=__toESM(require_png(),1);function padToUnion(png,width,height){if(png.width===width&&png.height===height)return png;let out=new import_pngjs.PNG({width,height,fill:!0});return import_pngjs.PNG.bitblt(png,out,0,0,png.width,png.height,0,0),out}function clusterRegions(mask,width,height,cellSize,maxRegions){let cols=Math.ceil(width/cellSize),rows=Math.ceil(height/cellSize),dirty=new Uint8Array(cols*rows);for(let y=0;y<height;y++)for(let x=0;x<width;x++)if(mask[y*width+x])dirty[Math.floor(y/cellSize)*cols+Math.floor(x/cellSize)]=1;let seen=new Uint8Array(cols*rows),regions=[];for(let cy=0;cy<rows;cy++)for(let cx=0;cx<cols;cx++){let idx=cy*cols+cx;if(!dirty[idx]||seen[idx])continue;let minX=cx,maxX=cx,minY=cy,maxY=cy,queue=[idx];seen[idx]=1;while(queue.length>0){let cur=queue.pop(),x=cur%cols,y=Math.floor(cur/cols);minX=Math.min(minX,x),maxX=Math.max(maxX,x),minY=Math.min(minY,y),maxY=Math.max(maxY,y);for(let[dx,dy]of[[1,0],[-1,0],[0,1],[0,-1]]){let nx=x+dx,ny=y+dy;if(nx<0||ny<0||nx>=cols||ny>=rows)continue;let nIdx=ny*cols+nx;if(dirty[nIdx]&&!seen[nIdx])seen[nIdx]=1,queue.push(nIdx)}}regions.push({x:minX*cellSize,y:minY*cellSize,w:Math.min((maxX+1)*cellSize,width)-minX*cellSize,h:Math.min((maxY+1)*cellSize,height)-minY*cellSize})}if(regions.sort((a,b)=>b.w*b.h-a.w*a.h),regions.length>maxRegions){let tail=regions.slice(maxRegions-1),minX=Math.min(...tail.map((r)=>r.x)),minY=Math.min(...tail.map((r)=>r.y)),maxX=Math.max(...tail.map((r)=>r.x+r.w)),maxY=Math.max(...tail.map((r)=>r.y+r.h));return[...regions.slice(0,maxRegions-1),{x:minX,y:minY,w:maxX-minX,h:maxY-minY}]}return regions}function diffPngs(before,after,options={}){let a=import_pngjs.PNG.sync.read(before),b=import_pngjs.PNG.sync.read(after),width=Math.max(a.width,b.width),height=Math.max(a.height,b.height),pa=padToUnion(a,width,height),pb=padToUnion(b,width,height),diff=new import_pngjs.PNG({width,height}),changedPixels=pixelmatch(pa.data,pb.data,diff.data,width,height,{threshold:options.threshold??0.1,includeAA:!1,alpha:0.6}),mask=new Uint8Array(width*height);if(changedPixels>0){let d=diff.data;for(let i=0;i<width*height;i++){let r=d[i*4],g=d[i*4+1],bch=d[i*4+2];if(r>200&&g<120&&bch<120)mask[i]=1}}let regions=changedPixels===0?[]:clusterRegions(mask,width,height,options.cellSize??16,options.maxRegions??10);for(let r of regions){let n=0;for(let y=r.y;y<r.y+r.h;y++){let row=y*width;for(let x=r.x;x<r.x+r.w;x++)n+=mask[row+x]}r.changedPixels=n}regions.sort((a,b)=>(b.changedPixels??0)-(a.changedPixels??0));let contentHeight=Math.min(a.height,b.height),contentLen=width*contentHeight*4,contentChangedPixels=contentHeight===height?changedPixels:pixelmatch(pa.data.subarray(0,contentLen),pb.data.subarray(0,contentLen),void 0,width,contentHeight,{threshold:options.threshold??0.1,includeAA:!1,alpha:0.6});return{changedPixels,changedRatio:changedPixels/(width*height),alignedChangedRatio:changedPixels===0?0:alignedChanged(pa.data,pb.data,mask,width,height,options.threshold??0.1)/(width*height),contentChangedRatio:contentChangedPixels/(width*contentHeight),heightDelta:b.height-a.height,width,height,regions,diffPng:import_pngjs.PNG.sync.write(diff)}}function alignedChanged(a,b,mask,width,height,threshold){let maxDelta=35215*threshold*threshold,remaining=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){if(!mask[y*width+x])continue;let here=(y*width+x)*4,matched=!1;for(let dy=-1;dy<=1&&!matched;dy++){let ny=y+dy;if(ny<0||ny>=height)continue;for(let dx=-1;dx<=1&&!matched;dx++){let nx=x+dx;if(nx<0||nx>=width||dx===0&&dy===0)continue;let there=(ny*width+nx)*4;if(colorDelta2(b,a,here,there)<=maxDelta)matched=!0;else if(colorDelta2(a,b,here,there)<=maxDelta)matched=!0}}if(!matched)remaining++}return remaining}function colorDelta2(a,b,ai,bi){let r1=a[ai],g1=a[ai+1],b1=a[ai+2],r2=b[bi],g2=b[bi+1],b2=b[bi+2],y=0.29889531*(r1-r2)+0.58662247*(g1-g2)+0.11448223*(b1-b2),i=0.59597799*(r1-r2)-0.2741761*(g1-g2)-0.32180189*(b1-b2),q=0.21147017*(r1-r2)-0.52261711*(g1-g2)+0.31114694*(b1-b2);return 0.5053*y*y+0.299*i*i+0.1957*q*q}function downscalePng(png,factor){if(!Number.isInteger(factor)||factor<=1)return png;let src=import_pngjs.PNG.sync.read(png),width=Math.max(1,Math.floor(src.width/factor)),height=Math.max(1,Math.floor(src.height/factor)),out=new import_pngjs.PNG({width,height});for(let y=0;y<height;y++)for(let x=0;x<width;x++){let r=0,g=0,b=0,a=0,n=0;for(let dy=0;dy<factor;dy++){let sy=y*factor+dy;if(sy>=src.height)break;for(let dx=0;dx<factor;dx++){let sx=x*factor+dx;if(sx>=src.width)break;let i=sy*src.width+sx<<2;r+=src.data[i]??0,g+=src.data[i+1]??0,b+=src.data[i+2]??0,a+=src.data[i+3]??0,n++}}let o=y*width+x<<2;out.data[o]=Math.round(r/n),out.data[o+1]=Math.round(g/n),out.data[o+2]=Math.round(b/n),out.data[o+3]=Math.round(a/n)}return import_pngjs.PNG.sync.write(out)}function resizePng(png,width,height){let src=import_pngjs.PNG.sync.read(png),outWidth=Math.max(1,Math.round(width)),outHeight=Math.max(1,Math.round(height));if(src.width===outWidth&&src.height===outHeight)return png;let out=new import_pngjs.PNG({width:outWidth,height:outHeight});for(let y=0;y<outHeight;y++){let sy=Math.max(0,Math.min(src.height-1,(y+0.5)*src.height/outHeight-0.5)),y0=Math.floor(sy),y1=Math.min(src.height-1,y0+1),fy=sy-y0;for(let x=0;x<outWidth;x++){let sx=Math.max(0,Math.min(src.width-1,(x+0.5)*src.width/outWidth-0.5)),x0=Math.floor(sx),x1=Math.min(src.width-1,x0+1),fx=sx-x0,dst=y*outWidth+x<<2;for(let channel=0;channel<4;channel++){let a=src.data[(y0*src.width+x0)*4+channel]??0,b=src.data[(y0*src.width+x1)*4+channel]??0,c=src.data[(y1*src.width+x0)*4+channel]??0,d=src.data[(y1*src.width+x1)*4+channel]??0,top=a+(b-a)*fx,bottom=c+(d-c)*fx;out.data[dst+channel]=Math.round(top+(bottom-top)*fy)}}}return import_pngjs.PNG.sync.write(out)}function pngSize(png){let p=import_pngjs.PNG.sync.read(png);return{width:p.width,height:p.height}}function cropPng(png,region,pad=24){let src=import_pngjs.PNG.sync.read(png),x=Math.max(0,region.x-pad),y=Math.max(0,region.y-pad),w=Math.min(src.width-x,region.w+pad*2),h=Math.min(src.height-y,region.h+pad*2),out=new import_pngjs.PNG({width:w,height:h});return import_pngjs.PNG.bitblt(src,out,x,y,w,h,0,0),import_pngjs.PNG.sync.write(out)}function sideBySidePng(left,right,gutter=12){let a=import_pngjs.PNG.sync.read(left),b=import_pngjs.PNG.sync.read(right),width=a.width+gutter+b.width,height=Math.max(a.height,b.height),out=new import_pngjs.PNG({width,height});return out.data.fill(255),import_pngjs.PNG.bitblt(a,out,0,0,a.width,a.height,0,0),import_pngjs.PNG.bitblt(b,out,0,0,b.width,b.height,a.width+gutter,0),import_pngjs.PNG.sync.write(out)}function unionRegion(regions){let minX=Math.min(...regions.map((r)=>r.x)),minY=Math.min(...regions.map((r)=>r.y)),maxX=Math.max(...regions.map((r)=>r.x+r.w)),maxY=Math.max(...regions.map((r)=>r.y+r.h));return{x:minX,y:minY,w:maxX-minX,h:maxY-minY}}var TOOLBAR_TAG="velloo-capture-toolbar",MAX_NODES=20000,MAX_DEPTH=24,MAX_TEXT=240,TRANSIENT_SCREENSHOT_ERROR=/Protocol error \(Page\.captureScreenshot\):\s*Unable to capture screenshot/i;async function retryTransientScreenshot(take){try{return await take()}catch(err){let message=err instanceof Error?err.message:String(err);if(!TRANSIENT_SCREENSHOT_ERROR.test(message))throw err;return await new Promise((resolve)=>setTimeout(resolve,100)),await take()}}async function capturePagePng(page,fullPage,timeout){return retryTransientScreenshot(()=>page.screenshot({fullPage,animations:"disabled",caret:"hide",...timeout===void 0?{}:{timeout}}))}var STYLE_PROPS=["display","position","boxSizing","flexDirection","flexWrap","alignItems","justifyContent","gap","gridTemplateColumns","padding","margin","width","maxWidth","height","minHeight","fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","textAlign","textTransform","color","backgroundColor","backgroundImage","borderRadius","borderWidth","borderColor","borderStyle","boxShadow","opacity","zIndex"];async function extractDom(page,limits={maxNodes:MAX_NODES,maxDepth:MAX_DEPTH,maxText:MAX_TEXT},toolbarTag=TOOLBAR_TAG){return page.evaluate(({props,maxNodes,maxDepth,maxText,toolbar})=>{let nodes=[],truncated=!1,ownText=(el)=>{let s="";for(let child of Array.from(el.childNodes))if(child.nodeType===3)s+=child.textContent??"";return s.replace(/\s+/g," ").trim().slice(0,maxText)},shown=(text,transform)=>{if(transform==="uppercase")return text.toUpperCase();if(transform==="lowercase")return text.toLowerCase();if(transform==="capitalize")return text.replace(/(^|\s)(\p{L})/gu,(m)=>m.toUpperCase());return text},lineOf=(el,cs)=>{let s="";for(let child of Array.from(el.childNodes)){if(child.nodeType===3){s+=shown(child.textContent??"",cs.textTransform);continue}if(child.nodeType!==1)continue;let inner=child;if(inner.tagName==="BR"){s+=" ";continue}let innerStyle=getComputedStyle(inner);if(innerStyle.display==="none"||innerStyle.visibility==="hidden")continue;let below=lineOf(inner,innerStyle);if(below===null)return null;if(below.trim()==="")continue;if(!(innerStyle.display.startsWith("inline")||innerStyle.display==="contents"))return null;s+=below}return s},signatureOf=(el)=>{let cls=(el.getAttribute("class")??"").trim();return`${el.tagName.toLowerCase()}|${cls}|${el.children.length}`},walk=(el,parent,depth)=>{if(nodes.length>=maxNodes){truncated=!0;return}if(depth>maxDepth){truncated=!0;return}if(el.tagName.toLowerCase()===toolbar)return;let cs=getComputedStyle(el);if(cs.display==="none"||cs.visibility==="hidden")return;let r=el.getBoundingClientRect(),scrollX2=window.scrollX,scrollY2=window.scrollY;if(r.width===0&&r.height===0)return;let style={};for(let p of props){let v=cs[p];if(typeof v==="string"&&v!==""&&v!=="none"&&v!=="normal")style[p]=v}let i=nodes.length,entry={i,parent,depth,tag:el.tagName.toLowerCase(),rect:{x:Math.round(r.x+scrollX2),y:Math.round(r.y+scrollY2),w:Math.round(r.width),h:Math.round(r.height)},style},id=el.getAttribute("id");if(id)entry.id=id;let cls=el.getAttribute("class");if(cls)entry.class=cls.trim().slice(0,400);let role=el.getAttribute("role")??el.getAttribute("aria-label");if(role)entry.role=role;let t=ownText(el);if(t){if(entry.text=t,el.childElementCount>0){let line=lineOf(el,cs)?.replace(/\s+/g," ").trim().slice(0,maxText);if(line&&line!==shown(t,cs.textTransform))entry.line=line}}let src=el.getAttribute("src");if(src)entry.src=src;let href=el.getAttribute("href");if(href)entry.href=href.slice(0,300);let nodePath=el.getAttribute("data-node-path");if(nodePath!==null)entry.nodePath=nodePath;nodes.push(entry);let children=Array.from(el.children),counts=new Map;for(let c of children){let sig=signatureOf(c);counts.set(sig,(counts.get(sig)??0)+1)}let seen=new Set;for(let c of children){let before=nodes.length;walk(c,i,depth+1);let sig=signatureOf(c),n=counts.get(sig)??0;if(n>=3&&!seen.has(sig)&&nodes.length>before){seen.add(sig);let added=nodes[before];if(added)added.repeat={count:n,signature:sig}}}};if(document.body)walk(document.body,null,0);return{url:location.href,title:document.title,viewport:{w:window.innerWidth,h:window.innerHeight},documentHeight:Math.max(document.documentElement?.scrollHeight??0,document.body?.scrollHeight??0),nodes,truncated}},{props:STYLE_PROPS,maxNodes:limits.maxNodes,maxDepth:limits.maxDepth,maxText:limits.maxText,toolbar:toolbarTag})}async function extractThemeVars(page){return page.evaluate(()=>{let light={},dark={},fonts=new Set,isDarkSelector=(sel)=>/(^|[\s,>])(\.dark|\[data-theme["'=\s]*dark|\.theme-dark)/i.test(sel),readRule=(rule,intoDark)=>{let{style,selectorText:selector}=rule;if(!style||typeof selector!=="string")return;if(!/(^|,)\s*(:root|html|body|\.dark|\[data-theme)/i.test(selector))return;let target=intoDark||isDarkSelector(selector)?dark:light;for(let i=0;i<style.length;i++){let prop=style.item(i);if(!prop.startsWith("--"))continue;let value=style.getPropertyValue(prop).trim();if(value)target[prop]=value}let ff=style.getPropertyValue("font-family").trim();if(ff)fonts.add(ff)},walkRules=(rules,intoDark)=>{for(let rule of Array.from(rules)){let asStyle=rule;if(typeof asStyle.selectorText==="string"&&asStyle.style)readRule(rule,intoDark);let nested=rule.cssRules;if(nested&&nested.length>0){let cond=rule instanceof CSSConditionRule?rule.conditionText:"";walkRules(nested,intoDark||/prefers-color-scheme\s*:\s*dark/i.test(cond))}}};for(let sheet of Array.from(document.styleSheets))try{let rules=sheet.cssRules;if(rules)walkRules(rules,!1)}catch{}let rootStyle=getComputedStyle(document.documentElement);for(let prop of Array.from(rootStyle)){if(!prop.startsWith("--"))continue;if(light[prop]!==void 0)continue;let value=rootStyle.getPropertyValue(prop).trim();if(value)light[prop]=value}let bodyFont=getComputedStyle(document.body??document.documentElement).fontFamily;if(bodyFont)fonts.add(bodyFont);let block=(sel,vars)=>{let entries=Object.entries(vars);if(entries.length===0)return"";return`${sel} {
88
88
  ${entries.map(([k,v])=>` ${k}: ${v};`).join(`
89
89
  `)}
90
90
  }
@@ -349,7 +349,7 @@ Check the render method of \``+name+"`.")}request||componentName&&(request=`
349
349
  Check the top-level render call using <`+componentName+">."),componentName="",didWarnForKey!=null&&parentOwner!==didWarnForKey&&(parentOwner=null,typeof didWarnForKey.type<"u"?parentOwner=getComponentNameFromType(didWarnForKey.type):typeof didWarnForKey.name==="string"&&(parentOwner=didWarnForKey.name),parentOwner&&(componentName=" It was passed a child from "+parentOwner+".")),didWarnForKey=task.componentStack,task.componentStack={parent:task.componentStack,type:child.type,owner:child._owner,stack:child._debugStack},console.error('Each child in a list should have a unique "key" prop.%s%s See https://react.dev/link/warning-keys for more information.',request,componentName),task.componentStack=didWarnForKey}}}function renderChildrenArray(request,task,children,childIndex){var{keyPath:prevKeyPath,componentStack:previousComponentStack,debugTask:previousDebugTask}=task;if(pushServerComponentStack(task,task.node._debugInfo),childIndex!==-1&&(task.keyPath=[task.keyPath,"Fragment",childIndex],task.replay!==null)){for(var replay=task.replay,replayNodes=replay.nodes,j=0;j<replayNodes.length;j++){var node=replayNodes[j];if(node[1]===childIndex){childIndex=node[2],node=node[3],task.replay={nodes:childIndex,slots:node,pendingTasks:1};try{if(renderChildrenArray(request,task,children,-1),task.replay.pendingTasks===1&&0<task.replay.nodes.length)throw Error("Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering.");task.replay.pendingTasks--}catch(x){if(typeof x==="object"&&x!==null&&(x===SuspenseException||typeof x.then==="function"))throw x;task.replay.pendingTasks--;var thrownInfo=getThrownInfo(task.componentStack);children=task.blockedBoundary;var error=x,resumeSlots=node;node=logRecoverableError(request,error,thrownInfo,task.debugTask),abortRemainingReplayNodes(request,children,childIndex,resumeSlots,error,node,thrownInfo,!1)}task.replay=replay,replayNodes.splice(j,1);break}}task.keyPath=prevKeyPath,task.componentStack=previousComponentStack,task.debugTask=previousDebugTask;return}if(replay=task.treeContext,replayNodes=children.length,task.replay!==null&&(j=task.replay.slots,j!==null&&typeof j==="object")){for(childIndex=0;childIndex<replayNodes;childIndex++)node=children[childIndex],task.treeContext=pushTreeContext(replay,replayNodes,childIndex),error=j[childIndex],typeof error==="number"?(resumeNode(request,task,error,node,childIndex),delete j[childIndex]):renderNode(request,task,node,childIndex);task.treeContext=replay,task.keyPath=prevKeyPath,task.componentStack=previousComponentStack,task.debugTask=previousDebugTask;return}for(j=0;j<replayNodes;j++)childIndex=children[j],warnForMissingKey(request,task,childIndex),task.treeContext=pushTreeContext(replay,replayNodes,j),renderNode(request,task,childIndex,j);task.treeContext=replay,task.keyPath=prevKeyPath,task.componentStack=previousComponentStack,task.debugTask=previousDebugTask}function trackPostponedBoundary(request,trackedPostpones,boundary){if(boundary.status=POSTPONED,boundary.rootSegmentID=request.nextSegmentId++,request=boundary.trackedContentKeyPath,request===null)throw Error("It should not be possible to postpone at the root. This is a bug in React.");var fallbackReplayNode=boundary.trackedFallbackNode,children=[],boundaryNode=trackedPostpones.workingMap.get(request);if(boundaryNode===void 0)return boundary=[request[1],request[2],children,null,fallbackReplayNode,boundary.rootSegmentID],trackedPostpones.workingMap.set(request,boundary),addToReplayParent(boundary,request[0],trackedPostpones),boundary;return boundaryNode[4]=fallbackReplayNode,boundaryNode[5]=boundary.rootSegmentID,boundaryNode}function trackPostpone(request,trackedPostpones,task,segment){segment.status=POSTPONED;var keyPath=task.keyPath,boundary=task.blockedBoundary;if(boundary===null)segment.id=request.nextSegmentId++,trackedPostpones.rootSlots=segment.id,request.completedRootSegment!==null&&(request.completedRootSegment.status=POSTPONED);else{if(boundary!==null&&boundary.status===PENDING){var boundaryNode=trackPostponedBoundary(request,trackedPostpones,boundary);if(boundary.trackedContentKeyPath===keyPath&&task.childIndex===-1){segment.id===-1&&(segment.id=segment.parentFlushed?boundary.rootSegmentID:request.nextSegmentId++),boundaryNode[3]=segment.id;return}}if(segment.id===-1&&(segment.id=segment.parentFlushed&&boundary!==null?boundary.rootSegmentID:request.nextSegmentId++),task.childIndex===-1)keyPath===null?trackedPostpones.rootSlots=segment.id:(task=trackedPostpones.workingMap.get(keyPath),task===void 0?(task=[keyPath[1],keyPath[2],[],segment.id],addToReplayParent(task,keyPath[0],trackedPostpones)):task[3]=segment.id);else{if(keyPath===null){if(request=trackedPostpones.rootSlots,request===null)request=trackedPostpones.rootSlots={};else if(typeof request==="number")throw Error("It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React.")}else if(boundary=trackedPostpones.workingMap,boundaryNode=boundary.get(keyPath),boundaryNode===void 0)request={},boundaryNode=[keyPath[1],keyPath[2],[],request],boundary.set(keyPath,boundaryNode),addToReplayParent(boundaryNode,keyPath[0],trackedPostpones);else if(request=boundaryNode[3],request===null)request=boundaryNode[3]={};else if(typeof request==="number")throw Error("It should not be possible to postpone both at the root of an element as well as a slot below. This is a bug in React.");request[task.childIndex]=segment.id}}}function untrackBoundary(request,boundary){request=request.trackedPostpones,request!==null&&(boundary=boundary.trackedContentKeyPath,boundary!==null&&(boundary=request.workingMap.get(boundary),boundary!==void 0&&(boundary.length=4,boundary[2]=[],boundary[3]=null)))}function spawnNewSuspendedReplayTask(request,task,thenableState){return createReplayTask(request,thenableState,task.replay,task.node,task.childIndex,task.blockedBoundary,task.hoistableState,task.abortSet,task.keyPath,task.formatContext,task.context,task.treeContext,task.row,task.componentStack,emptyContextObject,task.debugTask)}function spawnNewSuspendedRenderTask(request,task,thenableState){var segment=task.blockedSegment,newSegment=createPendingSegment(request,segment.chunks.length,null,task.formatContext,segment.lastPushedText,!0);return segment.children.push(newSegment),segment.lastPushedText=!1,createRenderTask(request,thenableState,task.node,task.childIndex,task.blockedBoundary,newSegment,task.blockedPreamble,task.hoistableState,task.abortSet,task.keyPath,task.formatContext,task.context,task.treeContext,task.row,task.componentStack,emptyContextObject,task.debugTask)}function renderNode(request,task,node,childIndex){var{formatContext:previousFormatContext,context:previousContext,keyPath:previousKeyPath,treeContext:previousTreeContext,componentStack:previousComponentStack,debugTask:previousDebugTask,blockedSegment:segment}=task;if(segment===null){segment=task.replay;try{return renderNodeDestructive(request,task,node,childIndex)}catch(thrownValue){if(resetHooksState(),node=thrownValue===SuspenseException?getSuspendedThenable():thrownValue,request.status!==12&&typeof node==="object"&&node!==null){if(typeof node.then==="function"){childIndex=thrownValue===SuspenseException?getThenableStateAfterSuspending():null,request=spawnNewSuspendedReplayTask(request,task,childIndex).ping,node.then(request,request),task.formatContext=previousFormatContext,task.context=previousContext,task.keyPath=previousKeyPath,task.treeContext=previousTreeContext,task.componentStack=previousComponentStack,task.replay=segment,task.debugTask=previousDebugTask,switchContext(previousContext);return}if(node.message==="Maximum call stack size exceeded"){node=thrownValue===SuspenseException?getThenableStateAfterSuspending():null,node=spawnNewSuspendedReplayTask(request,task,node),request.pingedTasks.push(node),task.formatContext=previousFormatContext,task.context=previousContext,task.keyPath=previousKeyPath,task.treeContext=previousTreeContext,task.componentStack=previousComponentStack,task.replay=segment,task.debugTask=previousDebugTask,switchContext(previousContext);return}}}}else{var childrenLength=segment.children.length,chunkLength=segment.chunks.length;try{return renderNodeDestructive(request,task,node,childIndex)}catch(thrownValue$3){if(resetHooksState(),segment.children.length=childrenLength,segment.chunks.length=chunkLength,node=thrownValue$3===SuspenseException?getSuspendedThenable():thrownValue$3,request.status!==12&&typeof node==="object"&&node!==null){if(typeof node.then==="function"){segment=node,node=thrownValue$3===SuspenseException?getThenableStateAfterSuspending():null,request=spawnNewSuspendedRenderTask(request,task,node).ping,segment.then(request,request),task.formatContext=previousFormatContext,task.context=previousContext,task.keyPath=previousKeyPath,task.treeContext=previousTreeContext,task.componentStack=previousComponentStack,task.debugTask=previousDebugTask,switchContext(previousContext);return}if(node.message==="Maximum call stack size exceeded"){segment=thrownValue$3===SuspenseException?getThenableStateAfterSuspending():null,segment=spawnNewSuspendedRenderTask(request,task,segment),request.pingedTasks.push(segment),task.formatContext=previousFormatContext,task.context=previousContext,task.keyPath=previousKeyPath,task.treeContext=previousTreeContext,task.componentStack=previousComponentStack,task.debugTask=previousDebugTask,switchContext(previousContext);return}}}}throw task.formatContext=previousFormatContext,task.context=previousContext,task.keyPath=previousKeyPath,task.treeContext=previousTreeContext,switchContext(previousContext),node}function abortTaskSoft(task){var{blockedBoundary:boundary,blockedSegment:segment}=task;segment!==null&&(segment.status=ABORTED,finishedTask(this,boundary,task.row,segment))}function abortRemainingReplayNodes(request$jscomp$0,boundary,nodes,slots,error$jscomp$0,errorDigest$jscomp$0,errorInfo$jscomp$0,aborted){for(var i=0;i<nodes.length;i++){var node=nodes[i];if(node.length===4)abortRemainingReplayNodes(request$jscomp$0,boundary,node[2],node[3],error$jscomp$0,errorDigest$jscomp$0,errorInfo$jscomp$0,aborted);else{var request=request$jscomp$0;node=node[5];var error=error$jscomp$0,errorDigest=errorDigest$jscomp$0,errorInfo=errorInfo$jscomp$0,wasAborted=aborted,resumedBoundary=createSuspenseBoundary(request,null,new Set,null,null);resumedBoundary.parentFlushed=!0,resumedBoundary.rootSegmentID=node,resumedBoundary.status=CLIENT_RENDERED,encodeErrorForBoundary(resumedBoundary,errorDigest,error,errorInfo,wasAborted),resumedBoundary.parentFlushed&&request.clientRenderedBoundaries.push(resumedBoundary)}}if(nodes.length=0,slots!==null){if(boundary===null)throw Error("We should not have any resumable nodes in the shell. This is a bug in React.");if(boundary.status!==CLIENT_RENDERED&&(boundary.status=CLIENT_RENDERED,encodeErrorForBoundary(boundary,errorDigest$jscomp$0,error$jscomp$0,errorInfo$jscomp$0,aborted),boundary.parentFlushed&&request$jscomp$0.clientRenderedBoundaries.push(boundary)),typeof slots==="object")for(var index in slots)delete slots[index]}}function abortTask(task,request,error){var boundary=task.blockedBoundary,segment=task.blockedSegment;if(segment!==null){if(segment.status===6)return;segment.status=ABORTED}var errorInfo=getThrownInfo(task.componentStack),node=task.node;if(node!==null&&typeof node==="object"&&pushHaltedAwaitOnComponentStack(task,node._debugInfo),boundary===null){if(request.status!==13&&request.status!==CLOSED){if(boundary=task.replay,boundary===null){request.trackedPostpones!==null&&segment!==null?(boundary=request.trackedPostpones,logRecoverableError(request,error,errorInfo,task.debugTask),trackPostpone(request,boundary,task,segment),finishedTask(request,null,task.row,segment)):(logRecoverableError(request,error,errorInfo,task.debugTask),fatalError(request,error,errorInfo,task.debugTask));return}boundary.pendingTasks--,boundary.pendingTasks===0&&0<boundary.nodes.length&&(segment=logRecoverableError(request,error,errorInfo,null),abortRemainingReplayNodes(request,null,boundary.nodes,boundary.slots,error,segment,errorInfo,!0)),request.pendingRootTasks--,request.pendingRootTasks===0&&completeShell(request)}}else{if(node=request.trackedPostpones,boundary.status!==CLIENT_RENDERED){if(node!==null&&segment!==null)return logRecoverableError(request,error,errorInfo,task.debugTask),trackPostpone(request,node,task,segment),boundary.fallbackAbortableTasks.forEach(function(fallbackTask){return abortTask(fallbackTask,request,error)}),boundary.fallbackAbortableTasks.clear(),finishedTask(request,boundary,task.row,segment);boundary.status=CLIENT_RENDERED,segment=logRecoverableError(request,error,errorInfo,task.debugTask),boundary.status=CLIENT_RENDERED,encodeErrorForBoundary(boundary,segment,error,errorInfo,!0),untrackBoundary(request,boundary),boundary.parentFlushed&&request.clientRenderedBoundaries.push(boundary)}boundary.pendingTasks--,errorInfo=boundary.row,errorInfo!==null&&--errorInfo.pendingTasks===0&&finishSuspenseListRow(request,errorInfo),boundary.fallbackAbortableTasks.forEach(function(fallbackTask){return abortTask(fallbackTask,request,error)}),boundary.fallbackAbortableTasks.clear()}task=task.row,task!==null&&--task.pendingTasks===0&&finishSuspenseListRow(request,task),request.allPendingTasks--,request.allPendingTasks===0&&completeAll(request)}function safelyEmitEarlyPreloads(request,shellComplete){try{var renderState=request.renderState,onHeaders=renderState.onHeaders;if(onHeaders){var headers=renderState.headers;if(headers){renderState.headers=null;var linkHeader=headers.preconnects;if(headers.fontPreloads&&(linkHeader&&(linkHeader+=", "),linkHeader+=headers.fontPreloads),headers.highImagePreloads&&(linkHeader&&(linkHeader+=", "),linkHeader+=headers.highImagePreloads),!shellComplete){var queueIter=renderState.styles.values(),queueStep=queueIter.next();b:for(;0<headers.remainingCapacity&&!queueStep.done;queueStep=queueIter.next())for(var sheetIter=queueStep.value.sheets.values(),sheetStep=sheetIter.next();0<headers.remainingCapacity&&!sheetStep.done;sheetStep=sheetIter.next()){var sheet=sheetStep.value,props=sheet.props,key=props.href,props$jscomp$0=sheet.props,header=getPreloadAsHeader(props$jscomp$0.href,"style",{crossOrigin:props$jscomp$0.crossOrigin,integrity:props$jscomp$0.integrity,nonce:props$jscomp$0.nonce,type:props$jscomp$0.type,fetchPriority:props$jscomp$0.fetchPriority,referrerPolicy:props$jscomp$0.referrerPolicy,media:props$jscomp$0.media});if(0<=(headers.remainingCapacity-=header.length+2))renderState.resets.style[key]=PRELOAD_NO_CREDS,linkHeader&&(linkHeader+=", "),linkHeader+=header,renderState.resets.style[key]=typeof props.crossOrigin==="string"||typeof props.integrity==="string"?[props.crossOrigin,props.integrity]:PRELOAD_NO_CREDS;else break b}}linkHeader?onHeaders({Link:linkHeader}):onHeaders({})}}}catch(error){logRecoverableError(request,error,{},null)}}function completeShell(request){request.trackedPostpones===null&&safelyEmitEarlyPreloads(request,!0),request.trackedPostpones===null&&preparePreamble(request),request.onShellError=noop,request=request.onShellReady,request()}function completeAll(request){safelyEmitEarlyPreloads(request,request.trackedPostpones===null?!0:request.completedRootSegment===null||request.completedRootSegment.status!==POSTPONED),preparePreamble(request),request=request.onAllReady,request()}function queueCompletedSegment(boundary,segment){if(segment.chunks.length===0&&segment.children.length===1&&segment.children[0].boundary===null&&segment.children[0].id===-1){var childSegment=segment.children[0];childSegment.id=segment.id,childSegment.parentFlushed=!0,childSegment.status!==COMPLETED&&childSegment.status!==ABORTED&&childSegment.status!==ERRORED||queueCompletedSegment(boundary,childSegment)}else boundary.completedSegments.push(segment)}function finishedSegment(request,boundary,segment){if(byteLengthOfChunk!==null){segment=segment.chunks;for(var segmentByteSize=0,i=0;i<segment.length;i++)segmentByteSize+=byteLengthOfChunk(segment[i]);boundary===null?request.byteSize+=segmentByteSize:boundary.byteSize+=segmentByteSize}}function finishedTask(request,boundary,row,segment){if(row!==null&&(--row.pendingTasks===0?finishSuspenseListRow(request,row):row.together&&tryToResolveTogetherRow(request,row)),request.allPendingTasks--,boundary===null){if(segment!==null&&segment.parentFlushed){if(request.completedRootSegment!==null)throw Error("There can only be one root segment. This is a bug in React.");request.completedRootSegment=segment}request.pendingRootTasks--,request.pendingRootTasks===0&&completeShell(request)}else if(boundary.pendingTasks--,boundary.status!==CLIENT_RENDERED)if(boundary.pendingTasks===0){if(boundary.status===PENDING&&(boundary.status=COMPLETED),segment!==null&&segment.parentFlushed&&(segment.status===COMPLETED||segment.status===ABORTED)&&queueCompletedSegment(boundary,segment),boundary.parentFlushed&&request.completedBoundaries.push(boundary),boundary.status===COMPLETED)row=boundary.row,row!==null&&hoistHoistables(row.hoistables,boundary.contentState),isEligibleForOutlining(request,boundary)||(boundary.fallbackAbortableTasks.forEach(abortTaskSoft,request),boundary.fallbackAbortableTasks.clear(),row!==null&&--row.pendingTasks===0&&finishSuspenseListRow(request,row)),request.pendingRootTasks===0&&request.trackedPostpones===null&&boundary.contentPreamble!==null&&preparePreamble(request);else if(boundary.status===POSTPONED&&(boundary=boundary.row,boundary!==null)){if(request.trackedPostpones!==null){row=request.trackedPostpones;var postponedRow=boundary.next;if(postponedRow!==null&&(segment=postponedRow.boundaries,segment!==null))for(postponedRow.boundaries=null,postponedRow=0;postponedRow<segment.length;postponedRow++){var postponedBoundary=segment[postponedRow];trackPostponedBoundary(request,row,postponedBoundary),finishedTask(request,postponedBoundary,null,null)}}--boundary.pendingTasks===0&&finishSuspenseListRow(request,boundary)}}else segment===null||!segment.parentFlushed||segment.status!==COMPLETED&&segment.status!==ABORTED||(queueCompletedSegment(boundary,segment),boundary.completedSegments.length===1&&boundary.parentFlushed&&request.partialBoundaries.push(boundary)),boundary=boundary.row,boundary!==null&&boundary.together&&tryToResolveTogetherRow(request,boundary);request.allPendingTasks===0&&completeAll(request)}function performWork(request$jscomp$2){if(request$jscomp$2.status!==CLOSED&&request$jscomp$2.status!==13){var prevContext=currentActiveSnapshot,prevDispatcher=ReactSharedInternals.H;ReactSharedInternals.H=HooksDispatcher;var prevAsyncDispatcher=ReactSharedInternals.A;ReactSharedInternals.A=DefaultAsyncDispatcher;var prevRequest=currentRequest;currentRequest=request$jscomp$2;var prevGetCurrentStackImpl=ReactSharedInternals.getCurrentStack;ReactSharedInternals.getCurrentStack=getCurrentStackInDEV;var prevResumableState=currentResumableState;currentResumableState=request$jscomp$2.resumableState;try{var pingedTasks=request$jscomp$2.pingedTasks,i;for(i=0;i<pingedTasks.length;i++){var request=request$jscomp$2,task=pingedTasks[i],segment=task.blockedSegment;if(segment===null){var prevTaskInDEV=void 0,request$jscomp$0=request;if(request=task,request.replay.pendingTasks!==0){switchContext(request.context),prevTaskInDEV=currentTaskInDEV,currentTaskInDEV=request;try{if(typeof request.replay.slots==="number"?resumeNode(request$jscomp$0,request,request.replay.slots,request.node,request.childIndex):retryNode(request$jscomp$0,request),request.replay.pendingTasks===1&&0<request.replay.nodes.length)throw Error("Couldn't find all resumable slots by key/index during replaying. The tree doesn't match so React will fallback to client rendering.");request.replay.pendingTasks--,request.abortSet.delete(request),finishedTask(request$jscomp$0,request.blockedBoundary,request.row,null)}catch(thrownValue){resetHooksState();var x=thrownValue===SuspenseException?getSuspendedThenable():thrownValue;if(typeof x==="object"&&x!==null&&typeof x.then==="function"){var ping=request.ping;x.then(ping,ping),request.thenableState=thrownValue===SuspenseException?getThenableStateAfterSuspending():null}else{request.replay.pendingTasks--,request.abortSet.delete(request);var errorInfo=getThrownInfo(request.componentStack),errorDigest=void 0,request$jscomp$1=request$jscomp$0,boundary=request.blockedBoundary,error$jscomp$0=request$jscomp$0.status===12?request$jscomp$0.fatalError:x,errorInfo$jscomp$0=errorInfo,replayNodes=request.replay.nodes,resumeSlots=request.replay.slots;errorDigest=logRecoverableError(request$jscomp$1,error$jscomp$0,errorInfo$jscomp$0,request.debugTask),abortRemainingReplayNodes(request$jscomp$1,boundary,replayNodes,resumeSlots,error$jscomp$0,errorDigest,errorInfo$jscomp$0,!1),request$jscomp$0.pendingRootTasks--,request$jscomp$0.pendingRootTasks===0&&completeShell(request$jscomp$0),request$jscomp$0.allPendingTasks--,request$jscomp$0.allPendingTasks===0&&completeAll(request$jscomp$0)}}finally{currentTaskInDEV=prevTaskInDEV}}}else if(request$jscomp$0=prevTaskInDEV=void 0,errorDigest=task,request$jscomp$1=segment,request$jscomp$1.status===PENDING){request$jscomp$1.status=6,switchContext(errorDigest.context),request$jscomp$0=currentTaskInDEV,currentTaskInDEV=errorDigest;var childrenLength=request$jscomp$1.children.length,chunkLength=request$jscomp$1.chunks.length;try{retryNode(request,errorDigest),pushSegmentFinale(request$jscomp$1.chunks,request.renderState,request$jscomp$1.lastPushedText,request$jscomp$1.textEmbedded),errorDigest.abortSet.delete(errorDigest),request$jscomp$1.status=COMPLETED,finishedSegment(request,errorDigest.blockedBoundary,request$jscomp$1),finishedTask(request,errorDigest.blockedBoundary,errorDigest.row,request$jscomp$1)}catch(thrownValue){resetHooksState(),request$jscomp$1.children.length=childrenLength,request$jscomp$1.chunks.length=chunkLength;var x$jscomp$0=thrownValue===SuspenseException?getSuspendedThenable():request.status===12?request.fatalError:thrownValue;if(request.status===12&&request.trackedPostpones!==null){var trackedPostpones=request.trackedPostpones,thrownInfo=getThrownInfo(errorDigest.componentStack);errorDigest.abortSet.delete(errorDigest),logRecoverableError(request,x$jscomp$0,thrownInfo,errorDigest.debugTask),trackPostpone(request,trackedPostpones,errorDigest,request$jscomp$1),finishedTask(request,errorDigest.blockedBoundary,errorDigest.row,request$jscomp$1)}else if(typeof x$jscomp$0==="object"&&x$jscomp$0!==null&&typeof x$jscomp$0.then==="function"){request$jscomp$1.status=PENDING,errorDigest.thenableState=thrownValue===SuspenseException?getThenableStateAfterSuspending():null;var ping$jscomp$0=errorDigest.ping;x$jscomp$0.then(ping$jscomp$0,ping$jscomp$0)}else{var errorInfo$jscomp$1=getThrownInfo(errorDigest.componentStack);errorDigest.abortSet.delete(errorDigest),request$jscomp$1.status=ERRORED;var boundary$jscomp$0=errorDigest.blockedBoundary,row=errorDigest.row,debugTask=errorDigest.debugTask;if(row!==null&&--row.pendingTasks===0&&finishSuspenseListRow(request,row),request.allPendingTasks--,prevTaskInDEV=logRecoverableError(request,x$jscomp$0,errorInfo$jscomp$1,debugTask),boundary$jscomp$0===null)fatalError(request,x$jscomp$0,errorInfo$jscomp$1,debugTask);else if(boundary$jscomp$0.pendingTasks--,boundary$jscomp$0.status!==CLIENT_RENDERED){boundary$jscomp$0.status=CLIENT_RENDERED,encodeErrorForBoundary(boundary$jscomp$0,prevTaskInDEV,x$jscomp$0,errorInfo$jscomp$1,!1),untrackBoundary(request,boundary$jscomp$0);var boundaryRow=boundary$jscomp$0.row;boundaryRow!==null&&--boundaryRow.pendingTasks===0&&finishSuspenseListRow(request,boundaryRow),boundary$jscomp$0.parentFlushed&&request.clientRenderedBoundaries.push(boundary$jscomp$0),request.pendingRootTasks===0&&request.trackedPostpones===null&&boundary$jscomp$0.contentPreamble!==null&&preparePreamble(request)}request.allPendingTasks===0&&completeAll(request)}}finally{currentTaskInDEV=request$jscomp$0}}}pingedTasks.splice(0,i),request$jscomp$2.destination!==null&&flushCompletedQueues(request$jscomp$2,request$jscomp$2.destination)}catch(error){pingedTasks={},logRecoverableError(request$jscomp$2,error,pingedTasks,null),fatalError(request$jscomp$2,error,pingedTasks,null)}finally{currentResumableState=prevResumableState,ReactSharedInternals.H=prevDispatcher,ReactSharedInternals.A=prevAsyncDispatcher,ReactSharedInternals.getCurrentStack=prevGetCurrentStackImpl,prevDispatcher===HooksDispatcher&&switchContext(prevContext),currentRequest=prevRequest}}}function preparePreambleFromSubtree(request,segment,collectedPreambleSegments){segment.preambleChildren.length&&collectedPreambleSegments.push(segment.preambleChildren);for(var pendingPreambles=!1,i=0;i<segment.children.length;i++)pendingPreambles=preparePreambleFromSegment(request,segment.children[i],collectedPreambleSegments)||pendingPreambles;return pendingPreambles}function preparePreambleFromSegment(request,segment,collectedPreambleSegments){var boundary=segment.boundary;if(boundary===null)return preparePreambleFromSubtree(request,segment,collectedPreambleSegments);var{contentPreamble:preamble,fallbackPreamble}=boundary;if(preamble===null||fallbackPreamble===null)return!1;switch(boundary.status){case COMPLETED:if(hoistPreambleState(request.renderState,preamble),request.byteSize+=boundary.byteSize,segment=boundary.completedSegments[0],!segment)throw Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");return preparePreambleFromSubtree(request,segment,collectedPreambleSegments);case POSTPONED:if(request.trackedPostpones!==null)return!0;case CLIENT_RENDERED:if(segment.status===COMPLETED)return hoistPreambleState(request.renderState,fallbackPreamble),preparePreambleFromSubtree(request,segment,collectedPreambleSegments);default:return!0}}function preparePreamble(request){if(request.completedRootSegment&&request.completedPreambleSegments===null){var collectedPreambleSegments=[],originalRequestByteSize=request.byteSize,hasPendingPreambles=preparePreambleFromSegment(request,request.completedRootSegment,collectedPreambleSegments),preamble=request.renderState.preamble;hasPendingPreambles===!1||preamble.headChunks&&preamble.bodyChunks?request.completedPreambleSegments=collectedPreambleSegments:request.byteSize=originalRequestByteSize}}function flushSubtree(request,destination,segment,hoistableState){switch(segment.parentFlushed=!0,segment.status){case PENDING:segment.id=request.nextSegmentId++;case POSTPONED:return hoistableState=segment.id,segment.lastPushedText=!1,segment.textEmbedded=!1,request=request.renderState,writeChunk(destination,placeholder1),writeChunk(destination,request.placeholderPrefix),request=hoistableState.toString(16),writeChunk(destination,request),!!destination.write(placeholder2);case COMPLETED:segment.status=FLUSHED;var r=!0,chunks=segment.chunks,chunkIdx=0;segment=segment.children;for(var childIdx=0;childIdx<segment.length;childIdx++){for(r=segment[childIdx];chunkIdx<r.index;chunkIdx++)writeChunk(destination,chunks[chunkIdx]);r=flushSegment(request,destination,r,hoistableState)}for(;chunkIdx<chunks.length-1;chunkIdx++)writeChunk(destination,chunks[chunkIdx]);return chunkIdx<chunks.length&&(r=!!destination.write(chunks[chunkIdx])),r;case ABORTED:return!0;default:throw Error("Aborted, errored or already flushed boundaries should not be flushed again. This is a bug in React.")}}var flushedByteSize=0;function flushSegment(request,destination,segment,hoistableState){var boundary=segment.boundary;if(boundary===null)return flushSubtree(request,destination,segment,hoistableState);if(boundary.parentFlushed=!0,boundary.status===CLIENT_RENDERED){var row=boundary.row;row!==null&&--row.pendingTasks===0&&finishSuspenseListRow(request,row),row=boundary.errorDigest;var errorMessage=boundary.errorMessage,errorStack=boundary.errorStack;boundary=boundary.errorComponentStack,destination.write(startClientRenderedSuspenseBoundary),writeChunk(destination,clientRenderedSuspenseBoundaryError1),row&&(writeChunk(destination,clientRenderedSuspenseBoundaryError1A),writeChunk(destination,escapeTextForBrowser(row)),writeChunk(destination,clientRenderedSuspenseBoundaryErrorAttrInterstitial)),errorMessage&&(writeChunk(destination,clientRenderedSuspenseBoundaryError1B),writeChunk(destination,escapeTextForBrowser(errorMessage)),writeChunk(destination,clientRenderedSuspenseBoundaryErrorAttrInterstitial)),errorStack&&(writeChunk(destination,clientRenderedSuspenseBoundaryError1C),writeChunk(destination,escapeTextForBrowser(errorStack)),writeChunk(destination,clientRenderedSuspenseBoundaryErrorAttrInterstitial)),boundary&&(writeChunk(destination,clientRenderedSuspenseBoundaryError1D),writeChunk(destination,escapeTextForBrowser(boundary)),writeChunk(destination,clientRenderedSuspenseBoundaryErrorAttrInterstitial)),destination.write(clientRenderedSuspenseBoundaryError2),flushSubtree(request,destination,segment,hoistableState)}else if(boundary.status!==COMPLETED)boundary.status===PENDING&&(boundary.rootSegmentID=request.nextSegmentId++),0<boundary.completedSegments.length&&request.partialBoundaries.push(boundary),writeStartPendingSuspenseBoundary(destination,request.renderState,boundary.rootSegmentID),hoistableState&&hoistHoistables(hoistableState,boundary.fallbackState),flushSubtree(request,destination,segment,hoistableState);else if(!flushingPartialBoundaries&&isEligibleForOutlining(request,boundary)&&(flushedByteSize+boundary.byteSize>request.progressiveChunkSize||hasSuspenseyContent(boundary.contentState)))boundary.rootSegmentID=request.nextSegmentId++,request.completedBoundaries.push(boundary),writeStartPendingSuspenseBoundary(destination,request.renderState,boundary.rootSegmentID),flushSubtree(request,destination,segment,hoistableState);else{if(flushedByteSize+=boundary.byteSize,hoistableState&&hoistHoistables(hoistableState,boundary.contentState),segment=boundary.row,segment!==null&&isEligibleForOutlining(request,boundary)&&--segment.pendingTasks===0&&finishSuspenseListRow(request,segment),destination.write(startCompletedSuspenseBoundary),segment=boundary.completedSegments,segment.length!==1)throw Error("A previously unvisited boundary must have exactly one root segment. This is a bug in React.");flushSegment(request,destination,segment[0],hoistableState)}return!!destination.write(endSuspenseBoundary)}function flushSegmentContainer(request,destination,segment,hoistableState){return writeStartSegment(destination,request.renderState,segment.parentFormatContext,segment.id),flushSegment(request,destination,segment,hoistableState),writeEndSegment(destination,segment.parentFormatContext)}function flushCompletedBoundary(request,destination,boundary){flushedByteSize=boundary.byteSize;for(var completedSegments=boundary.completedSegments,i=0;i<completedSegments.length;i++)flushPartiallyCompletedSegment(request,destination,boundary,completedSegments[i]);completedSegments.length=0,completedSegments=boundary.row,completedSegments!==null&&isEligibleForOutlining(request,boundary)&&--completedSegments.pendingTasks===0&&finishSuspenseListRow(request,completedSegments),writeHoistablesForBoundary(destination,boundary.contentState,request.renderState),completedSegments=request.resumableState,request=request.renderState,i=boundary.rootSegmentID,boundary=boundary.contentState;var requiresStyleInsertion=request.stylesToHoist;return request.stylesToHoist=!1,writeChunk(destination,request.startInlineScript),writeChunk(destination,endOfStartTag),requiresStyleInsertion?((completedSegments.instructions&SentClientRenderFunction)===NothingSent&&(completedSegments.instructions|=SentClientRenderFunction,writeChunk(destination,clientRenderScriptFunctionOnly)),(completedSegments.instructions&SentCompleteBoundaryFunction)===NothingSent&&(completedSegments.instructions|=SentCompleteBoundaryFunction,writeChunk(destination,completeBoundaryScriptFunctionOnly)),(completedSegments.instructions&SentStyleInsertionFunction)===NothingSent?(completedSegments.instructions|=SentStyleInsertionFunction,writeChunk(destination,completeBoundaryWithStylesScript1FullPartial)):writeChunk(destination,completeBoundaryWithStylesScript1Partial)):((completedSegments.instructions&SentCompleteBoundaryFunction)===NothingSent&&(completedSegments.instructions|=SentCompleteBoundaryFunction,writeChunk(destination,completeBoundaryScriptFunctionOnly)),writeChunk(destination,completeBoundaryScript1Partial)),completedSegments=i.toString(16),writeChunk(destination,request.boundaryPrefix),writeChunk(destination,completedSegments),writeChunk(destination,completeBoundaryScript2),writeChunk(destination,request.segmentPrefix),writeChunk(destination,completedSegments),requiresStyleInsertion?(writeChunk(destination,completeBoundaryScript3a),writeStyleResourceDependenciesInJS(destination,boundary)):writeChunk(destination,completeBoundaryScript3b),boundary=!!destination.write(completeBoundaryScriptEnd),writeBootstrap(destination,request)&&boundary}function flushPartiallyCompletedSegment(request,destination,boundary,segment){if(segment.status===FLUSHED)return!0;var hoistableState=boundary.contentState,segmentID=segment.id;if(segmentID===-1){if((segment.id=boundary.rootSegmentID)===-1)throw Error("A root segment ID must have been assigned by now. This is a bug in React.");return flushSegmentContainer(request,destination,segment,hoistableState)}if(segmentID===boundary.rootSegmentID)return flushSegmentContainer(request,destination,segment,hoistableState);return flushSegmentContainer(request,destination,segment,hoistableState),boundary=request.resumableState,request=request.renderState,writeChunk(destination,request.startInlineScript),writeChunk(destination,endOfStartTag),(boundary.instructions&SentCompleteSegmentFunction)===NothingSent?(boundary.instructions|=SentCompleteSegmentFunction,writeChunk(destination,completeSegmentScript1Full)):writeChunk(destination,completeSegmentScript1Partial),writeChunk(destination,request.segmentPrefix),segmentID=segmentID.toString(16),writeChunk(destination,segmentID),writeChunk(destination,completeSegmentScript2),writeChunk(destination,request.placeholderPrefix),writeChunk(destination,segmentID),destination=!!destination.write(completeSegmentScriptEnd),destination}var flushingPartialBoundaries=!1;function flushCompletedQueues(request,destination){try{if(!(0<request.pendingRootTasks)){var i,completedRootSegment=request.completedRootSegment;if(completedRootSegment!==null){if(completedRootSegment.status===POSTPONED)return;var completedPreambleSegments=request.completedPreambleSegments;if(completedPreambleSegments===null)return;flushedByteSize=request.byteSize;var{resumableState,renderState}=request,preamble=renderState.preamble,{htmlChunks,headChunks}=preamble,i$jscomp$0;if(htmlChunks){for(i$jscomp$0=0;i$jscomp$0<htmlChunks.length;i$jscomp$0++)writeChunk(destination,htmlChunks[i$jscomp$0]);if(headChunks)for(i$jscomp$0=0;i$jscomp$0<headChunks.length;i$jscomp$0++)writeChunk(destination,headChunks[i$jscomp$0]);else writeChunk(destination,startChunkForTag("head")),writeChunk(destination,endOfStartTag)}else if(headChunks)for(i$jscomp$0=0;i$jscomp$0<headChunks.length;i$jscomp$0++)writeChunk(destination,headChunks[i$jscomp$0]);var charsetChunks=renderState.charsetChunks;for(i$jscomp$0=0;i$jscomp$0<charsetChunks.length;i$jscomp$0++)writeChunk(destination,charsetChunks[i$jscomp$0]);charsetChunks.length=0,renderState.preconnects.forEach(flushResource,destination),renderState.preconnects.clear();var viewportChunks=renderState.viewportChunks;for(i$jscomp$0=0;i$jscomp$0<viewportChunks.length;i$jscomp$0++)writeChunk(destination,viewportChunks[i$jscomp$0]);viewportChunks.length=0,renderState.fontPreloads.forEach(flushResource,destination),renderState.fontPreloads.clear(),renderState.highImagePreloads.forEach(flushResource,destination),renderState.highImagePreloads.clear(),currentlyFlushingRenderState=renderState,renderState.styles.forEach(flushStylesInPreamble,destination),currentlyFlushingRenderState=null;var importMapChunks=renderState.importMapChunks;for(i$jscomp$0=0;i$jscomp$0<importMapChunks.length;i$jscomp$0++)writeChunk(destination,importMapChunks[i$jscomp$0]);importMapChunks.length=0,renderState.bootstrapScripts.forEach(flushResource,destination),renderState.scripts.forEach(flushResource,destination),renderState.scripts.clear(),renderState.bulkPreloads.forEach(flushResource,destination),renderState.bulkPreloads.clear(),htmlChunks||headChunks||(resumableState.instructions|=SentCompletedShellId);var hoistableChunks=renderState.hoistableChunks;for(i$jscomp$0=0;i$jscomp$0<hoistableChunks.length;i$jscomp$0++)writeChunk(destination,hoistableChunks[i$jscomp$0]);for(resumableState=hoistableChunks.length=0;resumableState<completedPreambleSegments.length;resumableState++){var segments=completedPreambleSegments[resumableState];for(renderState=0;renderState<segments.length;renderState++)flushSegment(request,destination,segments[renderState],null)}var preamble$jscomp$0=request.renderState.preamble,headChunks$jscomp$0=preamble$jscomp$0.headChunks;(preamble$jscomp$0.htmlChunks||headChunks$jscomp$0)&&writeChunk(destination,endChunkForTag("head"));var bodyChunks=preamble$jscomp$0.bodyChunks;if(bodyChunks)for(completedPreambleSegments=0;completedPreambleSegments<bodyChunks.length;completedPreambleSegments++)writeChunk(destination,bodyChunks[completedPreambleSegments]);flushSegment(request,destination,completedRootSegment,null),request.completedRootSegment=null;var renderState$jscomp$0=request.renderState;if(request.allPendingTasks!==0||request.clientRenderedBoundaries.length!==0||request.completedBoundaries.length!==0||request.trackedPostpones!==null&&(request.trackedPostpones.rootNodes.length!==0||request.trackedPostpones.rootSlots!==null)){var resumableState$jscomp$0=request.resumableState;if((resumableState$jscomp$0.instructions&SentMarkShellTime)===NothingSent){if(resumableState$jscomp$0.instructions|=SentMarkShellTime,writeChunk(destination,renderState$jscomp$0.startInlineScript),(resumableState$jscomp$0.instructions&SentCompletedShellId)===NothingSent){resumableState$jscomp$0.instructions|=SentCompletedShellId;var shellId="_"+resumableState$jscomp$0.idPrefix+"R_";writeChunk(destination,completedShellIdAttributeStart),writeChunk(destination,escapeTextForBrowser(shellId)),writeChunk(destination,attributeEnd)}writeChunk(destination,endOfStartTag),writeChunk(destination,shellTimeRuntimeScript),destination.write(endInlineScript)}}writeBootstrap(destination,renderState$jscomp$0)}var renderState$jscomp$1=request.renderState;completedRootSegment=0;var viewportChunks$jscomp$0=renderState$jscomp$1.viewportChunks;for(completedRootSegment=0;completedRootSegment<viewportChunks$jscomp$0.length;completedRootSegment++)writeChunk(destination,viewportChunks$jscomp$0[completedRootSegment]);viewportChunks$jscomp$0.length=0,renderState$jscomp$1.preconnects.forEach(flushResource,destination),renderState$jscomp$1.preconnects.clear(),renderState$jscomp$1.fontPreloads.forEach(flushResource,destination),renderState$jscomp$1.fontPreloads.clear(),renderState$jscomp$1.highImagePreloads.forEach(flushResource,destination),renderState$jscomp$1.highImagePreloads.clear(),renderState$jscomp$1.styles.forEach(preloadLateStyles,destination),renderState$jscomp$1.scripts.forEach(flushResource,destination),renderState$jscomp$1.scripts.clear(),renderState$jscomp$1.bulkPreloads.forEach(flushResource,destination),renderState$jscomp$1.bulkPreloads.clear();var hoistableChunks$jscomp$0=renderState$jscomp$1.hoistableChunks;for(completedRootSegment=0;completedRootSegment<hoistableChunks$jscomp$0.length;completedRootSegment++)writeChunk(destination,hoistableChunks$jscomp$0[completedRootSegment]);hoistableChunks$jscomp$0.length=0;var clientRenderedBoundaries=request.clientRenderedBoundaries;for(i=0;i<clientRenderedBoundaries.length;i++){var boundary=clientRenderedBoundaries[i];renderState$jscomp$1=destination;var{resumableState:resumableState$jscomp$1,renderState:renderState$jscomp$2}=request,id=boundary.rootSegmentID,errorDigest=boundary.errorDigest,errorMessage=boundary.errorMessage,errorStack=boundary.errorStack,errorComponentStack=boundary.errorComponentStack;if(writeChunk(renderState$jscomp$1,renderState$jscomp$2.startInlineScript),writeChunk(renderState$jscomp$1,endOfStartTag),(resumableState$jscomp$1.instructions&SentClientRenderFunction)===NothingSent?(resumableState$jscomp$1.instructions|=SentClientRenderFunction,writeChunk(renderState$jscomp$1,clientRenderScript1Full)):writeChunk(renderState$jscomp$1,clientRenderScript1Partial),writeChunk(renderState$jscomp$1,renderState$jscomp$2.boundaryPrefix),writeChunk(renderState$jscomp$1,id.toString(16)),writeChunk(renderState$jscomp$1,clientRenderScript1A),errorDigest||errorMessage||errorStack||errorComponentStack)writeChunk(renderState$jscomp$1,clientRenderErrorScriptArgInterstitial),writeChunk(renderState$jscomp$1,escapeJSStringsForInstructionScripts(errorDigest||""));if(errorMessage||errorStack||errorComponentStack)writeChunk(renderState$jscomp$1,clientRenderErrorScriptArgInterstitial),writeChunk(renderState$jscomp$1,escapeJSStringsForInstructionScripts(errorMessage||""));if(errorStack||errorComponentStack)writeChunk(renderState$jscomp$1,clientRenderErrorScriptArgInterstitial),writeChunk(renderState$jscomp$1,escapeJSStringsForInstructionScripts(errorStack||""));errorComponentStack&&(writeChunk(renderState$jscomp$1,clientRenderErrorScriptArgInterstitial),writeChunk(renderState$jscomp$1,escapeJSStringsForInstructionScripts(errorComponentStack)));var JSCompiler_inline_result=!!renderState$jscomp$1.write(clientRenderScriptEnd);if(!JSCompiler_inline_result){request.destination=null,i++,clientRenderedBoundaries.splice(0,i);return}}clientRenderedBoundaries.splice(0,i);var completedBoundaries=request.completedBoundaries;for(i=0;i<completedBoundaries.length;i++)if(!flushCompletedBoundary(request,destination,completedBoundaries[i])){request.destination=null,i++,completedBoundaries.splice(0,i);return}completedBoundaries.splice(0,i),flushingPartialBoundaries=!0;var partialBoundaries=request.partialBoundaries;for(i=0;i<partialBoundaries.length;i++){a:{clientRenderedBoundaries=request,boundary=destination;var boundary$jscomp$0=partialBoundaries[i];flushedByteSize=boundary$jscomp$0.byteSize;var completedSegments=boundary$jscomp$0.completedSegments;for(JSCompiler_inline_result=0;JSCompiler_inline_result<completedSegments.length;JSCompiler_inline_result++)if(!flushPartiallyCompletedSegment(clientRenderedBoundaries,boundary,boundary$jscomp$0,completedSegments[JSCompiler_inline_result])){JSCompiler_inline_result++,completedSegments.splice(0,JSCompiler_inline_result);var JSCompiler_inline_result$jscomp$0=!1;break a}completedSegments.splice(0,JSCompiler_inline_result);var row=boundary$jscomp$0.row;row!==null&&row.together&&boundary$jscomp$0.pendingTasks===1&&(row.pendingTasks===1?unblockSuspenseListRow(clientRenderedBoundaries,row,row.hoistables):row.pendingTasks--),JSCompiler_inline_result$jscomp$0=writeHoistablesForBoundary(boundary,boundary$jscomp$0.contentState,clientRenderedBoundaries.renderState)}if(!JSCompiler_inline_result$jscomp$0){request.destination=null,i++,partialBoundaries.splice(0,i);return}}partialBoundaries.splice(0,i),flushingPartialBoundaries=!1;var largeBoundaries=request.completedBoundaries;for(i=0;i<largeBoundaries.length;i++)if(!flushCompletedBoundary(request,destination,largeBoundaries[i])){request.destination=null,i++,largeBoundaries.splice(0,i);return}largeBoundaries.splice(0,i)}}finally{flushingPartialBoundaries=!1,request.allPendingTasks===0&&request.clientRenderedBoundaries.length===0&&request.completedBoundaries.length===0?(request.flushScheduled=!1,i=request.resumableState,i.hasBody&&writeChunk(destination,endChunkForTag("body")),i.hasHtml&&writeChunk(destination,endChunkForTag("html")),flushBuffered(destination),request.abortableTasks.size!==0&&console.error("There was still abortable task at the root when we closed. This is a bug in React."),request.status=CLOSED,destination.end(),request.destination=null):flushBuffered(destination)}}function startWork(request){request.flushScheduled=request.destination!==null,scheduleMicrotask(function(){return performWork(request)}),setTimeout(function(){request.status===10&&(request.status=11),request.trackedPostpones===null&&safelyEmitEarlyPreloads(request,request.pendingRootTasks===0)},0)}function enqueueFlush(request){request.flushScheduled===!1&&request.pingedTasks.length===0&&request.destination!==null&&(request.flushScheduled=!0,setTimeout(function(){var destination=request.destination;destination?flushCompletedQueues(request,destination):request.flushScheduled=!1},0))}function abort(request,reason){if(request.status===11||request.status===10)request.status=12;try{var abortableTasks=request.abortableTasks;if(0<abortableTasks.size){var error=reason===void 0?Error("The render was aborted by the server without a reason."):typeof reason==="object"&&reason!==null&&typeof reason.then==="function"?Error("The render was aborted by the server with a promise."):reason;request.fatalError=error,abortableTasks.forEach(function(task){var prevTaskInDEV=currentTaskInDEV,prevGetCurrentStackImpl=ReactSharedInternals.getCurrentStack;currentTaskInDEV=task,ReactSharedInternals.getCurrentStack=getCurrentStackInDEV;try{abortTask(task,request,error)}finally{currentTaskInDEV=prevTaskInDEV,ReactSharedInternals.getCurrentStack=prevGetCurrentStackImpl}}),abortableTasks.clear()}request.destination!==null&&flushCompletedQueues(request,request.destination)}catch(error$4){reason={},logRecoverableError(request,error$4,reason,null),fatalError(request,error$4,reason,null)}}function addToReplayParent(node,parentKeyPath,trackedPostpones){if(parentKeyPath===null)trackedPostpones.rootNodes.push(node);else{var workingMap=trackedPostpones.workingMap,parentNode=workingMap.get(parentKeyPath);parentNode===void 0&&(parentNode=[parentKeyPath[1],parentKeyPath[2],[],null],workingMap.set(parentKeyPath,parentNode),addToReplayParent(parentNode,parentKeyPath[0],trackedPostpones)),parentNode[2].push(node)}}var isomorphicReactPackageVersion$jscomp$inline_766=React.version;if(isomorphicReactPackageVersion$jscomp$inline_766!=="19.2.8")throw Error(`Incompatible React versions: The "react" and "react-dom" packages must have the exact same version. Instead got:
350
350
  - react: `+(isomorphicReactPackageVersion$jscomp$inline_766+`
351
351
  - react-dom: 19.2.8
352
- Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadableStream=function(children,options){return new Promise(function(resolve,reject){var onFatalError,onAllReady,allReady=new Promise(function(res,rej){onAllReady=res,onFatalError=rej}),onHeaders=options?options.onHeaders:void 0,onHeadersImpl;onHeaders&&(onHeadersImpl=function(headersDescriptor){onHeaders(new Headers(headersDescriptor))});var resumableState=createResumableState(options?options.identifierPrefix:void 0,options?options.unstable_externalRuntimeSrc:void 0,options?options.bootstrapScriptContent:void 0,options?options.bootstrapScripts:void 0,options?options.bootstrapModules:void 0),request$jscomp$0=createRequest(children,resumableState,createRenderState(resumableState,options?options.nonce:void 0,options?options.unstable_externalRuntimeSrc:void 0,options?options.importMap:void 0,onHeadersImpl,options?options.maxHeadersLength:void 0),createRootFormatContext(options?options.namespaceURI:void 0),options?options.progressiveChunkSize:void 0,options?options.onError:void 0,onAllReady,function(){var stream=new ReadableStream({type:"direct",pull:function(controller){var request=request$jscomp$0;if(request.status===13)request.status=CLOSED,closeWithError(controller,request.fatalError);else if(request.status!==CLOSED&&request.destination===null){request.destination=controller;try{flushCompletedQueues(request,controller)}catch(error){controller={},logRecoverableError(request,error,controller,null),fatalError(request,error,controller,null)}}},cancel:function(reason){request$jscomp$0.destination=null,abort(request$jscomp$0,reason)}},{highWaterMark:2048});stream.allReady=allReady,resolve(stream)},function(error){allReady.catch(function(){}),reject(error)},onFatalError,options?options.onPostpone:void 0,options?options.formState:void 0);if(options&&options.signal){var signal=options.signal;if(signal.aborted)abort(request$jscomp$0,signal.reason);else{var listener=function(){abort(request$jscomp$0,signal.reason),signal.removeEventListener("abort",listener)};signal.addEventListener("abort",listener)}}startWork(request$jscomp$0)})},$version="19.2.8";var react_dom_server_legacy_browser_development=__toESM(require_react_dom_server_legacy_browser_development()),b,l;b=exports_react_dom_server_bun_development,l=react_dom_server_legacy_browser_development;var $version2=b.version,$renderToReadableStream2=b.renderToReadableStream,$resume=b.resume,$renderToString=l.renderToString,$renderToStaticMarkup=l.renderToStaticMarkup;var import_react=__toESM(require_react_development(),1);function descend(body,index){return body===null?null:{snippetId:body.snippetId,path:[...body.path,index]}}function enterSnippet(body,snippetId){if(body===null)return{snippetId,path:[]};let here=`${body.snippetId}#${body.path.join(".")}`,outer=body.path.length===0?body.at??[]:[];return{snippetId,path:[],at:[here,...outer]}}function bodyAttributes(body){if(body===null)return{};return{"data-snippet-id":body.snippetId,"data-snippet-path":body.path.join("."),...body.at&&body.path.length===0?{"data-snippet-at":body.at.join(" ")}:{}}}class UnknownComponentError extends Error{ref;constructor(ref){super(`Unknown component $ref="${ref}". Not in the active component provider's registry. ("$ref" is a library component or registered extension; the MCP compose tool resolves snippet tags to $snippet nodes.)`);this.ref=ref;this.name="UnknownComponentError"}}class UnknownSnippetError extends Error{snippetId;constructor(snippetId){super(`Unknown snippet $snippet="${snippetId}".`);this.snippetId=snippetId;this.name="UnknownSnippetError"}}class SnippetCycleError extends Error{snippetId;cycle;constructor(snippetId,stack){super(`Snippet cycle detected: ${[...stack,snippetId].join(" \u2192 ")}`);this.name="SnippetCycleError",this.snippetId=snippetId,this.cycle=stack}}class SnippetParamError extends Error{snippetId;paramName;constructor(snippetId,paramName,message){super(message??`Snippet "${snippetId}": required param "${paramName}" not supplied.`);this.snippetId=snippetId;this.paramName=paramName;this.name="SnippetParamError"}}class ParamRefError extends Error{paramName;constructor(paramName){super(`$param "${paramName}" appears outside a snippet body.`);this.paramName=paramName;this.name="ParamRefError"}}function resolveSnippetBody(instance,snippet){let{args,missing}=resolveSnippetArgs(snippet,instance.args??{});if(missing.length>0)throw new SnippetParamError(snippet.id,missing[0]);let substituted=substituteSnippetParams(snippet.tree,args);if(substituted.missing.length>0)throw new SnippetParamError(snippet.id,substituted.missing[0]);if(substituted.invalid.length>0){let bad=substituted.invalid[0];throw new SnippetParamError(snippet.id,bad.param,`Snippet "${snippet.id}": param "${bad.param}" resolved to a ${bad.valueType} but sits in a \`children\` array, where only nodes render. Pass a scalar param as a prop value, e.g. {"$ref":"Heading","props":{"children":{"$param":"${bad.param}"}}}. Only \`type:"node"\` params belong directly in children.`)}let body=substituted.value;if(instance.$overrides)body=applySnippetOverrides(body,instance.$overrides);let extra=instance.$extraClassName?.trim();if(!extra)return body;return applySnippetExtraClassName(body,extra)}function buildTree(node,opts,path=[],stack=[],lockedPath=null,body=null){if(isSnippetInstance(node)){let snippets=opts.snippets;if(!snippets)throw new UnknownSnippetError(node.$snippet);let snippet=snippets.get(node.$snippet);if(!snippet)throw new UnknownSnippetError(node.$snippet);if(stack.includes(snippet.id))throw new SnippetCycleError(snippet.id,stack);let resolved=resolveSnippetBody(node,snippet);return buildTree(resolved,opts,path,[...stack,snippet.id],lockedPath??path,enterSnippet(body,snippet.id))}if(isParamRef(node))throw new ParamRefError(node.$param);if(!isComponentNode(node))throw Error(`buildTree: expected a component, snippet instance, or node param in a node position but got ${JSON.stringify(node)}`);if(isRepoNode(node))return buildRepoNode(node,opts,path,stack,lockedPath,body);let Component=node.$ref===PARAM_TAG_REF?ParamTag:opts.registry[node.$ref];if(!Component)throw new UnknownComponentError(node.$ref);let{children:childrenProp,...restProps}=node.props??{},dataNodePath=(lockedPath??path).join("."),children;if(Array.isArray(node.children)&&node.children.length>0){if(children=node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>buildTree(c,opts,[...path,i,j],stack,lockedPath,null)):buildTree(child,opts,[...path,i],stack,lockedPath,descend(body,i))),Array.isArray(children)&&children.length===1)children=children[0]}else if(childrenProp!==void 0)children=resolvePropChildren(childrenProp,opts,path,stack,lockedPath);return import_react.createElement(Component,{...restProps,"data-node-path":dataNodePath,...bodyAttributes(body),key:dataNodePath||"root"},children)}function isNodeLike(v){return typeof v==="object"&&v!==null&&!Array.isArray(v)&&(isComponentNode(v)||isSnippetInstance(v)||isParamRef(v))}function resolvePropChildren(value,opts,path,stack,lockedPath){if(isNodeLike(value))return buildTree(value,opts,path,stack,lockedPath);if(Array.isArray(value))return value.map((item,i)=>{if(!isNodeLike(item))return item;let el=buildTree(item,opts,path,stack,lockedPath);return import_react.cloneElement(el,{key:`inline-${i}`})});return value}function buildRoot(node,opts){return import_react.createElement(import_react.Fragment,null,buildTree(node,opts))}function resolveSnippetBodyForEdit(body,paramDefaults,snippetId){if(isParamRef(body))return paramTagNode(body.$param);if(isSnippetInstance(body))return body;if(!isComponentNode(body))return body;let nextProps=body.props?substituteSnippetParams(body.props,paramDefaults).value:void 0,nextChildren=body.children?.map((c)=>resolveSnippetBodyForEdit(c,paramDefaults,snippetId));return{...body,...nextProps?{props:nextProps}:{},...nextChildren?{children:nextChildren}:{}}}var PARAM_TAG_REF="velloo:param-tag";function paramTagNode(name){return{$ref:PARAM_TAG_REF,props:{name}}}function snippetParamPlaceholder(param){if(param.default!==void 0)return param.default;switch(param.type){case"node":return paramTagNode(param.name);case"number":return 0;case"boolean":return!1;case"icon":return"Circle";case"color":return"#7c3aed";case"enum":return param.enum?.[0]??"";default:return`$${param.name}`}}var PARAM_TAG_STYLE={display:"inline-flex",alignItems:"center",alignSelf:"flex-start",borderRadius:"0.375rem",border:"1px dashed var(--color-border, #d4d4d8)",padding:"0.05rem 0.4rem",color:"var(--color-muted-foreground, #71717a)",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.75rem",lineHeight:1.6,whiteSpace:"nowrap"};function ParamTag({name,...rest}){return import_react.createElement("span",{...rest,"data-velloo-param":name,style:PARAM_TAG_STYLE},`$${name}`)}function repoProxyInstance(node,snippet){let props=node.props??{},args={};for(let param of snippet.params)if(param.name==="children"&&param.type==="node"&&node.children?.length)args.children=node.children.length===1?node.children[0]:node.children;else if(param.name in props)args[param.name]=props[param.name];return{$snippet:snippet.id,args}}function buildRepoNode(node,opts,path,stack,lockedPath,body){let proxy=node.$repo.proxy?opts.snippets?.get(node.$repo.proxy):void 0;if(proxy&&!stack.includes(proxy.id))return buildTree(repoProxyInstance(node,proxy),opts,path,stack,lockedPath??path);let dataNodePath=(lockedPath??path).join("."),textChild=node.props?.children,children=node.children&&node.children.length>0?node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>buildTree(c,opts,[...path,i,j],stack,lockedPath,null)):buildTree(child,opts,[...path,i],stack,lockedPath,descend(body,i))):typeof textChild==="string"||typeof textChild==="number"?textChild:null;return import_react.createElement(RepoPlaceholder,{label:node.$ref,source:node.$repo.importPath,"data-node-path":dataNodePath,...bodyAttributes(body),key:dataNodePath||"root",children})}var REPO_FRAME_STYLE={position:"relative",border:"1px dashed var(--color-border, #d4d4d8)",borderRadius:"0.5rem",padding:"1.5rem 0.75rem 0.75rem",minHeight:"2.5rem"},REPO_LABEL_STYLE={position:"absolute",top:"0.25rem",left:"0.5rem",color:"var(--color-muted-foreground, #71717a)",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.6875rem",lineHeight:1.4,pointerEvents:"none"};function RepoPlaceholder({label,source,children,...rest}){return import_react.createElement("div",{...rest,"data-velloo-repo":label,style:REPO_FRAME_STYLE,title:`${label} from ${source}`},import_react.createElement("span",{style:REPO_LABEL_STYLE},`<${label}>`),children)}var CANVAS_RUNTIME=`
352
+ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadableStream=function(children,options){return new Promise(function(resolve,reject){var onFatalError,onAllReady,allReady=new Promise(function(res,rej){onAllReady=res,onFatalError=rej}),onHeaders=options?options.onHeaders:void 0,onHeadersImpl;onHeaders&&(onHeadersImpl=function(headersDescriptor){onHeaders(new Headers(headersDescriptor))});var resumableState=createResumableState(options?options.identifierPrefix:void 0,options?options.unstable_externalRuntimeSrc:void 0,options?options.bootstrapScriptContent:void 0,options?options.bootstrapScripts:void 0,options?options.bootstrapModules:void 0),request$jscomp$0=createRequest(children,resumableState,createRenderState(resumableState,options?options.nonce:void 0,options?options.unstable_externalRuntimeSrc:void 0,options?options.importMap:void 0,onHeadersImpl,options?options.maxHeadersLength:void 0),createRootFormatContext(options?options.namespaceURI:void 0),options?options.progressiveChunkSize:void 0,options?options.onError:void 0,onAllReady,function(){var stream=new ReadableStream({type:"direct",pull:function(controller){var request=request$jscomp$0;if(request.status===13)request.status=CLOSED,closeWithError(controller,request.fatalError);else if(request.status!==CLOSED&&request.destination===null){request.destination=controller;try{flushCompletedQueues(request,controller)}catch(error){controller={},logRecoverableError(request,error,controller,null),fatalError(request,error,controller,null)}}},cancel:function(reason){request$jscomp$0.destination=null,abort(request$jscomp$0,reason)}},{highWaterMark:2048});stream.allReady=allReady,resolve(stream)},function(error){allReady.catch(function(){}),reject(error)},onFatalError,options?options.onPostpone:void 0,options?options.formState:void 0);if(options&&options.signal){var signal=options.signal;if(signal.aborted)abort(request$jscomp$0,signal.reason);else{var listener=function(){abort(request$jscomp$0,signal.reason),signal.removeEventListener("abort",listener)};signal.addEventListener("abort",listener)}}startWork(request$jscomp$0)})},$version="19.2.8";var react_dom_server_legacy_browser_development=__toESM(require_react_dom_server_legacy_browser_development()),b,l;b=exports_react_dom_server_bun_development,l=react_dom_server_legacy_browser_development;var $version2=b.version,$renderToReadableStream2=b.renderToReadableStream,$resume=b.resume,$renderToString=l.renderToString,$renderToStaticMarkup=l.renderToStaticMarkup;var import_react=__toESM(require_react_development(),1);function descend(body,index){return body===null?null:{snippetId:body.snippetId,path:[...body.path,index]}}function enterSnippet(body,snippetId){if(body===null)return{snippetId,path:[]};let here=`${body.snippetId}#${body.path.join(".")}`,outer=body.path.length===0?body.at??[]:[];return{snippetId,path:[],at:[here,...outer]}}function bodyAttributes(body){if(body===null)return{};return{"data-snippet-id":body.snippetId,"data-snippet-path":body.path.join("."),...body.at&&body.path.length===0?{"data-snippet-at":body.at.join(" ")}:{}}}var TEXT_CHILDREN_ATTRIBUTE="data-node-text";class UnknownComponentError extends Error{ref;constructor(ref){super(`Unknown component $ref="${ref}". Not in the active component provider's registry. ("$ref" is a library component or registered extension; the MCP compose tool resolves snippet tags to $snippet nodes.)`);this.ref=ref;this.name="UnknownComponentError"}}class UnknownSnippetError extends Error{snippetId;constructor(snippetId){super(`Unknown snippet $snippet="${snippetId}".`);this.snippetId=snippetId;this.name="UnknownSnippetError"}}class SnippetCycleError extends Error{snippetId;cycle;constructor(snippetId,stack){super(`Snippet cycle detected: ${[...stack,snippetId].join(" \u2192 ")}`);this.name="SnippetCycleError",this.snippetId=snippetId,this.cycle=stack}}class SnippetParamError extends Error{snippetId;paramName;constructor(snippetId,paramName,message){super(message??`Snippet "${snippetId}": required param "${paramName}" not supplied.`);this.snippetId=snippetId;this.paramName=paramName;this.name="SnippetParamError"}}class ParamRefError extends Error{paramName;constructor(paramName){super(`$param "${paramName}" appears outside a snippet body.`);this.paramName=paramName;this.name="ParamRefError"}}function resolveSnippetBody(instance,snippet){let{args,missing}=resolveSnippetArgs(snippet,instance.args??{});if(missing.length>0)throw new SnippetParamError(snippet.id,missing[0]);let substituted=substituteSnippetParams(snippet.tree,args);if(substituted.missing.length>0)throw new SnippetParamError(snippet.id,substituted.missing[0]);if(substituted.invalid.length>0){let bad=substituted.invalid[0];throw new SnippetParamError(snippet.id,bad.param,`Snippet "${snippet.id}": param "${bad.param}" resolved to ${bad.valueType==="null"?"null":`a ${bad.valueType}`} but sits in a \`children\` array, where content renders. A string or number there is text and a \`type:"node"\` param is a subtree; to show or hide something by a flag, use {"$if":"${bad.param}","then":\u2026}.`)}let body=substituted.value;if(instance.$overrides)body=applySnippetOverrides(body,instance.$overrides);let extra=instance.$extraClassName?.trim();if(!extra)return body;return applySnippetExtraClassName(body,extra)}function buildTree(node,opts,path=[],stack=[],lockedPath=null,body=null){let identity=resolveNodeIdentity(node,{library:opts.registry});switch(identity.kind){case"snippet":{let instance=identity.node,snippets=opts.snippets;if(!snippets)throw new UnknownSnippetError(instance.$snippet);let snippet=snippets.get(instance.$snippet);if(!snippet)throw new UnknownSnippetError(instance.$snippet);if(stack.includes(snippet.id))throw new SnippetCycleError(snippet.id,stack);let resolved=resolveSnippetBody(instance,snippet);return buildTree(resolved,opts,path,[...stack,snippet.id],lockedPath??path,enterSnippet(body,snippet.id))}case"param":throw new ParamRefError(identity.node.$param);case"text":return import_react.createElement(import_react.Fragment,{key:path.join(".")||"root"},identity.text);case"invalid":throw Error(`buildTree: expected a component, snippet instance, or node param in a node position but got ${JSON.stringify(identity.value)}`);case"repo":return buildRepoNode(identity.node,opts,path,stack,lockedPath,body);case"synthetic":if(identity.ref!==PARAM_TAG_REF)throw new UnknownComponentError(identity.ref);return buildComponentElement(identity.node,ParamTag,opts,path,stack,lockedPath,body);case"unresolved":throw new UnknownComponentError(identity.ref);case"component":return buildComponentElement(identity.node,identity.entry,opts,path,stack,lockedPath,body);case"extension":case"emit-as":{let Component=ownEntry(opts.registry,identity.ref);if(!Component)throw new UnknownComponentError(identity.ref);return buildComponentElement(identity.node,Component,opts,path,stack,lockedPath,body)}}}function buildChild(child,opts,path,stack,lockedPath,body){return isTextNode(child)?child.$text:buildTree(child,opts,path,stack,lockedPath,body)}function textChildrenAttribute(children,lockedPath){if(lockedPath!==null||!children)return{};let at=children.flatMap((child,i)=>!Array.isArray(child)&&nodeShape(child).kind==="text"?[i]:[]);return at.length>0?{[TEXT_CHILDREN_ATTRIBUTE]:at.join(",")}:{}}function buildComponentElement(node,Component,opts,path,stack,lockedPath,body){let{children:childrenProp,...restProps}=node.props??{},dataNodePath=(lockedPath??path).join("."),children;if(Array.isArray(node.children)&&node.children.length>0){if(children=node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>buildChild(c,opts,[...path,i,j],stack,lockedPath,null)):buildChild(child,opts,[...path,i],stack,lockedPath,descend(body,i))),Array.isArray(children)&&children.length===1)children=children[0]}else if(childrenProp!==void 0)children=resolvePropChildren(childrenProp,opts,path,stack,lockedPath);return import_react.createElement(Component,{...restProps,"data-node-path":dataNodePath,...textChildrenAttribute(node.children,lockedPath),...bodyAttributes(body),key:dataNodePath||"root"},children)}function resolvePropChildren(value,opts,path,stack,lockedPath){if(isNode(value))return buildTree(value,opts,path,stack,lockedPath);if(Array.isArray(value))return value.map((item,i)=>{if(!isNode(item))return item;let el=buildTree(item,opts,path,stack,lockedPath);return import_react.cloneElement(el,{key:`inline-${i}`})});return value}function buildRoot(node,opts){return import_react.createElement(import_react.Fragment,null,buildTree(node,opts))}function resolveSnippetBodyForEdit(body,paramDefaults,snippetId){if(isParamRef(body))return paramTagNode(body.$param);if(isSnippetInstance(body))return body;if(!isComponentNode(body))return body;let nextProps=body.props?substituteSnippetParams(body.props,paramDefaults).value:void 0,nextChildren=body.children?.map((c)=>resolveSnippetBodyForEdit(c,paramDefaults,snippetId));return{...body,...nextProps?{props:nextProps}:{},...nextChildren?{children:nextChildren}:{}}}function paramTagNode(name){return{$ref:PARAM_TAG_REF,props:{name}}}function snippetParamPlaceholder(param){if(param.default!==void 0)return param.default;switch(param.type){case"node":return paramTagNode(param.name);case"number":return 0;case"boolean":return!1;case"icon":return"Circle";case"color":return"#7c3aed";case"enum":return param.enum?.[0]??"";default:return`$${param.name}`}}var PARAM_TAG_STYLE={display:"inline-flex",alignItems:"center",alignSelf:"flex-start",borderRadius:"0.375rem",border:"1px dashed var(--color-border, #d4d4d8)",padding:"0.05rem 0.4rem",color:"var(--color-muted-foreground, #71717a)",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.75rem",lineHeight:1.6,whiteSpace:"nowrap"};function ParamTag({name,...rest}){return import_react.createElement("span",{...rest,"data-velloo-param":name,style:PARAM_TAG_STYLE},`$${name}`)}function repoProxyInstance(node,snippet){let props=node.props??{},args={};for(let param of snippet.params)if(param.name==="children"&&param.type==="node"&&node.children?.length)args.children=node.children.length===1?node.children[0]:node.children;else if(param.name in props)args[param.name]=props[param.name];return{$snippet:snippet.id,args}}function buildRepoNode(node,opts,path,stack,lockedPath,body){let proxy=node.$repo.proxy?opts.snippets?.get(node.$repo.proxy):void 0;if(proxy&&!stack.includes(proxy.id))return buildTree(repoProxyInstance(node,proxy),opts,path,stack,lockedPath??path);let dataNodePath=(lockedPath??path).join("."),textChild=node.props?.children,children=node.children&&node.children.length>0?node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>buildChild(c,opts,[...path,i,j],stack,lockedPath,null)):buildChild(child,opts,[...path,i],stack,lockedPath,descend(body,i))):typeof textChild==="string"||typeof textChild==="number"?textChild:null;return import_react.createElement(RepoPlaceholder,{label:node.$ref,source:node.$repo.importPath,"data-node-path":dataNodePath,...textChildrenAttribute(node.children,lockedPath),...bodyAttributes(body),key:dataNodePath||"root",children})}var REPO_FRAME_STYLE={position:"relative",border:"1px dashed var(--color-border, #d4d4d8)",borderRadius:"0.5rem",padding:"1.5rem 0.75rem 0.75rem",minHeight:"2.5rem"},REPO_LABEL_STYLE={position:"absolute",top:"0.25rem",left:"0.5rem",color:"var(--color-muted-foreground, #71717a)",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:"0.6875rem",lineHeight:1.4,pointerEvents:"none"};function RepoPlaceholder({label,source,children,...rest}){return import_react.createElement("div",{...rest,"data-velloo-repo":label,style:REPO_FRAME_STYLE,title:`${label} from ${source}`},import_react.createElement("span",{style:REPO_LABEL_STYLE},`<${label}>`),children)}var CANVAS_SETTLED_EVENT="velloo:canvas-settled",CANVAS_RUNTIME=`
353
353
  (() => {
354
354
  if (window.__velloo_canvas) return;
355
355
  window.__velloo_canvas = {};
@@ -364,10 +364,15 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
364
364
  var root = document.createElement("div");
365
365
  root.id = "velloo-canvas-root";
366
366
 
367
- function settleOnSsr() {
367
+ // Why the screen is on its server render, for whoever reads the page next: a
368
+ // capture cannot tell a mount that failed from a screen that never had one,
369
+ // and the server believes a bundle it built was mounted.
370
+ function settleOnSsr(reason) {
368
371
  if (root.parentNode) root.parentNode.removeChild(root);
369
372
  if (ssr) ssr.style.display = "";
373
+ window.__velloo_canvas_unmounted = String(reason || "the mount did not commit").slice(0, 400);
370
374
  window.__velloo_canvas_ready = true;
375
+ window.dispatchEvent(new Event(${JSON.stringify("velloo:canvas-settled")}));
371
376
  }
372
377
  // The SSR tree stays in the document as a visual fallback, but it must stop
373
378
  // answering to node identity the moment the mount owns the screen. Every
@@ -377,7 +382,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
377
382
  // of them at once; filtering at each call site only fixes the ones that
378
383
  // remembered to, and the capture path (a Playwright selector, not our code)
379
384
  // could not be fixed that way at all.
380
- var IDENTITY_ATTRS = ["data-node-path", "data-snippet-id", "data-snippet-path", "data-snippet-at"];
385
+ var IDENTITY_ATTRS = ["data-node-path", "data-node-text", "data-snippet-id", "data-snippet-path", "data-snippet-at"];
381
386
 
382
387
  function dropIdentity(el) {
383
388
  var stale = el.querySelectorAll("[" + IDENTITY_ATTRS.join("],[") + "]");
@@ -392,7 +397,9 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
392
397
  ssr.style.display = "none";
393
398
  dropIdentity(ssr);
394
399
  }
400
+ window.__velloo_canvas_unmounted = undefined;
395
401
  window.__velloo_canvas_ready = true;
402
+ window.dispatchEvent(new Event(${JSON.stringify("velloo:canvas-settled")}));
396
403
  }
397
404
 
398
405
  var diagnostics = [];
@@ -420,10 +427,17 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
420
427
  }
421
428
 
422
429
  var badge = null;
430
+ // An extension's placeholder is the stand-in the design asked for, drawn
431
+ // inside the mount so the rest of the screen can render for real. Badging it
432
+ // would put a fidelity warning on every frame of every screen that uses a
433
+ // chart, for the state the user deliberately chose.
434
+ function badged(item) {
435
+ return item.code !== "extension";
436
+ }
423
437
  function refreshBadge() {
424
438
  var counts = { adapted: 0, fallback: 0, proxy: 0, unavailable: 0 };
425
439
  var issues = 0;
426
- diagnostics.forEach(function (item) {
440
+ diagnostics.filter(badged).forEach(function (item) {
427
441
  if (Object.prototype.hasOwnProperty.call(counts, item.status)) counts[item.status] += 1;
428
442
  if (item.code) issues += 1;
429
443
  });
@@ -440,7 +454,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
440
454
  var parts = degraded.map(function (key) { return counts[key] + " " + key; });
441
455
  if (issues) parts.push(issues + " diagnostic" + (issues === 1 ? "" : "s"));
442
456
  badge.textContent = "Canvas: " + parts.join(" \xB7 ");
443
- badge.title = diagnostics.filter(function (item) { return item.status !== "exact" || item.code; }).map(function (item) {
457
+ badge.title = diagnostics.filter(function (item) { return badged(item) && (item.status !== "exact" || item.code); }).map(function (item) {
444
458
  return (item.name || item.id) + ": " + item.status + (item.code ? " [" + item.code + "]" : "") + (item.note ? " \u2014 " + item.note : "");
445
459
  }).join("\\n");
446
460
  }
@@ -449,8 +463,13 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
449
463
  // The stub served on a build failure still exports a no-op mountScreen, so
450
464
  // checking the export alone is not enough: calling it would settle neither
451
465
  // onReady nor onError and __velloo_canvas_ready would never flip.
452
- if (!mod || typeof mod.mountScreen !== "function" || mod.__velloo_canvas_build_errors) {
453
- settleOnSsr();
466
+ if (mod && mod.__velloo_canvas_build_errors) {
467
+ var first = mod.__velloo_canvas_build_errors[0];
468
+ settleOnSsr("the browser bundle failed to build: " + (first && first.message || "no message"));
469
+ return;
470
+ }
471
+ if (!mod || typeof mod.mountScreen !== "function") {
472
+ settleOnSsr("the browser bundle exports no mountScreen");
454
473
  return;
455
474
  }
456
475
  exposeDiagnostics(mod.__velloo_canvas_diagnostics);
@@ -464,10 +483,12 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
464
483
  onDiagnostic: report,
465
484
  el: root,
466
485
  onReady: settleOnMount,
467
- onError: settleOnSsr,
486
+ onError: function (error) {
487
+ settleOnSsr("a component threw while rendering: " + (error && error.message || error));
488
+ },
468
489
  });
469
490
  } catch (e) {
470
- settleOnSsr();
491
+ settleOnSsr("mounting threw: " + (e && e.message || e));
471
492
  }
472
493
  }).catch(function (error) {
473
494
  // A module that throws while loading (one reading location.host under a
@@ -479,7 +500,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
479
500
  refs.forEach(function (id) {
480
501
  if (id.indexOf("repo:") === 0) report({ id: id, status: "unavailable", code: "render-threw", note: note });
481
502
  });
482
- settleOnSsr();
503
+ settleOnSsr("a module threw while the bundle loaded: " + String(error && error.message || error));
483
504
  });
484
505
  })();
485
506
  `;var HOST_FILES_PREFIX="/api/host-files",HOST_STYLESHEET_ATTRIBUTE="data-velloo-host-stylesheet";var PROTOCOL_VERSION=1,SELECT_RING="#2563eb";var HOVER_RING="#60a5fa";var RENDER_ERROR_META="velloo-render-error",COMPUTED_PROPS=["fontFamily","fontSize","fontWeight","lineHeight","letterSpacing","textAlign","color","backgroundColor","borderTopWidth","borderTopColor","borderTopLeftRadius","paddingTop","paddingRight","paddingBottom","paddingLeft","marginTop","marginRight","marginBottom","marginLeft","columnGap"];var IFRAME_RUNTIME=String.raw`
@@ -520,6 +541,11 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
520
541
  // because a click there would otherwise select silently.
521
542
  ".__velloo-selected { outline: var(--velloo-ring-select) solid ${SELECT_RING} !important;" +
522
543
  " outline-offset: calc(-1 * var(--velloo-ring-select)) !important; }" +
544
+ // Text beside elements has no box to outline, so it is tinted through the
545
+ // highlight registry instead \u2014 which paints the glyphs' own line boxes
546
+ // and adds nothing to the DOM a selector could match.
547
+ "::highlight(velloo-hover) { background-color: color-mix(in srgb, ${HOVER_RING} 22%, transparent); }" +
548
+ "::highlight(velloo-selected) { background-color: color-mix(in srgb, ${SELECT_RING} 30%, transparent); }" +
523
549
  // The rest of the screen while a snippet is being edited in place.
524
550
  ".__velloo-dimmed { opacity: 0.28 !important; filter: saturate(0.4) !important; }" +
525
551
  // Scrollable frames need a *visible* affordance: wheel events forward to
@@ -614,12 +640,85 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
614
640
  thumb.addEventListener('pointercancel', up);
615
641
  });
616
642
 
617
- function findPath(target) {
643
+ // \u2500\u2500 Text beside elements \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
644
+ // A text node renders as a bare DOM text node: no wrapper, so the design's
645
+ // DOM is the app's and no selector can tell them apart. That leaves it with
646
+ // no element to carry a path. Its parent says which of its children are text
647
+ // (data-node-text="0,2"), and the DOM text nodes that are the parent's own \u2014
648
+ // not inside a child with a path of its own \u2014 are those children, in order.
649
+ // When the counts disagree (a component that writes text of its own around
650
+ // its children) there is no telling which is which, and the text selects as
651
+ // its parent \u2014 what it did before text nodes existed.
652
+ function ownTextNodes(el) {
653
+ const out = [];
654
+ const walk = (node) => {
655
+ for (let child = node.firstChild; child; child = child.nextSibling) {
656
+ if (child.nodeType === 3) {
657
+ if (child.data !== '') out.push(child);
658
+ } else if (child.nodeType === 1 && !child.hasAttribute('data-node-path')) {
659
+ walk(child);
660
+ }
661
+ }
662
+ };
663
+ walk(el);
664
+ return out;
665
+ }
666
+
667
+ // The parent element's text children: their child indices and DOM nodes.
668
+ function textChildren(el) {
669
+ const raw = el.getAttribute && el.getAttribute('data-node-text');
670
+ if (!raw) return null;
671
+ const indices = raw.split(',');
672
+ const nodes = ownTextNodes(el);
673
+ return nodes.length === indices.length ? { indices: indices, nodes: nodes } : null;
674
+ }
675
+
676
+ function rangeOf(textNode) {
677
+ const range = document.createRange();
678
+ range.selectNodeContents(textNode);
679
+ return range;
680
+ }
681
+
682
+ // The text child of \`el\` under the pointer, as a path, or null.
683
+ function textPathAt(el, x, y) {
684
+ const found = textChildren(el);
685
+ if (!found) return null;
686
+ for (let i = 0; i < found.nodes.length; i++) {
687
+ const rects = rangeOf(found.nodes[i]).getClientRects();
688
+ for (let j = 0; j < rects.length; j++) {
689
+ const r = rects[j];
690
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) {
691
+ const base = el.getAttribute('data-node-path');
692
+ return (base === '' ? '' : base + '.') + found.indices[i];
693
+ }
694
+ }
695
+ }
696
+ return null;
697
+ }
698
+
699
+ // A text node's path, resolved to its DOM node and the element it sits in.
700
+ function textNodeFor(path) {
701
+ const str = String(path);
702
+ if (str === '') return null;
703
+ const cut = str.lastIndexOf('.');
704
+ const parent = document.querySelector(pathSelector(cut === -1 ? '' : str.slice(0, cut)));
705
+ const found = parent ? textChildren(parent) : null;
706
+ if (!found) return null;
707
+ const at = found.indices.indexOf(str.slice(cut + 1));
708
+ return at === -1 ? null : { parent: parent, node: found.nodes[at] };
709
+ }
710
+
711
+ // \`point\` is the pointer event: with it, text under the pointer resolves
712
+ // to its own path rather than to the element it sits in.
713
+ function findPath(target, point) {
618
714
  if (!target) return null;
619
715
  let el = target;
620
716
  while (el && el.nodeType === 1) {
621
717
  const p = el.getAttribute && el.getAttribute('data-node-path');
622
- if (p !== null && p !== undefined) return p;
718
+ if (p !== null && p !== undefined) {
719
+ const text = point ? textPathAt(el, point.clientX, point.clientY) : null;
720
+ return text === null ? p : text;
721
+ }
623
722
  el = el.parentElement;
624
723
  }
625
724
  return null;
@@ -707,8 +806,15 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
707
806
  dim(document.body);
708
807
  }
709
808
 
809
+ // The highlight registry name for a ring class: \`__velloo-hover\` \u2192 \`velloo-hover\`.
810
+ const highlightName = (cls) => cls.replace(/^_+/, '');
811
+ const highlights = typeof CSS !== 'undefined' && CSS.highlights && typeof Highlight === 'function'
812
+ ? CSS.highlights
813
+ : null;
814
+
710
815
  function clearClass(cls) {
711
816
  document.querySelectorAll('.' + cls).forEach((el) => el.classList.remove(cls));
817
+ if (highlights) highlights.delete(highlightName(cls));
712
818
  }
713
819
 
714
820
  // The repo-backed canvas mount leaves the SSR tree in the document, hidden,
@@ -752,6 +858,12 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
752
858
  els = document.querySelectorAll(snippetSelector(snippetPath));
753
859
  } else if (path !== null && path !== undefined) {
754
860
  els = document.querySelectorAll(pathSelector(path));
861
+ const text = els.length === 0 ? textNodeFor(path) : null;
862
+ if (text) {
863
+ if (highlights) highlights.set(highlightName(cls), new Highlight(rangeOf(text.node)));
864
+ if (scroll) text.parent.scrollIntoView({ block: 'center', inline: 'nearest' });
865
+ return;
866
+ }
755
867
  } else {
756
868
  return;
757
869
  }
@@ -811,9 +923,11 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
811
923
  for (let i = 0; i < paths.length; i++) {
812
924
  const path = paths[i];
813
925
  const el = document.querySelector(pathSelector(path));
814
- if (!el) continue;
815
- els.push(el);
816
- const r = el.getBoundingClientRect();
926
+ const text = el ? null : textNodeFor(path);
927
+ if (!el && !text) continue;
928
+ // Text has no box of its own to observe: it moves when its parent does.
929
+ els.push(el || text.parent);
930
+ const r = el ? el.getBoundingClientRect() : rangeOf(text.node).getBoundingClientRect();
817
931
  rects.push({ path: path, x: r.left, y: r.top, w: r.width, h: r.height });
818
932
  }
819
933
  // A definition path resolves to one box per instance, all of them ringed
@@ -903,7 +1017,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
903
1017
  }, true);
904
1018
 
905
1019
  document.addEventListener('click', (ev) => {
906
- const path = findPath(ev.target);
1020
+ const path = findPath(ev.target, ev);
907
1021
  ev.preventDefault();
908
1022
  // Focus mode scopes the screen to one snippet: the dimmed rest of the
909
1023
  // screen isn't editable, so clicking it deselects rather than selecting
@@ -928,7 +1042,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
928
1042
  send({ type: 'exit' });
929
1043
  return;
930
1044
  }
931
- const path = findPath(ev.target);
1045
+ const path = findPath(ev.target, ev);
932
1046
  if (path === null) return;
933
1047
  const snippetId = nearestSnippetId(ev.target);
934
1048
  if (snippetId === undefined) send({ type: 'enter', path: path });
@@ -959,15 +1073,24 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
959
1073
  else send({ type: 'hover', path: pendingHover, snippetPath: pendingHoverSnippet });
960
1074
  }
961
1075
 
962
- document.addEventListener('mouseover', (ev) => {
1076
+ function trackHover(ev) {
963
1077
  // Nothing outside the focused snippet is editable, so nothing outside it
964
1078
  // should light up as though it were.
965
- const path = outsideFocus(ev.target) ? null : findPath(ev.target);
1079
+ const path = outsideFocus(ev.target) ? null : findPath(ev.target, ev);
966
1080
  const snippetPath = findSnippetPath(ev.target);
967
1081
  if (path === pendingHover && snippetPath === pendingHoverSnippet) return;
968
1082
  pendingHover = path;
969
1083
  pendingHoverSnippet = snippetPath;
970
1084
  if (!hoverRaf) hoverRaf = requestAnimationFrame(flushHover);
1085
+ }
1086
+
1087
+ document.addEventListener('mouseover', trackHover);
1088
+ // Moving from a text run onto the padding beside it never leaves the element
1089
+ // they share, so no mouseover fires. Only an element that holds text nodes
1090
+ // needs the finer event.
1091
+ document.addEventListener('mousemove', (ev) => {
1092
+ const el = ev.target && ev.target.closest ? ev.target.closest('[data-node-path]') : null;
1093
+ if (el && el.hasAttribute('data-node-text')) trackHover(ev);
971
1094
  });
972
1095
 
973
1096
  document.addEventListener('mouseleave', () => {
@@ -990,9 +1113,13 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
990
1113
  // We only preventDefault + forward when the parent has established a
991
1114
  // channel (port is non-null). Library-tile iframes don't run a
992
1115
  // handshake; preventDefault'ing their wheels would freeze the
993
- // surrounding masonry's scroll.
1116
+ // surrounding masonry's scroll. Their Ctrl+wheel is still cancelled,
1117
+ // or a pinch over a tile zooms the whole canvas page.
994
1118
  window.addEventListener('wheel', (ev) => {
995
- if (!port) return;
1119
+ if (!port) {
1120
+ if (ev.ctrlKey && window.parent !== window) ev.preventDefault();
1121
+ return;
1122
+ }
996
1123
  // Alt/Option + wheel scrolls the design document itself \u2014 the only wheel
997
1124
  // path to the content, since plain wheel pans the canvas.
998
1125
  if (ev.altKey) return;
@@ -1030,15 +1157,22 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1030
1157
 
1031
1158
  window.__velloo = { ready: true };
1032
1159
  })();
1033
- `;var LIVE_RUNTIME=`
1160
+ `;var LIVE_GATE_MS=6000,LIVE_ISLANDS_MS=5000,LIVE_RUNTIME=`
1034
1161
  (() => {
1035
1162
  if (window.__velloo_live) return;
1036
1163
  window.__velloo_live = { ready: false };
1037
1164
  const BUNDLE_URL = __VELLOO_LIVE_BUNDLE_URL__;
1038
1165
 
1039
- function markReady() {
1040
- window.__velloo_live_ready = true;
1041
- window.__velloo_live.ready = true;
1166
+ // Each mount pass owns the flag only while it is the latest one: a pass
1167
+ // superseded by a late canvas commit must not open the gate for its
1168
+ // successor.
1169
+ var pass = 0;
1170
+ function setReady(value) {
1171
+ window.__velloo_live_ready = value;
1172
+ window.__velloo_live.ready = value;
1173
+ }
1174
+ function markReady(run) {
1175
+ if (run === pass) setReady(true);
1042
1176
  }
1043
1177
  // Measure the content the real component rendered into a marker's overlay
1044
1178
  // mount and reserve it as the marker's height. Only for fit:"content"
@@ -1077,8 +1211,8 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1077
1211
  // below can't stop \u2014 a fixed 2-frame wait would capture a mid-entry frame
1078
1212
  // (a Pie tweening from radius 0 reads as *empty*). Quiescence-detection
1079
1213
  // lands the real final frame instead, and also covers a measure-then-
1080
- // rerender lib (ResponsiveContainer). Bounded by DEADLINE_MS so a looping
1081
- // animation that never quiesces still flips ready.
1214
+ // rerender lib (ResponsiveContainer). Bounded by the pass's deadline so a
1215
+ // looping animation that never quiesces still flips ready.
1082
1216
  //
1083
1217
  // After quiescence we ALSO require marker heights to be stable across two
1084
1218
  // consecutive animation frames before flipping ready. A multi-island grid
@@ -1086,13 +1220,11 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1086
1220
  // lower rows settle later); DOM-quiescence alone could flip ready while a
1087
1221
  // marker is still resizing, so the screenshot would measure a stale rect.
1088
1222
  // Re-reserving fit:"content" heights on each stability check also lets a
1089
- // late reflow grow the reservation. Still bounded by DEADLINE_MS so a
1223
+ // late reflow grow the reservation. Still bounded by the deadline so a
1090
1224
  // never-quiescing loop can't hang the gate.
1091
- function settle() {
1225
+ function settle(run, markers, deadline) {
1092
1226
  var QUIET_MS = 250;
1093
- var DEADLINE_MS = 5000;
1094
- var start = Date.now();
1095
- var lastMutation = start;
1227
+ var lastMutation = Date.now();
1096
1228
  var observer = new MutationObserver(function () {
1097
1229
  lastMutation = Date.now();
1098
1230
  });
@@ -1114,7 +1246,8 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1114
1246
  var prevHeights = null;
1115
1247
  function tick() {
1116
1248
  var now = Date.now();
1117
- var deadlineHit = now - start >= DEADLINE_MS;
1249
+ if (run !== pass) { observer.disconnect(); return; }
1250
+ var deadlineHit = now >= deadline;
1118
1251
  if (now - lastMutation >= QUIET_MS || deadlineHit) {
1119
1252
  // DOM is quiet (or we hit the deadline). Reserve content height, then
1120
1253
  // confirm the layout has actually stopped moving across two frames.
@@ -1122,7 +1255,7 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1122
1255
  var heights = markerHeights();
1123
1256
  if (deadlineHit || (prevHeights !== null && sameHeights(prevHeights, heights))) {
1124
1257
  observer.disconnect();
1125
- markReady();
1258
+ markReady(run);
1126
1259
  return;
1127
1260
  }
1128
1261
  prevHeights = heights;
@@ -1135,96 +1268,159 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1135
1268
  requestAnimationFrame(tick);
1136
1269
  }
1137
1270
 
1138
- const markers = Array.prototype.slice.call(document.querySelectorAll('[data-live-node]'));
1139
- if (markers.length === 0) { markReady(); return; }
1271
+ // The tree that owns the screen: the canvas mount's root once it has
1272
+ // committed (the server render is hidden and stripped of identity by then),
1273
+ // the server render otherwise \u2014 before the commit, after a fallback, or on a
1274
+ // page with no mount at all.
1275
+ function owner() {
1276
+ var root = document.getElementById('velloo-canvas-root');
1277
+ var ssr = document.getElementById('velloo-ssr');
1278
+ if (root && ssr && ssr.style.display === 'none') return root;
1279
+ return ssr || document;
1280
+ }
1140
1281
 
1141
- // Freeze chart animation so screenshots capture the final frame.
1142
- const freeze = document.createElement('style');
1143
- freeze.textContent =
1144
- '[data-live-node] *, .recharts-layer, .recharts-surface * { animation: none !important; transition: none !important; }';
1145
- document.head.appendChild(freeze);
1282
+ var mountedIn = null;
1146
1283
 
1147
- // The ready flag must always set, even if the bundle hangs \u2014 the
1148
- // screenshot wait keys off it.
1149
- const cap = setTimeout(markReady, 4000);
1284
+ function mountIslands() {
1285
+ var run = ++pass;
1286
+ mountedIn = owner();
1287
+ var markers = Array.prototype.slice.call(mountedIn.querySelectorAll('[data-live-node]'));
1288
+ if (markers.length === 0) { markReady(run); return; }
1289
+ setReady(false);
1290
+ mount(run, markers);
1291
+ }
1150
1292
 
1151
- import(BUNDLE_URL)
1152
- .then(function (mod) {
1153
- if (!mod || !mod.components) {
1154
- clearTimeout(cap);
1155
- settle();
1156
- return;
1293
+ // Bounded gate on the canvas mount, which settles (commit or fallback) with
1294
+ // an event. The only way to reach GATE_MS is a bundle that has done neither
1295
+ // yet; the islands then mount into the server render, and the listener stays
1296
+ // so a later settle that moves ownership remounts them where the screen is.
1297
+ function awaitCanvasMount() {
1298
+ var GATE_MS = ${LIVE_GATE_MS};
1299
+ var gateTimer = null;
1300
+ window.addEventListener(${JSON.stringify(CANVAS_SETTLED_EVENT)}, function () {
1301
+ if (gateTimer !== null) {
1302
+ clearTimeout(gateTimer);
1303
+ gateTimer = null;
1304
+ mountIslands();
1305
+ } else if (mountedIn !== null && owner() !== mountedIn) {
1306
+ mountIslands();
1157
1307
  }
1308
+ });
1309
+ if (window.__velloo_canvas_ready === true) { mountIslands(); return; }
1310
+ gateTimer = setTimeout(function () {
1311
+ gateTimer = null;
1312
+ mountIslands();
1313
+ }, GATE_MS);
1314
+ }
1158
1315
 
1159
- const mounts = markers.map(function (marker) {
1160
- return new Promise(function (resolve) {
1161
- const ref = marker.getAttribute('data-live-ref');
1162
- const Comp = ref && mod.components[ref];
1163
- // A multi-app loader exports a per-island runtime map \u2014 each
1164
- // island must mount with ITS host app's React copy. A single-app
1165
- // bundle exports React/createRoot at the top level (mod itself).
1166
- const rt = (mod.runtimes && ref && mod.runtimes[ref]) || mod;
1167
- if (!Comp || typeof rt.createRoot !== 'function' || !rt.React) { resolve(); return; }
1168
- const React = rt.React;
1169
- const createRoot = rt.createRoot;
1170
- const ErrorBoundary = rt.ErrorBoundary;
1171
-
1172
- let props = {};
1173
- try { props = JSON.parse(marker.getAttribute('data-live-props') || '{}'); } catch (e) {}
1174
-
1175
- const skeleton = marker.querySelector('[data-velloo-extension]');
1176
- const overlay = document.createElement('div');
1177
- overlay.setAttribute('data-live-mount', '');
1178
- overlay.style.cssText = 'position:absolute;inset:0;pointer-events:none;';
1179
- marker.appendChild(overlay);
1180
-
1181
- const root = createRoot(overlay);
1182
-
1183
- function onMounted() {
1184
- if (skeleton) skeleton.style.visibility = 'hidden';
1185
- resolve();
1186
- }
1187
- function onError() {
1188
- // Defer DOM teardown out of React's commit phase.
1189
- setTimeout(function () {
1190
- try { root.unmount(); } catch (e) {}
1191
- if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
1192
- if (skeleton) skeleton.style.visibility = '';
1193
- }, 0);
1194
- resolve();
1195
- }
1196
- function Mounted() {
1197
- React.useEffect(function () { onMounted(); }, []);
1198
- return React.createElement(Comp, props);
1199
- }
1200
-
1201
- root.render(
1202
- React.createElement(
1203
- ErrorBoundary,
1204
- { onError: onError },
1205
- React.createElement(Mounted, null),
1206
- ),
1207
- );
1316
+ var frozen = false;
1317
+ function freezeAnimation() {
1318
+ if (frozen) return;
1319
+ frozen = true;
1320
+ const freeze = document.createElement('style');
1321
+ freeze.textContent =
1322
+ '[data-live-node] *, .recharts-layer, .recharts-surface * { animation: none !important; transition: none !important; }';
1323
+ document.head.appendChild(freeze);
1324
+ }
1325
+
1326
+ function mount(run, markers) {
1327
+ // Freeze chart animation so screenshots capture the final frame.
1328
+ freezeAnimation();
1329
+
1330
+ // One deadline for the whole pass \u2014 bundle import, every mount, settling \u2014
1331
+ // and a timer that flips the flag at it even if the import hangs, so the
1332
+ // pass can never outlast LIVE_ISLANDS_MS.
1333
+ var ISLANDS_MS = ${LIVE_ISLANDS_MS};
1334
+ var deadline = Date.now() + ISLANDS_MS;
1335
+ setTimeout(function () { markReady(run); }, ISLANDS_MS);
1336
+
1337
+ import(BUNDLE_URL)
1338
+ .then(function (mod) {
1339
+ if (!mod || !mod.components) {
1340
+ settle(run, markers, deadline);
1341
+ return;
1342
+ }
1343
+
1344
+ const mounts = markers.map(function (marker) {
1345
+ return new Promise(function (resolve) {
1346
+ // Already mounted by an earlier pass over this same tree.
1347
+ if (marker.querySelector(':scope > [data-live-mount]')) { resolve(); return; }
1348
+ const ref = marker.getAttribute('data-live-ref');
1349
+ const Comp = ref && mod.components[ref];
1350
+ // A multi-app loader exports a per-island runtime map \u2014 each
1351
+ // island must mount with ITS host app's React copy. A single-app
1352
+ // bundle exports React/createRoot at the top level (mod itself).
1353
+ const rt = (mod.runtimes && ref && mod.runtimes[ref]) || mod;
1354
+ if (!Comp || typeof rt.createRoot !== 'function' || !rt.React) { resolve(); return; }
1355
+ const React = rt.React;
1356
+ const createRoot = rt.createRoot;
1357
+ const ErrorBoundary = rt.ErrorBoundary;
1358
+
1359
+ let props = {};
1360
+ try { props = JSON.parse(marker.getAttribute('data-live-props') || '{}'); } catch (e) {}
1361
+
1362
+ const skeleton = marker.querySelector('[data-velloo-extension]');
1363
+ const overlay = document.createElement('div');
1364
+ overlay.setAttribute('data-live-mount', '');
1365
+ overlay.style.cssText = 'position:absolute;inset:0;pointer-events:none;';
1366
+ marker.appendChild(overlay);
1367
+
1368
+ const root = createRoot(overlay);
1369
+
1370
+ function onMounted() {
1371
+ if (skeleton) skeleton.style.visibility = 'hidden';
1372
+ resolve();
1373
+ }
1374
+ function onError() {
1375
+ // Defer DOM teardown out of React's commit phase.
1376
+ setTimeout(function () {
1377
+ try { root.unmount(); } catch (e) {}
1378
+ if (overlay.parentNode) overlay.parentNode.removeChild(overlay);
1379
+ if (skeleton) skeleton.style.visibility = '';
1380
+ }, 0);
1381
+ resolve();
1382
+ }
1383
+ function Mounted() {
1384
+ React.useEffect(function () { onMounted(); }, []);
1385
+ return React.createElement(Comp, props);
1386
+ }
1387
+
1388
+ root.render(
1389
+ React.createElement(
1390
+ ErrorBoundary,
1391
+ { onError: onError },
1392
+ React.createElement(Mounted, null),
1393
+ ),
1394
+ );
1395
+ });
1208
1396
  });
1209
- });
1210
1397
 
1211
- Promise.allSettled(mounts).then(function () {
1212
- clearTimeout(cap);
1213
- settle();
1398
+ Promise.allSettled(mounts).then(function () {
1399
+ settle(run, markers, deadline);
1400
+ });
1401
+ })
1402
+ .catch(function () {
1403
+ settle(run, markers, deadline);
1214
1404
  });
1215
- })
1216
- .catch(function () {
1217
- clearTimeout(cap);
1218
- settle();
1219
- });
1405
+ }
1406
+
1407
+ // The canvas payload sits AFTER this script in the document, so whether the
1408
+ // page has a mount is only knowable once parsing finishes.
1409
+ function begin() {
1410
+ if (document.getElementById('velloo-canvas-data')) awaitCanvasMount();
1411
+ else mountIslands();
1412
+ }
1413
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', begin);
1414
+ else begin();
1220
1415
  })();
1221
- `;function buildDocument(opts){let{viewport,bodyHtml,snapshotCss,themeCss,adapterCss,customCss,googleFonts,baseHref,title="Velloo design",includeRuntime=!0,dark,liveBundleUrl,canvasBundle,selectionRing,scriptNonce,hostStylesheets}=opts,script=scriptNonce?`<script nonce="${escapeHtml(scriptNonce)}">`:"<script>",runtime=includeRuntime?`${script}${IFRAME_RUNTIME}</script>`:"",live=liveBundleUrl?`${script}${LIVE_RUNTIME.replace("__VELLOO_LIVE_BUNDLE_URL__",JSON.stringify(liveBundleUrl))}</script>`:"",canvas=canvasBundle?`<script type="application/json" id="velloo-canvas-data">${jsonForScript({tree:canvasBundle.tree,themeOptions:canvasBundle.themeOptions,preview:canvasBundle.preview,pathname:canvasBundle.pathname})}</script>${script}${CANVAS_RUNTIME.replace("__VELLOO_CANVAS_BUNDLE_URL__",JSON.stringify(canvasBundle.url))}</script>`:"",hostStyles=(hostStylesheets??[]).map((path)=>{let href=path.startsWith("/")?`${HOST_FILES_PREFIX}${path}`:path;return`
1416
+ `;function buildDocument(opts){let{viewport,bodyHtml,snapshotCss,themeCss,adapterCss,customCss,googleFonts,baseHref,title="Velloo design",includeRuntime=!0,dark,liveBundleUrl,canvasBundle,selectionRing,scriptNonce,hostStylesheets,appCss}=opts,script=scriptNonce?`<script nonce="${escapeHtml(scriptNonce)}">`:"<script>",runtime=includeRuntime?`${script}${IFRAME_RUNTIME}</script>`:"",live=liveBundleUrl?`${script}${LIVE_RUNTIME.replace("__VELLOO_LIVE_BUNDLE_URL__",JSON.stringify(liveBundleUrl))}</script>`:"",canvas=canvasBundle?`<script type="application/json" id="velloo-canvas-data">${jsonForScript({tree:canvasBundle.tree,themeOptions:canvasBundle.themeOptions,preview:canvasBundle.preview,pathname:canvasBundle.pathname})}</script>${script}${CANVAS_RUNTIME.replace("__VELLOO_CANVAS_BUNDLE_URL__",JSON.stringify(canvasBundle.url))}</script>`:"",hostStyles=(hostStylesheets??[]).map((path)=>{let href=path.startsWith("/")?`${HOST_FILES_PREFIX}${path}`:path;return`
1222
1417
  <link rel="stylesheet" href="${escapeHtml(href)}" ${HOST_STYLESHEET_ATTRIBUTE}="${escapeHtml(path)}" />`}).join(""),body=canvasBundle?`<div id="velloo-ssr">${bodyHtml}</div>`:bodyHtml,fontLinks=googleFonts&&googleFonts.length>0?`
1223
1418
  <link rel="preconnect" href="https://fonts.googleapis.com" />
1224
1419
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
1225
1420
  <link rel="stylesheet" href="${escapeHtml(`https://fonts.googleapis.com/css2?${googleFonts.map((f)=>`family=${sanitizeGoogleFontSpec(f)}`).join("&")}&display=swap`)}" />`:"",adapterStyle=adapterCss&&adapterCss.trim()!==""?`
1226
1421
  <style data-velloo-adapter>${neutralizeCssText(adapterCss)}</style>`:"",customStyle=customCss&&customCss.trim()!==""?`
1227
- <style>${neutralizeCssText(customCss)}</style>`:"",selectionRingStyle=selectionRing?' style="--velloo-ring-select: 2px"':"",antiAutofill='data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" autocomplete="off"';return`<!doctype html>
1422
+ <style>${neutralizeCssText(customCss)}</style>`:"",appStyle=appCss&&appCss.trim()!==""?`
1423
+ <style data-velloo-app-css>${neutralizeCssText(appCss)}</style>`:"",selectionRingStyle=selectionRing?' style="--velloo-ring-select: 2px"':"",antiAutofill='data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" autocomplete="off"';return`<!doctype html>
1228
1424
  <html lang="en"${dark?' class="dark"':""}${selectionRingStyle}>
1229
1425
  <head>
1230
1426
  <meta charset="utf-8" />${baseHref?`
@@ -1232,13 +1428,15 @@ Learn more: https://react.dev/warnings/version-mismatch`));var $renderToReadable
1232
1428
  <meta name="viewport" content="width=${viewport.w}, initial-scale=1" />
1233
1429
  <title>${escapeHtml(title)}</title>${fontLinks}${hostStyles}
1234
1430
  <style>${snapshotCss}</style>
1235
- <style>${neutralizeCssText(themeCss)}</style>${adapterStyle}${customStyle}
1431
+ <style>${neutralizeCssText(themeCss)}</style>${adapterStyle}${customStyle}${appStyle}
1236
1432
  </head>
1237
1433
  <body data-1p-ignore="true" data-lpignore="true" data-bwignore="true" data-form-type="other" autocomplete="off">${body}${runtime}${live}${canvas}</body>
1238
- </html>`}function jsonForScript(value){return JSON.stringify(value).replace(/</g,"\\u003c")}function escapeHtml(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var import_react2=__toESM(require_react_development(),1);var MAX_STAND_INS=8;class RenderGuardLimitError extends Error{failures;constructor(failures,options){super(`${failures.length} components failed to render \u2014 more than the ${MAX_STAND_INS} the guard will stand in for, so the screen was not drawn.`,options);this.name="RenderGuardLimitError",this.failures=failures}}function blame(error,registry){if(!(error instanceof Error)||typeof error.stack!=="string")return null;for(let match of error.stack.matchAll(/^\s*at ([A-Za-z0-9_$]+)/gm)){let name=match[1];if(name!==void 0&&Object.hasOwn(registry,name))return name}return null}function attr(props,name){let value=props[name];return typeof value==="string"?value:void 0}function standIn(componentId,reason,kind){let missing=kind==="missing";return function(props){return import_react2.createElement("div",{"data-velloo-render-error":componentId,"data-node-path":attr(props,"data-node-path"),"data-snippet-id":attr(props,"data-snippet-id"),"data-snippet-path":attr(props,"data-snippet-path"),"data-snippet-at":attr(props,"data-snippet-at"),title:reason,style:{border:"1px dashed currentColor",borderRadius:"6px",padding:"12px",...missing?{}:{opacity:0.7},font:"12px ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap"}},import_react2.createElement("span",{style:{display:"block",opacity:0.7}},missing?`${componentId} is not in this screen's library`:`${componentId} failed to render \u2014 ${reason}`),missing?props.children:null)}}function locate(registry,toHtml){let open=[];function Close({node}){let at=open.lastIndexOf(node);if(at>=0)open.splice(at,1);return null}let traced={};for(let[componentId,Component]of Object.entries(registry))traced[componentId]=function(props){let nodePath=attr(props,"data-node-path");if(nodePath===void 0)return import_react2.createElement(Component,props);let node={componentId,nodePath,snippetPath:attr(props,"data-snippet-path")};return open.push(node),import_react2.createElement(import_react2.Fragment,null,import_react2.createElement(Component,props),import_react2.createElement(Close,{node}))};try{toHtml(traced)}catch{return open.at(-1)??null}return null}function replaceAt(Component,at,replacement){return function(props){let here=attr(props,"data-node-path")===at.nodePath&&attr(props,"data-snippet-path")===at.snippetPath;return import_react2.createElement(here?replacement:Component,props)}}function renderGuarded(registry,toHtml){let failures=[],active=registry;for(;;)try{return{html:toHtml(active),failures}}catch(error){let unknown=error instanceof UnknownComponentError,reason=error instanceof Error?error.message:String(error),componentId=unknown?error.ref:blame(error,registry),node=componentId===null?locate(active,toHtml):null;if(componentId===null&&node===null)throw error;let failure=node?{componentId:node.componentId,reason,kind:"threw",nodePath:node.nodePath}:{componentId,reason,kind:unknown?"missing":"threw"};if(failures.some((seen)=>seen.componentId===failure.componentId&&seen.nodePath===failure.nodePath))throw error;if(failures.length>=MAX_STAND_INS)throw new RenderGuardLimitError([...failures,failure],{cause:error});failures.push(failure);let replacement=standIn(failure.componentId,reason,failure.kind),Original=active[failure.componentId];active={...active,[failure.componentId]:node&&Original?replaceAt(Original,node,replacement):replacement}}}var STATIC_REF="velloo:static";function collectSerializedRefs(tree){if(!tree)return[];let seen=new Set,visitValue=(value)=>{if(Array.isArray(value))for(let item of value)visitValue(item);else if(value&&typeof value==="object"&&"$node"in value)visit(value.$node)},visit=(node)=>{if(seen.add(node.ref),node.proxy)visit(node.proxy);for(let value of Object.values(node.props??{}))visitValue(value);for(let child of node.children??[])if(typeof child==="object")visit(child)};return visit(tree),[...seen]}function serializeTree(node,opts,path=[],stack=[],lockedPath=null,body=null){if(isSnippetInstance(node)){let snippet=opts.snippets?.get(node.$snippet);if(!snippet||stack.includes(snippet.id))return null;let resolved=resolveSnippetBody(node,snippet);return serializeTree(resolved,opts,path,[...stack,snippet.id],lockedPath??path,enterSnippet(body,snippet.id))}if(isParamRef(node))return null;if(!isComponentNode(node))return null;if(!isRepoNode(node)&&opts.staticFallback?.refs.has(node.$ref))return{ref:STATIC_REF,props:{html:opts.staticFallback.render(node,path,lockedPath)}};let{children:childrenProp,...rawProps}=node.props??{},repo=isRepoNode(node),restProps=repo?serializeSlotProps(rawProps,opts,path,stack,lockedPath):rawProps,dataNodePath=(lockedPath??path).join("."),children;if(Array.isArray(node.children)&&node.children.length>0)children=node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>serializeTree(c,opts,[...path,i,j],stack,lockedPath,null)):serializeTree(child,opts,[...path,i],stack,lockedPath,descend(body,i))).filter((c)=>c!==null);else if(childrenProp!==void 0)children=serializePropChildren(childrenProp,opts,path,stack,lockedPath);let proxy=repo?serializeProxy(node,opts,path,stack,lockedPath):null;return{ref:repo?repoKey(node.$repo):node.$ref,...repo?{repo:{...node.$repo,name:node.$ref}}:{},...proxy?{proxy}:{},props:{...restProps,"data-node-path":dataNodePath,...bodyAttributes(body)},...children&&children.length>0?{children}:{}}}function isNodeLike2(v){return typeof v==="object"&&v!==null&&!Array.isArray(v)&&(isComponentNode(v)||isSnippetInstance(v)||isParamRef(v))}function serializePropChildren(value,opts,path,stack,lockedPath){if(isNodeLike2(value)){let s=serializeTree(value,opts,path,stack,lockedPath);return s?[s]:void 0}if(Array.isArray(value)){let out=[];for(let item of value)if(isNodeLike2(item)){let s=serializeTree(item,opts,path,stack,lockedPath);if(s)out.push(s)}else if(typeof item==="string"||typeof item==="number")out.push(item);return out.length>0?out:void 0}if(typeof value==="string"||typeof value==="number")return[value];return}function serializeProxy(node,opts,path,stack,lockedPath){let snippet=node.$repo.proxy?opts.snippets?.get(node.$repo.proxy):void 0;if(!snippet||stack.includes(snippet.id))return null;try{return serializeTree(repoProxyInstance(node,snippet),opts,path,stack,lockedPath??path)}catch{return null}}function serializeSlotProps(props,opts,path,stack,lockedPath){let out={};for(let[name,value]of Object.entries(props))if(isNodeLike2(value)){let s=serializeTree(value,opts,path,stack,lockedPath??path);if(s)out[name]={$node:s}}else out[name]=value;return out}var COLOR_TOKEN_MAP={background:"--color-background",foreground:"--color-foreground",border:"--color-border",input:"--color-input",ring:"--color-ring",primary:["--color-primary","--color-primary-foreground"],secondary:["--color-secondary","--color-secondary-foreground"],muted:["--color-muted","--color-muted-foreground"],accent:["--color-accent","--color-accent-foreground"],destructive:["--color-destructive","--color-destructive-foreground"],card:["--color-card","--color-card-foreground"],popover:["--color-popover","--color-popover-foreground"]};function emit(varName,value,lines){if(typeof value==="number")lines.push(` ${varName}: ${value};`);else if(typeof value==="string")lines.push(` ${varName}: ${sanitizeCssTokenValue(value)};`)}var SEMANTIC_COLOR_VARS=new Set(Object.values(COLOR_TOKEN_MAP).flatMap((target)=>Array.isArray(target)?target:[target]));function emitPalette(palette,lines){if(!palette)return;for(let[name,value]of Object.entries(palette)){if(!isCssIdent(name))continue;if(SEMANTIC_COLOR_VARS.has(`--color-${name}`))continue;emit(`--color-${name}`,value,lines)}}function emitSpacing(spacing,lines){for(let[name,value]of spacingCssTokens(spacing))emit(`--spacing-${name}`,value,lines)}function emitShadows(shadows,lines){if(!shadows)return;for(let[name,value]of Object.entries(shadows)){if(!isCssIdent(name))continue;if(typeof value==="string"||typeof value==="number")emit(`--shadow-${name}`,value,lines)}}function emitContainer(container,lines){if(!container)return;let decls=[" width: 100%;"];if(container.center)decls.push(" margin-inline: auto;");if(container.padding)decls.push(` padding-inline: ${sanitizeCssTokenValue(container.padding)};`);if(container.maxWidth)decls.push(` max-width: ${sanitizeCssTokenValue(container.maxWidth)};`);lines.push("",".container {",...decls,"}")}function emitColorBlock(colors,lines){for(let[token,target]of Object.entries(COLOR_TOKEN_MAP)){let value=colors[token];if(value===void 0)continue;if(Array.isArray(target)){let[defaultVar,foregroundVar]=target;if(typeof value==="object")emit(defaultVar,value.DEFAULT,lines),emit(foregroundVar,value.foreground,lines);else emit(defaultVar,value,lines)}else if(typeof value==="string")emit(target,value,lines)}}function themeToCss(theme){let lines=[":root {"];emitColorBlock(theme.colors,lines),emitPalette(theme.palette,lines),emitSpacing(theme.spacing,lines),emitShadows(theme.shadows,lines);let fontFamily=theme.typography.fontFamily;if(fontFamily)for(let[role,stack]of Object.entries(fontFamily)){if(!isCssIdent(role))continue;emit(`--font-${role}`,stack,lines)}let radiusValue=theme.radius.md??theme.radius.lg??theme.radius.sm;if(radiusValue!==void 0){let formatted=typeof radiusValue==="number"?`${radiusValue}px`:sanitizeCssTokenValue(radiusValue);lines.push(` --radius: ${formatted};`)}if(lines.push("}"),theme.colorsDark||theme.paletteDark)lines.push(""),lines.push(".dark {"),emitColorBlock(theme.colorsDark??{},lines),emitPalette(theme.paletteDark,lines),lines.push("}");return emitContainer(theme.container,lines),[lines.join(`
1434
+ </html>`}function jsonForScript(value){return JSON.stringify(value).replace(/</g,"\\u003c")}function escapeHtml(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}var import_react2=__toESM(require_react_development(),1);var MAX_STAND_INS=8;class RenderGuardLimitError extends Error{failures;constructor(failures,options){super(`${failures.length} components failed to render \u2014 more than the ${MAX_STAND_INS} the guard will stand in for, so the screen was not drawn.`,options);this.name="RenderGuardLimitError",this.failures=failures}}function blame(error,registry){if(!(error instanceof Error)||typeof error.stack!=="string")return null;for(let match of error.stack.matchAll(/^\s*at ([A-Za-z0-9_$]+)/gm)){let name=match[1];if(name!==void 0&&Object.hasOwn(registry,name))return name}return null}function attr(props,name){let value=props[name];return typeof value==="string"?value:void 0}function standIn(componentId,reason,kind){let missing=kind==="missing";return function(props){return import_react2.createElement("div",{"data-velloo-render-error":componentId,"data-node-path":attr(props,"data-node-path"),"data-snippet-id":attr(props,"data-snippet-id"),"data-snippet-path":attr(props,"data-snippet-path"),"data-snippet-at":attr(props,"data-snippet-at"),title:reason,style:{border:"1px dashed currentColor",borderRadius:"6px",padding:"12px",...missing?{}:{opacity:0.7},font:"12px ui-monospace, SFMono-Regular, Menlo, monospace",whiteSpace:"pre-wrap"}},import_react2.createElement("span",{style:{display:"block",opacity:0.7}},missing?`${componentId} is not in this screen's library`:`${componentId} failed to render \u2014 ${reason}`),missing?props.children:null)}}function locate(registry,toHtml){let open=[];function Close({node}){let at=open.lastIndexOf(node);if(at>=0)open.splice(at,1);return null}let traced={};for(let[componentId,Component]of Object.entries(registry))traced[componentId]=function(props){let nodePath=attr(props,"data-node-path");if(nodePath===void 0)return import_react2.createElement(Component,props);let node={componentId,nodePath,snippetPath:attr(props,"data-snippet-path")};return open.push(node),import_react2.createElement(import_react2.Fragment,null,import_react2.createElement(Component,props),import_react2.createElement(Close,{node}))};try{toHtml(traced)}catch{return open.at(-1)??null}return null}function replaceAt(Component,at,replacement){return function(props){let here=attr(props,"data-node-path")===at.nodePath&&attr(props,"data-snippet-path")===at.snippetPath;return import_react2.createElement(here?replacement:Component,props)}}function renderGuarded(registry,toHtml){let failures=[],active=registry;for(;;)try{return{html:toHtml(active),failures}}catch(error){let unknown=error instanceof UnknownComponentError,reason=error instanceof Error?error.message:String(error),componentId=unknown?error.ref:blame(error,registry),node=componentId===null?locate(active,toHtml):null;if(componentId===null&&node===null)throw error;let failure=node?{componentId:node.componentId,reason,kind:"threw",nodePath:node.nodePath}:{componentId,reason,kind:unknown?"missing":"threw"};if(failures.some((seen)=>seen.componentId===failure.componentId&&seen.nodePath===failure.nodePath))throw error;if(failures.length>=MAX_STAND_INS)throw new RenderGuardLimitError([...failures,failure],{cause:error});failures.push(failure);let replacement=standIn(failure.componentId,reason,failure.kind),Original=active[failure.componentId];active={...active,[failure.componentId]:node&&Original?replaceAt(Original,node,replacement):replacement}}}function collectSerializedRepoRefs(tree){let out=new Map,visitValue=(value)=>{if(Array.isArray(value))for(let item of value)visitValue(item);else if(value&&typeof value==="object"&&"$node"in value)visit(value.$node)},visit=(node)=>{if(node.repo&&!out.has(node.ref))out.set(node.ref,{...node.repo,hasProxy:node.proxy!==void 0});if(node.proxy)visit(node.proxy);for(let value of Object.values(node.props??{}))visitValue(value);for(let child of node.children??[])if(typeof child==="object")visit(child)};if(tree)visit(tree);return out}function collectSerializedRefs(tree){if(!tree)return[];let seen=new Set,visitValue=(value)=>{if(Array.isArray(value))for(let item of value)visitValue(item);else if(value&&typeof value==="object"&&"$node"in value)visit(value.$node)},visit=(node)=>{if(seen.add(node.ref),node.proxy)visit(node.proxy);for(let value of Object.values(node.props??{}))visitValue(value);for(let child of node.children??[])if(typeof child==="object")visit(child)};return visit(tree),[...seen]}function serializeTree(node,opts,path=[],stack=[],lockedPath=null,body=null){let shape=nodeShape(node);switch(shape.kind){case"snippet":{let instance=shape.node,snippet=opts.snippets?.get(instance.$snippet);if(!snippet||stack.includes(snippet.id))return null;let resolved=resolveSnippetBody(instance,snippet);return serializeTree(resolved,opts,path,[...stack,snippet.id],lockedPath??path,enterSnippet(body,snippet.id))}case"param":case"invalid":return null;case"text":return null;case"repo":return serializeRepo(shape.node,opts,path,stack,lockedPath,body);case"synthetic":case"named":case"emit-as":{let{node:component,ref}=shape;if(opts.staticFallback?.refs.has(ref)){let html=opts.staticFallback.render(component,path,lockedPath);return{ref:STATIC_REF,props:{html}}}return serializeComponent(component,opts,path,stack,lockedPath,body)}}}function serializeComponent(node,opts,path,stack,lockedPath,body){let{children:childrenProp,...props}=node.props??{};return{ref:node.$ref,props:nodeProps(props,node,path,lockedPath,body),...serializeChildren(node,childrenProp,opts,path,stack,lockedPath,body)}}function serializeRepo(node,opts,path,stack,lockedPath,body){let{children:childrenProp,...rawProps}=node.props??{},props=serializeSlotProps(rawProps,opts,path,stack,lockedPath),proxy=serializeProxy(node,opts,path,stack,lockedPath);return{ref:repoKey(node.$repo),repo:{...node.$repo,name:node.$ref},...proxy?{proxy}:{},props:nodeProps(props,node,path,lockedPath,body),...serializeChildren(node,childrenProp,opts,path,stack,lockedPath,body)}}function nodeProps(props,node,path,lockedPath,body){return{...props,"data-node-path":(lockedPath??path).join("."),...textChildrenAttribute(node.children,lockedPath),...bodyAttributes(body)}}function serializeChild(child,opts,path,stack,lockedPath,body){let shape=nodeShape(child);return shape.kind==="text"?shape.text:serializeTree(child,opts,path,stack,lockedPath,body)}function serializeChildren(node,childrenProp,opts,path,stack,lockedPath,body){let children;if(Array.isArray(node.children)&&node.children.length>0)children=node.children.flatMap((child,i)=>Array.isArray(child)?child.map((c,j)=>serializeChild(c,opts,[...path,i,j],stack,lockedPath,null)):serializeChild(child,opts,[...path,i],stack,lockedPath,descend(body,i))).filter((c)=>c!==null);else if(childrenProp!==void 0)children=serializePropChildren(childrenProp,opts,path,stack,lockedPath);return children&&children.length>0?{children}:{}}function serializePropChildren(value,opts,path,stack,lockedPath){if(isNode(value)){let s=serializeTree(value,opts,path,stack,lockedPath);return s?[s]:void 0}if(Array.isArray(value)){let out=[];for(let item of value)if(isNode(item)){let s=serializeTree(item,opts,path,stack,lockedPath);if(s)out.push(s)}else if(typeof item==="string"||typeof item==="number")out.push(item);return out.length>0?out:void 0}if(typeof value==="string"||typeof value==="number")return[value];return}function serializeProxy(node,opts,path,stack,lockedPath){let snippet=node.$repo.proxy?opts.snippets?.get(node.$repo.proxy):void 0;if(!snippet||stack.includes(snippet.id))return null;try{return serializeTree(repoProxyInstance(node,snippet),opts,path,stack,lockedPath??path)}catch{return null}}function serializeSlotProps(props,opts,path,stack,lockedPath){let out={};for(let[name,value]of Object.entries(props))if(isNode(value)){let s=serializeTree(value,opts,path,stack,lockedPath??path);if(s)out[name]={$node:s}}else out[name]=value;return out}var COLOR_TOKEN_MAP={background:"--color-background",foreground:"--color-foreground",border:"--color-border",input:"--color-input",ring:"--color-ring",primary:["--color-primary","--color-primary-foreground"],secondary:["--color-secondary","--color-secondary-foreground"],muted:["--color-muted","--color-muted-foreground"],accent:["--color-accent","--color-accent-foreground"],destructive:["--color-destructive","--color-destructive-foreground"],card:["--color-card","--color-card-foreground"],popover:["--color-popover","--color-popover-foreground"]};function emit(varName,value,lines){if(typeof value==="number")lines.push(` ${varName}: ${value};`);else if(typeof value==="string")lines.push(` ${varName}: ${sanitizeCssTokenValue(value)};`)}var SEMANTIC_COLOR_VARS=new Set(Object.values(COLOR_TOKEN_MAP).flatMap((target)=>Array.isArray(target)?target:[target]));function emitPalette(palette,lines){if(!palette)return;for(let[name,value]of Object.entries(palette)){if(!isCssIdent(name))continue;if(SEMANTIC_COLOR_VARS.has(`--color-${name}`))continue;emit(`--color-${name}`,value,lines)}}function emitSpacing(spacing,lines){for(let[name,value]of spacingCssTokens(spacing))emit(`--spacing-${name}`,value,lines)}function emitShadows(shadows,lines){if(!shadows)return;for(let[name,value]of Object.entries(shadows)){if(!isCssIdent(name))continue;if(typeof value==="string"||typeof value==="number")emit(`--shadow-${name}`,value,lines)}}function emitContainer(container,lines){if(!container)return;let decls=[" width: 100%;"];if(container.center)decls.push(" margin-inline: auto;");if(container.padding)decls.push(` padding-inline: ${sanitizeCssTokenValue(container.padding)};`);if(container.maxWidth)decls.push(` max-width: ${sanitizeCssTokenValue(container.maxWidth)};`);lines.push("",".container {",...decls,"}")}function emitColorBlock(colors,lines){for(let[token,target]of Object.entries(COLOR_TOKEN_MAP)){let value=colors[token];if(value===void 0)continue;if(Array.isArray(target)){let[defaultVar,foregroundVar]=target;if(typeof value==="object")emit(defaultVar,value.DEFAULT,lines),emit(foregroundVar,value.foreground,lines);else emit(defaultVar,value,lines)}else if(typeof value==="string")emit(target,value,lines)}}function themeToCss(theme){let lines=[":root {"];emitColorBlock(theme.colors,lines),emitPalette(theme.palette,lines),emitSpacing(theme.spacing,lines),emitShadows(theme.shadows,lines);let fontFamily=theme.typography.fontFamily;if(fontFamily)for(let[role,stack]of Object.entries(fontFamily)){if(!isCssIdent(role))continue;emit(`--font-${role}`,stack,lines)}let radiusValue=theme.radius.md??theme.radius.lg??theme.radius.sm;if(radiusValue!==void 0){let formatted=typeof radiusValue==="number"?`${radiusValue}px`:sanitizeCssTokenValue(radiusValue);lines.push(` --radius: ${formatted};`)}if(lines.push("}"),theme.colorsDark||theme.paletteDark)lines.push(""),lines.push(".dark {"),emitColorBlock(theme.colorsDark??{},lines),emitPalette(theme.paletteDark,lines),lines.push("}");return emitContainer(theme.container,lines),[lines.join(`
1239
1435
  `),typesetCss(theme.typography.typesets)].join(`
1240
1436
 
1241
- `)}function renderBody(screen,registry,snippets){return renderBodyGuarded(screen,registry,snippets).html}var CANVAS_ATTRIBUTE=/^data-(?:node-path|snippet-id|snippet-path|velloo-.*)$/;async function renderNativeHtml(screen,registry,snippets){return new HTMLRewriter().on('link[rel="preload"]',{element(element){element.remove()}}).on("*",{element(element){let param=element.getAttribute("data-velloo-param");if(param!==null){element.replace(`$${param}`);return}let html=element.namespaceURI==="http://www.w3.org/1999/xhtml";for(let[name,value]of[...element.attributes])if(CANVAS_ATTRIBUTE.test(name))element.removeAttribute(name);else if(html)element.removeAttribute(name),element.setAttribute(name,value)}}).transform(new Response(renderBody(screen,registry,snippets))).text()}function renderBodyGuarded(screen,registry,snippets){return ScreenSchema.parse(screen),renderGuarded(registry,(active)=>$renderToString(buildRoot(screen.tree,{registry:active,snippets})))}async function renderScreen(screen,theme,options){ScreenSchema.parse(screen),ThemeSchema.parse(theme);let pass=options.renderPass,{html:bodyHtml,failures}=renderGuarded(options.registry,(active)=>{let element=buildRoot(screen.tree,{registry:active,snippets:options.snippets});return $renderToString(pass?pass.wrap(element):element)}),adapterCss=pass?pass.css(bodyHtml):void 0,themeCss=themeToCss(theme),canvasBundle=options.canvasBundle?(()=>{let staticRefs=options.canvasBundle.staticRefs??[],tree=serializeTree(screen.tree,{snippets:options.snippets,...staticRefs.length>0?{staticFallback:{refs:new Set(staticRefs),render:(node,path,lockedPath)=>$renderToString(buildTree(node,{registry:options.registry,snippets:options.snippets},path,[],lockedPath))}}:{}});return tree?{url:options.canvasBundle.url,tree,themeOptions:options.canvasBundle.themeOptions,preview:options.canvasBundle.preview,...screen.route?{pathname:screen.route}:{}}:void 0})():void 0;return{html:buildDocument({viewport:options.viewport,bodyHtml,snapshotCss:options.snapshotCss,themeCss,adapterCss,customCss:options.customCss,googleFonts:theme.typography.googleFonts,baseHref:options.baseHref,title:screen.name,dark:options.dark,liveBundleUrl:options.liveBundleUrl,canvasBundle,...options.includeRuntime!==void 0?{includeRuntime:options.includeRuntime}:{},...options.selectionRing!==void 0?{selectionRing:options.selectionRing}:{},...options.scriptNonce!==void 0?{scriptNonce:options.scriptNonce}:{},...options.hostStylesheets?{hostStylesheets:options.hostStylesheets}:{}}),bodyHtml,themeCss,failures}}async function waitForLiveIslands(target,html){if(html.includes("data-live-node"))await target.waitForFunction(()=>window.__velloo_live_ready===!0,void 0,{timeout:6000}).catch(()=>{});if(html.includes("velloo-canvas-data"))await target.waitForFunction(()=>window.__velloo_canvas_ready===!0,void 0,{timeout:6000}).catch(()=>{})}async function missingHostStylesheets(target,html){if(!html.includes(HOST_STYLESHEET_ATTRIBUTE))return;return target.evaluate((attribute)=>[...document.querySelectorAll(`link[${attribute}]`)].flatMap((link)=>{let entry=performance.getEntriesByName(link.href)[0];if(!entry)return[];let status=entry.responseStatus??0,sameOrigin=new URL(link.href).origin===location.origin;return status>=400||sameOrigin&&status===0?[`${status||"blocked"} stylesheet ${link.getAttribute(attribute)}`]:[]}),HOST_STYLESHEET_ATTRIBUTE).catch(()=>{return})}async function waitForFonts(target){await target.evaluate(()=>Promise.race([document.fonts.ready,new Promise((r)=>setTimeout(r,2000))])).catch(()=>{})}async function settleForCapture(page,html,opts={}){if(await page.waitForLoadState("load",{timeout:5000}).catch(()=>{}),await waitForFonts(page),opts.liveIslands!==!1)await waitForLiveIslands(page,html)}async function screenshot(opts){return await screenshotInternal(opts),opts.outPath}async function screenshotBuffer(opts){let buf=await screenshotInternal(opts);if(!buf)throw Error("screenshotBuffer: no buffer returned (internal invariant)");return buf}async function openDocument(page,html){let base=/<base href="(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?)\/?"/.exec(html)?.[1];if(!base){await page.setContent(html,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS});return}let url=`${base}/__velloo_capture/${crypto.randomUUID()}`;await page.route(url,(route)=>route.fulfill({status:200,contentType:"text/html; charset=utf-8",body:html})),await page.goto(url,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS})}async function canvasMountState(page){return page.evaluate(()=>{let w=window;if(!document.getElementById("velloo-canvas-data"))return;let ssr=document.getElementById("velloo-ssr");return{mounted:Boolean(ssr&&ssr.style.display==="none"),...w.__velloo_canvas_bundle?{bundle:w.__velloo_canvas_bundle}:{},diagnostics:w.__velloo_canvas_diagnostics??[]}}).catch(()=>{return})}async function probeCanvasMount(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:1},async(context)=>{let page=await context.newPage(),consoleErrors=[];return page.on("console",(message)=>{if(message.type()==="error")consoleErrors.push(message.text().slice(0,400))}),page.on("pageerror",(error)=>consoleErrors.push(error.message.slice(0,400))),await openDocument(page,opts.html),await settleForCapture(page,opts.html),await page.waitForTimeout(150),{...await canvasMountState(page)??{mounted:!1,diagnostics:[]},consoleErrors:consoleErrors.slice(0,20)}})}async function captureScreenshot(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();await openDocument(page,opts.html),await settleForCapture(page,opts.html);let nodeRects=await page.$$eval("[data-node-path]",(els)=>els.map((el)=>{let r=el.getBoundingClientRect();return{path:el.dataset.nodePath??"",x:r.left,y:r.top,w:r.width,h:r.height}})),png=await page.screenshot({fullPage:opts.fullPage??!0,animations:"disabled",caret:"hide",timeout:CAPTURE_TIMEOUT_MS}),dom=opts.dom?await extractDom(page):void 0,canvas=await canvasMountState(page),missing=await missingHostStylesheets(page,opts.html);return{png,nodeRects,...dom?{dom}:{},...canvas?{canvas}:{},...missing?.length?{missingHostStylesheets:missing}:{}}})}async function screenshotInternal(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();if(await openDocument(page,opts.html),await settleForCapture(page,opts.html),opts.clipSelector){let locator=page.locator(opts.clipSelector).first();if(await locator.count()===0)throw Error(`screenshot: no element matches selector ${opts.clipSelector}`);if(opts.outPath)return await locator.screenshot({path:opts.outPath,timeout:CAPTURE_TIMEOUT_MS}),null;return await locator.screenshot({timeout:CAPTURE_TIMEOUT_MS})}let fullPage=opts.fullPage??!0;if(opts.outPath)return await page.screenshot({path:opts.outPath,fullPage,timeout:CAPTURE_TIMEOUT_MS}),null;return await page.screenshot({fullPage,timeout:CAPTURE_TIMEOUT_MS})})}async function measureRendered(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:1},async(context)=>{let page=await context.newPage();return await openDocument(page,opts.html),await settleForCapture(page,opts.html),extractDom(page)})}function buildBoardComposite(frames,options={}){let maxWidth=options.maxWidth??1600,labelPad=options.labels?26:0,minX=Math.min(...frames.map(({frame})=>frame.x)),minY=Math.min(...frames.map(({frame})=>frame.y)),maxX=Math.max(...frames.map(({frame})=>frame.x+frame.w)),maxY=Math.max(...frames.map(({frame})=>frame.y+frame.h)),w=maxX-minX+48,h=maxY-minY+48+labelPad,scale=Math.min(1,maxWidth/w),outW=Math.max(1,Math.round(w*scale)),outH=Math.max(1,Math.round(h*scale)),esc=(s)=>s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),pieces=frames.map(({frame,html,label})=>{let left=frame.x-minX+24,top=frame.y-minY+24+labelPad;return(options.labels&&label?`<div class="label" style="left:${left}px;top:${top-26}px">${esc(label)}</div>`:"")+`<iframe scrolling="no" srcdoc="${esc(html)}" style="position:absolute;left:${left}px;top:${top}px;width:${frame.w}px;height:${frame.h}px"></iframe>`}).join(`
1437
+ `)}function renderBody(screen,registry,snippets){return renderBodyGuarded(screen,registry,snippets).html}var CANVAS_ATTRIBUTE=/^data-(?:node-path|node-text|snippet-id|snippet-path|velloo-.*)$/;async function renderNativeHtml(screen,registry,snippets){return new HTMLRewriter().on('link[rel="preload"]',{element(element){element.remove()}}).on("*",{element(element){let param=element.getAttribute("data-velloo-param");if(param!==null){element.replace(`$${param}`);return}let html=element.namespaceURI==="http://www.w3.org/1999/xhtml";for(let[name,value]of[...element.attributes])if(CANVAS_ATTRIBUTE.test(name))element.removeAttribute(name);else if(html)element.removeAttribute(name),element.setAttribute(name,value)}}).transform(new Response(renderBody(screen,registry,snippets))).text()}function renderBodyGuarded(screen,registry,snippets){return ScreenSchema.parse(screen),renderGuarded(registry,(active)=>$renderToString(buildRoot(screen.tree,{registry:active,snippets})))}async function renderScreen(screen,theme,options){ScreenSchema.parse(screen),ThemeSchema.parse(theme);let pass=options.renderPass,{html:bodyHtml,failures}=renderGuarded(options.registry,(active)=>{let element=buildRoot(screen.tree,{registry:active,snippets:options.snippets});return $renderToString(pass?pass.wrap(element):element)}),themeCss=themeToCss(theme),staticHtml=[],canvasBundle=options.canvasBundle?(()=>{let staticRefs=options.canvasBundle.staticRefs??[],tree=serializeTree(screen.tree,{snippets:options.snippets,...staticRefs.length>0?{staticFallback:{refs:new Set(staticRefs),render:(node,path,lockedPath)=>{let element=buildTree(node,{registry:options.registry,snippets:options.snippets},path,[],lockedPath),html=$renderToString(pass?pass.wrap(element):element);return staticHtml.push(html),html}}}:{}});return tree?{url:options.canvasBundle.url,tree,themeOptions:options.canvasBundle.themeOptions,preview:options.canvasBundle.preview,...screen.route?{pathname:screen.route}:{}}:void 0})():void 0,adapterCss=pass?pass.css([bodyHtml,...staticHtml].join("")):void 0;return{html:buildDocument({viewport:options.viewport,bodyHtml,snapshotCss:options.snapshotCss,themeCss,adapterCss,customCss:options.customCss,googleFonts:theme.typography.googleFonts,baseHref:options.baseHref,title:screen.name,dark:options.dark,liveBundleUrl:options.liveBundleUrl,canvasBundle,...options.includeRuntime!==void 0?{includeRuntime:options.includeRuntime}:{},...options.selectionRing!==void 0?{selectionRing:options.selectionRing}:{},...options.scriptNonce!==void 0?{scriptNonce:options.scriptNonce}:{},...options.hostStylesheets?{hostStylesheets:options.hostStylesheets}:{},...options.appCss?{appCss:options.appCss}:{}}),bodyHtml,themeCss,failures}}var NO_RUNTIMES={live:!1,canvas:!1},READY_SLACK_MS=1000,READY_TIMEOUT_MS=LIVE_GATE_MS+LIVE_ISLANDS_MS+READY_SLACK_MS;async function runtimesOf(target){return target.evaluate(()=>({live:document.querySelector("[data-live-node]")!==null,canvas:document.getElementById("velloo-canvas-data")!==null})).catch(()=>NO_RUNTIMES)}async function waitForRuntimes(target,runtimes){if(!runtimes.live&&!runtimes.canvas)return;await target.waitForFunction((want)=>{let w=window;return(!want.live||w.__velloo_live_ready===!0)&&(!want.canvas||w.__velloo_canvas_ready===!0)},runtimes,{timeout:READY_TIMEOUT_MS}).catch(()=>{})}async function missingHostStylesheets(target,html){if(!html.includes(HOST_STYLESHEET_ATTRIBUTE))return;return target.evaluate((attribute)=>[...document.querySelectorAll(`link[${attribute}]`)].flatMap((link)=>{let entry=performance.getEntriesByName(link.href)[0];if(!entry)return[];let status=entry.responseStatus??0,sameOrigin=new URL(link.href).origin===location.origin;return status>=400||sameOrigin&&status===0?[`${status||"blocked"} stylesheet ${link.getAttribute(attribute)}`]:[]}),HOST_STYLESHEET_ATTRIBUTE).catch(()=>{return})}async function waitForFonts(target){await target.evaluate(()=>Promise.race([document.fonts.ready,new Promise((r)=>setTimeout(r,2000))])).catch(()=>{})}async function settleDocument(target){await waitForFonts(target),await waitForRuntimes(target,await runtimesOf(target))}async function settleForCapture(page){await page.waitForLoadState("load",{timeout:5000}).catch(()=>{});let children=page.frames().filter((frame)=>frame!==page.mainFrame());await Promise.all([settleDocument(page),...children.map(settleDocument)]),await Promise.all(page.frames().map(removeEditingChrome))}async function removeEditingChrome(frame){await frame.evaluate(()=>{for(let thumb of document.querySelectorAll(".__velloo-scrollthumb"))thumb.remove()}).catch(()=>{})}async function screenshot(opts){return await screenshotInternal(opts),opts.outPath}async function screenshotBuffer(opts){let buf=await screenshotInternal(opts);if(!buf)throw Error("screenshotBuffer: no buffer returned (internal invariant)");return buf}async function openDocument(page,html){let base=/<base href="(http:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?)\/?"/.exec(html)?.[1];if(!base){await page.setContent(html,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS});return}let url=`${base}/__velloo_capture/${crypto.randomUUID()}`;await page.route(url,(route)=>route.fulfill({status:200,contentType:"text/html; charset=utf-8",body:html})),await page.goto(url,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS})}async function canvasMountState(page){return page.evaluate(()=>{let w=window;if(!document.getElementById("velloo-canvas-data"))return;let ssr=document.getElementById("velloo-ssr"),mounted=Boolean(ssr&&ssr.style.display==="none");return{mounted,...!mounted&&w.__velloo_canvas_unmounted?{reason:w.__velloo_canvas_unmounted}:{},...w.__velloo_canvas_bundle?{bundle:w.__velloo_canvas_bundle}:{},diagnostics:w.__velloo_canvas_diagnostics??[]}}).catch(()=>{return})}async function probeCanvasMount(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:1},async(context)=>{let page=await context.newPage(),consoleErrors=[];return page.on("console",(message)=>{if(message.type()==="error")consoleErrors.push(message.text().slice(0,400))}),page.on("pageerror",(error)=>consoleErrors.push(error.message.slice(0,400))),await openDocument(page,opts.html),await settleForCapture(page),await page.waitForTimeout(150),{...await canvasMountState(page)??{mounted:!1,diagnostics:[]},consoleErrors:consoleErrors.slice(0,20)}})}async function freezePage(page){return page.evaluate(()=>{let cssOf=(sheet)=>{try{return[...sheet.cssRules].map((rule)=>rule.cssText).join(`
1438
+ `)}catch{return""}},attributesOf=(el)=>Object.fromEntries([...el.attributes].filter((attr)=>!/^on/i.test(attr.name)).map((attr)=>[attr.name,attr.value])),copy=document.documentElement.cloneNode(!0),paired=(selector)=>{let copies=[...copy.querySelectorAll(selector)];return[...document.querySelectorAll(selector)].flatMap((live,at)=>{let twin=copies[at];return twin?[[live,twin]]:[]})};for(let[live,twin]of paired("style"))if((live.textContent??"").trim()===""&&live.sheet)twin.textContent=cssOf(live.sheet);for(let[live,twin]of paired("input"))if(live.type==="checkbox"||live.type==="radio")twin.toggleAttribute("checked",live.checked);else if(live.type!=="file"&&live.type!=="password")twin.setAttribute("value",live.value);for(let[live,twin]of paired("textarea"))twin.textContent=live.value;for(let[live,twin]of paired("option"))twin.toggleAttribute("selected",live.selected);let head=copy.querySelector("head");for(let sheet of document.adoptedStyleSheets??[]){let style=document.createElement("style");style.textContent=cssOf(sheet),head?.append(style)}let ssr=document.getElementById("velloo-ssr"),mounted=Boolean(ssr&&ssr.style.display==="none");if(mounted)copy.querySelector("#velloo-ssr")?.remove();for(let el of copy.querySelectorAll("script, base, link[rel='modulepreload']"))el.remove();let styles=[...head?.querySelectorAll("style, link[rel='stylesheet']")??[]].map((el)=>el instanceof HTMLStyleElement?{tag:"style",attributes:attributesOf(el),css:el.textContent??""}:{tag:"link",attributes:attributesOf(el)}),body=copy.querySelector("body")?.innerHTML??"";for(let el of copy.querySelectorAll("template[data-velloo-anchor], style[data-velloo-pointer]"))el.remove();return{html:`<!doctype html>
1439
+ ${copy.outerHTML}`,head:styles,body,htmlAttributes:attributesOf(document.documentElement),bodyAttributes:attributesOf(document.body),mounted:mounted&&document.getElementById("velloo-canvas-data")!==null}})}async function captureMountedDocument(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:1},async(context)=>{let page=await context.newPage();await openDocument(page,opts.html),await settleForCapture(page);let canvas=await canvasMountState(page);return{...await freezePage(page),...canvas?{canvas}:{}}})}async function captureScreenshot(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();await openDocument(page,opts.html),await settleForCapture(page);let frozen=opts.freeze?await freezePage(page):void 0,nodeRects=await page.$$eval("[data-node-path]",(els)=>els.map((el)=>{let r=el.getBoundingClientRect();return{path:el.dataset.nodePath??"",x:r.left,y:r.top,w:r.width,h:r.height}})),png=await capturePagePng(page,opts.fullPage??!0,CAPTURE_TIMEOUT_MS),dom=opts.dom?await extractDom(page):void 0,canvas=await canvasMountState(page),missing=await missingHostStylesheets(page,opts.html);return{png,nodeRects,...dom?{dom}:{},...canvas?{canvas}:{},...missing?.length?{missingHostStylesheets:missing}:{},...frozen?{frozen}:{}}})}async function screenshotInternal(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();await openDocument(page,opts.html),await settleForCapture(page);let toFile=opts.outPath?{path:opts.outPath}:{};if(opts.clipSelector){let locator=page.locator(opts.clipSelector).first();if(await locator.count()===0)throw Error(`screenshot: no element matches selector ${opts.clipSelector}`);let png=await retryTransientScreenshot(()=>locator.screenshot({...toFile,timeout:CAPTURE_TIMEOUT_MS}));return opts.outPath?null:png}let fullPage=opts.fullPage??!0,png=await retryTransientScreenshot(()=>page.screenshot({...toFile,fullPage,timeout:CAPTURE_TIMEOUT_MS}));return opts.outPath?null:png})}async function measureRendered(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:1},async(context)=>{let page=await context.newPage();return await openDocument(page,opts.html),await settleForCapture(page),extractDom(page)})}function buildBoardComposite(frames,options={}){let maxWidth=options.maxWidth??1600,labelPad=options.labels?26:0,minX=Math.min(...frames.map(({frame})=>frame.x)),minY=Math.min(...frames.map(({frame})=>frame.y)),maxX=Math.max(...frames.map(({frame})=>frame.x+frame.w)),maxY=Math.max(...frames.map(({frame})=>frame.y+frame.h)),w=maxX-minX+48,h=maxY-minY+48+labelPad,scale=Math.min(1,maxWidth/w),outW=Math.max(1,Math.round(w*scale)),outH=Math.max(1,Math.round(h*scale)),esc=(s)=>s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),pieces=frames.map(({frame,html,label})=>{let left=frame.x-minX+24,top=frame.y-minY+24+labelPad;return(options.labels&&label?`<div class="label" style="left:${left}px;top:${top-26}px">${esc(label)}</div>`:"")+`<iframe scrolling="no" srcdoc="${esc(html)}" style="position:absolute;left:${left}px;top:${top}px;width:${frame.w}px;height:${frame.h}px"></iframe>`}).join(`
1242
1440
  `);return{html:`<!doctype html>
1243
1441
  <html><head><meta charset="utf-8"><style>
1244
1442
  *{box-sizing:border-box}
@@ -1251,7 +1449,7 @@ iframe{border:1px solid #e4e4e7;background:#fff;display:block}
1251
1449
  <div class="canvas">
1252
1450
  ${pieces}
1253
1451
  </div>
1254
- </body></html>`,viewport:{w:outW,h:outH},scale}}async function screenshotCompareBuffer(opts){let labelLeft=opts.leftLabel??"light",labelRight=opts.rightLabel??"dark",w=opts.viewport.w,h=opts.viewport.h,wrapper=buildCompareWrapper(opts.leftHtml,opts.rightHtml,w,h,labelLeft,labelRight);return withContext({viewport:{width:w*2+24,height:800},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();return await page.setContent(wrapper,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await page.waitForFunction(()=>{let l=document.getElementById("L"),r=document.getElementById("R");return!!(l&&r&&l.dataset.ready==="1"&&r.dataset.ready==="1")},void 0,{timeout:CAPTURE_TIMEOUT_MS}).catch(()=>{}),await settleForCapture(page,wrapper,{liveIslands:!1}),await Promise.all(page.frames().filter((frame)=>frame!==page.mainFrame()).map(async(frame)=>{let html=frame.name()==="R"?opts.rightHtml:opts.leftHtml;await waitForFonts(frame),await waitForLiveIslands(frame,html)})),await page.screenshot({fullPage:!0,timeout:CAPTURE_TIMEOUT_MS})})}function buildCompareWrapper(leftHtml,rightHtml,panelWidth,panelHeight,leftLabel,rightLabel){let esc=escapeHtml;return`<!doctype html>
1452
+ </body></html>`,viewport:{w:outW,h:outH},scale}}async function screenshotCompareBuffer(opts){let labelLeft=opts.leftLabel??"light",labelRight=opts.rightLabel??"dark",w=opts.viewport.w,h=opts.viewport.h,wrapper=buildCompareWrapper(opts.leftHtml,opts.rightHtml,w,h,labelLeft,labelRight);return withContext({viewport:{width:w*2+24,height:800},deviceScaleFactor:opts.deviceScaleFactor??1},async(context)=>{let page=await context.newPage();return await page.setContent(wrapper,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await page.waitForFunction(()=>{let l=document.getElementById("L"),r=document.getElementById("R");return!!(l&&r&&l.dataset.ready==="1"&&r.dataset.ready==="1")},void 0,{timeout:CAPTURE_TIMEOUT_MS}).catch(()=>{}),await settleForCapture(page),await retryTransientScreenshot(()=>page.screenshot({fullPage:!0,timeout:CAPTURE_TIMEOUT_MS}))})}function buildCompareWrapper(leftHtml,rightHtml,panelWidth,panelHeight,leftLabel,rightLabel){let esc=escapeHtml;return`<!doctype html>
1255
1453
  <html><head><meta charset="utf-8"><style>${["*{box-sizing:border-box}","body{margin:0;padding:8px;background:#f4f4f5;font-family:ui-sans-serif,system-ui,sans-serif;color:#27272a}",".row{display:flex;gap:8px;align-items:flex-start}",".panel{display:flex;flex-direction:column;gap:4px}",".label{font-size:11px;text-transform:uppercase;letter-spacing:0.05em;color:#71717a}","iframe{border:1px solid #e4e4e7;background:#fff;display:block}"].join("")}</style></head>
1256
1454
  <body>
1257
1455
  <div class="row">
@@ -1277,7 +1475,7 @@ iframe{border:1px solid #e4e4e7;background:#fff;display:block}
1277
1475
  }
1278
1476
  size("L"); size("R");
1279
1477
  </script>
1280
- </body></html>`}async function pdfPageBuffer(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h}},async(context)=>{let page=await context.newPage();await page.emulateMedia({media:"screen"}),await page.setContent(opts.html,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await settleForCapture(page,opts.html);let height=opts.fullPage??!0?Math.max(opts.viewport.h,await page.evaluate(()=>document.documentElement.scrollHeight).catch(()=>opts.viewport.h)):opts.viewport.h;if(opts.label)await page.evaluate((label)=>{let el=document.createElement("div");el.textContent=label,el.style.cssText="position:fixed;left:12px;bottom:12px;z-index:2147483647;font:600 11px/1 ui-sans-serif,system-ui,sans-serif;color:#fafafa;background:rgba(24,24,27,.85);padding:6px 10px;border-radius:8px",document.body.appendChild(el)},opts.label);return await page.pdf({width:`${opts.viewport.w}px`,height:`${height}px`,printBackground:!0,pageRanges:"1"})})}async function pdfDeckBuffer(pages){let first=pages[0];if(!first)throw Error("pdfDeckBuffer: no pages");if(pages.length===1)return pdfPageBuffer(first);let wrapper=buildDeckWrapper(pages),maxW=Math.max(...pages.map((p)=>p.viewport.w)),maxH=Math.max(...pages.map((p)=>p.viewport.h));return withContext({viewport:{width:maxW,height:maxH}},async(context)=>{let page=await context.newPage();return await page.emulateMedia({media:"screen"}),await page.setContent(wrapper,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await page.waitForFunction((count)=>{for(let i=0;i<count;i++){let f=document.getElementById(`f${i}`);if(!(f instanceof HTMLIFrameElement)||f.dataset.ready!=="1")return!1}return!0},pages.length,{timeout:CAPTURE_TIMEOUT_MS}).catch(()=>{}),await settleForCapture(page,wrapper,{liveIslands:!1}),await Promise.all(page.frames().filter((f)=>f!==page.mainFrame()).map(async(frame)=>{let entry=pages[Number(frame.name().slice(1))];if(await waitForFonts(frame),entry)await waitForLiveIslands(frame,entry.html)})),await page.evaluate((entries)=>{let rules=[];entries.forEach((e,i)=>{let f=document.getElementById(`f${i}`),section=document.getElementById(`s${i}`);if(!(f instanceof HTMLIFrameElement)||!(section instanceof HTMLElement))return;let content=f.contentDocument?.documentElement?.scrollHeight??e.h,height=e.fullPage?Math.max(e.h,content):e.h;f.height=String(height),section.style.height=`${height}px`,rules.push(`@page p${i}{size:${e.w}px ${height}px;margin:0}`)});let style=document.getElementById("deck-pages");if(style)style.textContent=rules.join(`
1478
+ </body></html>`}var ENDS_PARAGRAPH=new Set("address article aside blockquote center details dialog dir div dl dd dt fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp".split(" ")),SCOPE_BOUNDARY=new Set("applet button caption html marquee object table td template th".split(" ")),VOID=new Set("area base br col embed hr img input link meta param source track wbr".split(" ")),RAW_TEXT=new Set("iframe noembed noframes noscript script style textarea title".split(" ")),FOREIGN=new Set(["svg","math"]),TAG_NAME=/[a-zA-Z][^\s/>]*/y,NODE_PATH=/\sdata-node-path=(?:"([^"]*)"|'([^']*)')/;function tagEnd(html,from){let quote="";for(let i=from;i<html.length;i++){let ch=html[i];if(quote){if(ch===quote)quote=""}else if(ch==='"'||ch==="'")quote=ch;else if(ch===">")return i+1}return html.length}function skipContent(html,from,tag,nests){let token=new RegExp(`<(/?)${tag}(?=[\\s/>])`,"gi");token.lastIndex=from;let depth=1;for(let match=token.exec(html);match;match=token.exec(html)){let end=tagEnd(html,match.index);if(match[1])depth-=1;else if(nests&&html[end-2]!=="/")depth+=1;if(depth===0)return end;token.lastIndex=end}return html.length}function openParagraph(stack){for(let i=stack.length-1;i>=0;i--){let open=stack[i];if(open.tag==="p")return open;if(open.moved||SCOPE_BOUNDARY.has(open.tag))return null}return null}function paragraphBreaks(html){let breaks=[],stack=[],at=html.indexOf("<");while(at!==-1){if(html.startsWith("<!--",at)){let close=html.indexOf("-->",at+4);at=close===-1?-1:html.indexOf("<",close+3);continue}let closing=html[at+1]==="/";TAG_NAME.lastIndex=at+(closing?2:1);let name=TAG_NAME.exec(html)?.[0].toLowerCase();if(!name){at=html.indexOf("<",at+1);continue}let next=tagEnd(html,at);if(closing){let open=stack.findLastIndex((entry)=>entry.tag===name);if(open!==-1)stack.length=open}else{let source=html.slice(at,next),own=NODE_PATH.exec(source),path=own?own[1]??own[2]??"":stack.at(-1)?.path??null,paragraph=ENDS_PARAGRAPH.has(name)?openParagraph(stack):null;if(paragraph)breaks.push({tag:name,path,paragraphPath:paragraph.path});if(RAW_TEXT.has(name))next=skipContent(html,next,name,!1);else if(FOREIGN.has(name)){if(!source.endsWith("/>"))next=skipContent(html,next,name,!0)}else if(!VOID.has(name))stack.push({tag:name,path,moved:paragraph!==null})}at=html.indexOf("<",next)}return breaks}async function pdfPageBuffer(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h}},async(context)=>{let page=await context.newPage();await page.emulateMedia({media:"screen"}),await page.setContent(opts.html,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await settleForCapture(page);let height=opts.fullPage??!0?Math.max(opts.viewport.h,await page.evaluate(()=>document.documentElement.scrollHeight).catch(()=>opts.viewport.h)):opts.viewport.h;if(opts.label)await page.evaluate((label)=>{let el=document.createElement("div");el.textContent=label,el.style.cssText="position:fixed;left:12px;bottom:12px;z-index:2147483647;font:600 11px/1 ui-sans-serif,system-ui,sans-serif;color:#fafafa;background:rgba(24,24,27,.85);padding:6px 10px;border-radius:8px",document.body.appendChild(el)},opts.label);return await page.pdf({width:`${opts.viewport.w}px`,height:`${height}px`,printBackground:!0,pageRanges:"1"})})}async function pdfDeckBuffer(pages){let first=pages[0];if(!first)throw Error("pdfDeckBuffer: no pages");if(pages.length===1)return pdfPageBuffer(first);let wrapper=buildDeckWrapper(pages),maxW=Math.max(...pages.map((p)=>p.viewport.w)),maxH=Math.max(...pages.map((p)=>p.viewport.h));return withContext({viewport:{width:maxW,height:maxH}},async(context)=>{let page=await context.newPage();return await page.emulateMedia({media:"screen"}),await page.setContent(wrapper,{waitUntil:"domcontentloaded",timeout:CAPTURE_TIMEOUT_MS}),await page.waitForFunction((count)=>{for(let i=0;i<count;i++){let f=document.getElementById(`f${i}`);if(!(f instanceof HTMLIFrameElement)||f.dataset.ready!=="1")return!1}return!0},pages.length,{timeout:CAPTURE_TIMEOUT_MS}).catch(()=>{}),await settleForCapture(page),await page.evaluate((entries)=>{let rules=[];entries.forEach((e,i)=>{let f=document.getElementById(`f${i}`),section=document.getElementById(`s${i}`);if(!(f instanceof HTMLIFrameElement)||!(section instanceof HTMLElement))return;let content=f.contentDocument?.documentElement?.scrollHeight??e.h,height=e.fullPage?Math.max(e.h,content):e.h;f.height=String(height),section.style.height=`${height}px`,rules.push(`@page p${i}{size:${e.w}px ${height}px;margin:0}`)});let style=document.getElementById("deck-pages");if(style)style.textContent=rules.join(`
1281
1479
  `)},pages.map((p)=>({w:p.viewport.w,h:p.viewport.h,fullPage:p.fullPage??!0}))),await page.pdf({printBackground:!0,preferCSSPageSize:!0})})}function buildDeckWrapper(pages){let styles=["*{box-sizing:border-box}","html,body{margin:0;padding:0}","section{position:relative;overflow:hidden}","section:not(:last-of-type){break-after:page}","iframe{border:0;display:block;background:#fff}",".chip{position:absolute;left:12px;bottom:12px;z-index:2147483647;font:600 11px/1 ui-sans-serif,system-ui,sans-serif;color:#fafafa;background:rgba(24,24,27,.85);padding:6px 10px;border-radius:8px}"].join(""),pageRules=pages.map((p,i)=>`@page p${i}{size:${p.viewport.w}px ${p.viewport.h}px;margin:0}`).join(`
1282
1480
  `),sections=pages.map((p,i)=>{let{w,h}=p.viewport,chip=p.label?`<div class="chip">${escapeHtml(p.label)}</div>`:"";return`<section id="s${i}" style="page:p${i};width:${w}px;height:${h}px"><iframe id="f${i}" name="f${i}" width="${w}" height="${h}" srcdoc="${escapeHtml(p.html)}"></iframe>${chip}</section>`}).join(`
1283
1481
  `);return`<!doctype html>
@@ -1290,4 +1488,4 @@ for (let i = 0; i < ${pages.length}; i++) {
1290
1488
  f.addEventListener("load", () => { f.dataset.ready = "1"; });
1291
1489
  }
1292
1490
  </script>
1293
- </body></html>`}async function captureUrlScreenshot(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1,...opts.dark?{colorScheme:"dark"}:{},...opts.storageStatePath?{storageState:opts.storageStatePath}:{}},async(context)=>{if(opts.cookies&&opts.cookies.length>0)await context.addCookies(opts.cookies.map((cookie)=>({name:cookie.name,value:cookie.value,...cookie.url!==void 0?{url:cookie.url}:{},...cookie.domain!==void 0?{domain:cookie.domain}:{},...cookie.path!==void 0?{path:cookie.path}:{}})));if(opts.localStorage&&Object.keys(opts.localStorage).length>0)await context.addInitScript((entries)=>{try{for(let[k,v]of entries)localStorage.setItem(k,v)}catch{}},Object.entries(opts.localStorage));if(opts.dark)await context.addInitScript(()=>{try{localStorage.setItem("theme","dark")}catch{}});let page=await context.newPage();if(await page.goto(opts.url,{waitUntil:"domcontentloaded",timeout:15000}),opts.dark)await page.evaluate(()=>{let el=document.documentElement;el.classList.add("dark"),el.setAttribute("data-theme","dark"),el.style.colorScheme="dark"}).catch(()=>{});let settleMs=opts.settleTimeoutMs??8000,settleStart=Date.now();await page.waitForLoadState("networkidle",{timeout:settleMs}).catch(()=>{});let stillLoading=await page.waitForFunction(()=>{let shown=(el)=>el.getClientRects().length>0&&getComputedStyle(el).visibility!=="hidden";for(let el of document.querySelectorAll('[aria-busy="true"]'))if(shown(el))return!1;for(let el of document.body?.querySelectorAll("*")??[]){if(el.childElementCount>0)continue;if(/^\s*loading[^a-z0-9]*$/i.test(el.textContent??"")&&shown(el))return!1}return!0},void 0,{timeout:Math.max(1000,settleMs-(Date.now()-settleStart)),polling:100}).then(()=>!1).catch(()=>!0),finalUrl=page.url(),authWall=await page.locator('input[type="password"]').count().then((n)=>n>0).catch(()=>!1),pageError=stillLoading?"the target was still showing a loading state when it was captured \u2014 its data had not arrived, so the diff isn't about your design. Pass a higher settleTimeoutMs":await page.evaluate(()=>{if(document.querySelector("nextjs-portal, [data-nextjs-dialog], #__next-build-error, vite-error-overlay"))return"the target app is showing a dev error overlay \u2014 it's throwing, so the diff isn't about your design";let txt=(document.body?.innerText??"").trim();if(txt.length===0)return"the target captured as a blank page (no visible text)";let m=txt.match(/Unhandled Runtime Error|Application error: a (?:client|server)-side exception|Internal Server Error|This page (?:could not be|isn't) found|Failed to compile|\b(?:Type|Syntax|Reference)Error:/i);return m?`the target looks like an error page ("${m[0]}")`:null}).catch(()=>null),png=await page.screenshot({fullPage:opts.fullPage??!0,animations:"disabled",caret:"hide",timeout:CAPTURE_TIMEOUT_MS}),dom=opts.dom?await extractDom(page).catch(()=>{return}):void 0;return{png,finalUrl,authWall,pageError,...dom?{dom}:{}}})}var LOGIN_PATH=/\/(login|signin|sign-in|auth|authenticate|account\/login|users\/sign_in)(\/|$)/i;function classifyCapture(requested,finalUrl){try{let norm=(u)=>u.origin+u.pathname.replace(/\/+$/,""),reqUrl=new URL(requested),finUrl=new URL(finalUrl);return{redirected:norm(reqUrl)!==norm(finUrl),finalLooksLikeLogin:LOGIN_PATH.test(finUrl.pathname),requestedLooksLikeLogin:LOGIN_PATH.test(reqUrl.pathname)}}catch{return{redirected:requested!==finalUrl,finalLooksLikeLogin:LOGIN_PATH.test(finalUrl),requestedLooksLikeLogin:LOGIN_PATH.test(requested)}}}export{require_react_development,buildBoardComposite,CHROMIUM_INSTALL_ARGV,CHROMIUM_INSTALL_CMD,CHROMIUM_FULL_INSTALL_ARGV,CHROMIUM_DEPS_INSTALL_ARGV,CHROMIUM_DEPS_INSTALL_CMD,BrowserMissingError,chromiumExecutable,MAX_CONCURRENT_RENDERS,closePooledBrowser,isCaptureTimeout,capturesDir,sessionStatePath,captureDir,listCaptures,readCaptureManifest,deleteCapture,isSafeCaptureId,isSafeCaptureFile,diffPngs,downscalePng,resizePng,pngSize,cropPng,sideBySidePng,unionRegion,HeadedBrowserMissingError,startCaptureSession,resolveSnippetBody,resolveSnippetBodyForEdit,snippetParamPlaceholder,HOST_FILES_PREFIX,RENDER_ERROR_META,screenshotCompareBuffer,pdfPageBuffer,pdfDeckBuffer,RenderGuardLimitError,require_react_dom,collectSerializedRefs,serializeTree,themeToCss,renderNativeHtml,renderBodyGuarded,renderScreen,screenshot,screenshotBuffer,probeCanvasMount,captureScreenshot,measureRendered,captureUrlScreenshot,classifyCapture};
1491
+ </body></html>`}class HideSelectorError extends Error{selectors;constructor(selectors){super(`\`hide\` selectors that are not valid CSS: ${selectors.map((s)=>JSON.stringify(s)).join(", ")}`);this.selectors=selectors;this.name="HideSelectorError"}}async function hideSelectors(page,selectors){let outcome=await page.evaluate((list)=>{let invalid=[],matched={};for(let selector of list)try{matched[selector]=document.querySelectorAll(selector).length}catch{invalid.push(selector)}if(invalid.length>0)return{invalid,matched};if(!document.adoptedStyleSheets.some((sheet)=>sheet.vellooHide)){let sheet=new CSSStyleSheet;sheet.vellooHide=!0;for(let selector of list)try{sheet.insertRule(`${selector} { display: none !important; }`)}catch{invalid.push(selector)}document.adoptedStyleSheets=[...document.adoptedStyleSheets,sheet]}return{invalid,matched}},selectors);if(outcome.invalid.length>0)throw new HideSelectorError(outcome.invalid);return outcome.matched}var SCROLL_MAX_STEPS=40,SCROLL_PAUSE_MS=120,SCROLL_IMAGE_WAIT_MS=3000;function keepSeenElementsSeen(){let Native=window.IntersectionObserver;if(!Native)return;window.IntersectionObserver=class extends Native{constructor(callback,options){let seen=new WeakSet;super((entries,observer)=>{let kept=entries.filter((entry)=>{if(entry.isIntersecting)seen.add(entry.target);return entry.isIntersecting||!seen.has(entry.target)});if(kept.length>0)callback(kept,observer)},options)}}}async function scrollThrough(page){return page.evaluate(async({maxSteps,pauseMs,imageWaitMs})=>{let height=()=>Math.max(document.documentElement?.scrollHeight??0,document.body?.scrollHeight??0),pause=(ms)=>new Promise((resolve)=>setTimeout(resolve,ms)),to=(top)=>window.scrollTo({top,left:0,behavior:"instant"}),heightBefore=height(),stride=Math.max(1,Math.floor(window.innerHeight*0.8)),top=0,steps=0;while(top+window.innerHeight<height()&&steps<maxSteps)top+=stride,to(top),await pause(pauseMs),steps+=1;let truncated=top+window.innerHeight<height();to(0);let loading=[...document.images].filter((image)=>!image.complete).map((image)=>new Promise((resolve)=>{image.addEventListener("load",resolve,{once:!0}),image.addEventListener("error",resolve,{once:!0})}));return await Promise.race([Promise.all(loading),pause(imageWaitMs)]),await pause(pauseMs*2),{steps,heightBefore,heightAfter:height(),truncated}},{maxSteps:SCROLL_MAX_STEPS,pauseMs:SCROLL_PAUSE_MS,imageWaitMs:SCROLL_IMAGE_WAIT_MS}).catch(()=>null)}async function captureUrlScreenshot(opts){return withContext({viewport:{width:opts.viewport.w,height:opts.viewport.h},deviceScaleFactor:opts.deviceScaleFactor??1,...opts.dark?{colorScheme:"dark"}:{},...opts.storageStatePath?{storageState:opts.storageStatePath}:{}},async(context)=>{if(opts.cookies&&opts.cookies.length>0)await context.addCookies(opts.cookies.map((cookie)=>({name:cookie.name,value:cookie.value,...cookie.url!==void 0?{url:cookie.url}:{},...cookie.domain!==void 0?{domain:cookie.domain}:{},...cookie.path!==void 0?{path:cookie.path}:{}})));if(opts.localStorage&&Object.keys(opts.localStorage).length>0)await context.addInitScript((entries)=>{try{for(let[k,v]of entries)localStorage.setItem(k,v)}catch{}},Object.entries(opts.localStorage));if(opts.dark)await context.addInitScript(()=>{try{localStorage.setItem("theme","dark")}catch{}});let scrolls=(opts.fullPage??!0)&&opts.scroll!==!1;if(scrolls)await context.addInitScript(keepSeenElementsSeen);let page=await context.newPage();if(await page.goto(opts.url,{waitUntil:"domcontentloaded",timeout:15000}),opts.dark)await page.evaluate(()=>{let el=document.documentElement;el.classList.add("dark"),el.setAttribute("data-theme","dark"),el.style.colorScheme="dark"}).catch(()=>{});let hide=opts.hide?.length?opts.hide:null;if(hide)await hideSelectors(page,hide);let settleMs=opts.settleTimeoutMs??8000,settleStart=Date.now();await page.waitForLoadState("networkidle",{timeout:settleMs}).catch(()=>{});let stillLoading=await page.waitForFunction(()=>{let shown=(el)=>el.getClientRects().length>0&&getComputedStyle(el).visibility!=="hidden";for(let el of document.querySelectorAll('[aria-busy="true"]'))if(shown(el))return!1;for(let el of document.body?.querySelectorAll("*")??[]){if(el.childElementCount>0)continue;if(/^\s*loading[^a-z0-9]*$/i.test(el.textContent??"")&&shown(el))return!1}return!0},void 0,{timeout:Math.max(1000,settleMs-(Date.now()-settleStart)),polling:100}).then(()=>!1).catch(()=>!0),scroll=scrolls&&!stillLoading?await scrollThrough(page):null,finalUrl=page.url(),authWall=await page.locator('input[type="password"]').count().then((n)=>n>0).catch(()=>!1),pageError=stillLoading?"the target was still showing a loading state when it was captured \u2014 its data had not arrived, so the diff isn't about your design. Pass a higher settleTimeoutMs":await page.evaluate(()=>{if(document.querySelector("nextjs-portal, [data-nextjs-dialog], #__next-build-error, vite-error-overlay"))return"the target app is showing a dev error overlay \u2014 it's throwing, so the diff isn't about your design";let txt=(document.body?.innerText??"").trim();if(txt.length===0)return"the target captured as a blank page (no visible text)";let m=txt.match(/Unhandled Runtime Error|Application error: a (?:client|server)-side exception|Internal Server Error|This page (?:could not be|isn't) found|Failed to compile|\b(?:Type|Syntax|Reference)Error:/i);return m?`the target looks like an error page ("${m[0]}")`:null}).catch(()=>null),hidden=hide?await hideSelectors(page,hide):null,png=await capturePagePng(page,opts.fullPage??!0,CAPTURE_TIMEOUT_MS),dom=opts.dom?await extractDom(page).catch(()=>{return}):void 0;return{png,finalUrl,authWall,pageError,...dom?{dom}:{},...scroll?{scroll}:{},...hidden?{hidden}:{}}})}var LOGIN_PATH=/\/(login|signin|sign-in|auth|authenticate|account\/login|users\/sign_in)(\/|$)/i;function classifyCapture(requested,finalUrl){try{let norm=(u)=>u.origin+u.pathname.replace(/\/+$/,""),reqUrl=new URL(requested),finUrl=new URL(finalUrl);return{redirected:norm(reqUrl)!==norm(finUrl),finalLooksLikeLogin:LOGIN_PATH.test(finUrl.pathname),requestedLooksLikeLogin:LOGIN_PATH.test(reqUrl.pathname)}}catch{return{redirected:requested!==finalUrl,finalLooksLikeLogin:LOGIN_PATH.test(finalUrl),requestedLooksLikeLogin:LOGIN_PATH.test(requested)}}}export{TAILWIND_CLASSNAME,SX_PROP,STYLE_PROP,STYLE_CHANNELS,CSS_FRAMEWORK_CHANNEL,catalogFromManifest,identifierRef,styleChannelOf,UnknownProviderError,createProviderLoader,COMPONENT_GROUPS,UNGROUPED_LABEL,ownEntry,resolveNodeIdentity,require_react_development,buildBoardComposite,CHROMIUM_INSTALL_ARGV,CHROMIUM_INSTALL_CMD,CHROMIUM_FULL_INSTALL_ARGV,CHROMIUM_DEPS_INSTALL_ARGV,CHROMIUM_DEPS_INSTALL_CMD,BrowserMissingError,chromiumExecutable,MAX_CONCURRENT_RENDERS,closePooledBrowser,isCaptureTimeout,capturesDir,sessionStatePath,captureDir,listCaptures,readCaptureManifest,deleteCapture,isSafeCaptureId,isSafeCaptureFile,diffPngs,downscalePng,resizePng,pngSize,cropPng,sideBySidePng,unionRegion,HeadedBrowserMissingError,startCaptureSession,resolveSnippetBody,resolveSnippetBodyForEdit,snippetParamPlaceholder,HOST_FILES_PREFIX,RENDER_ERROR_META,screenshotCompareBuffer,paragraphBreaks,pdfPageBuffer,pdfDeckBuffer,RenderGuardLimitError,require_react_dom,collectSerializedRepoRefs,collectSerializedRefs,serializeTree,themeToCss,renderNativeHtml,renderBodyGuarded,renderScreen,screenshot,screenshotBuffer,probeCanvasMount,captureMountedDocument,captureScreenshot,measureRendered,HideSelectorError,captureUrlScreenshot,classifyCapture};