@kaptures/cli 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ import{createRequire as e}from"node:module";import{formatWithOptions as t,parseA
3
3
  `)}function Le(e){return typeof e==`function`?e():e}function Re(e=[],t={}){let r=new Set(t.boolean||[]),i=new Set(t.string||[]),a=t.alias||{},o=t.default||{},s=new Map,c=new Map;for(let[e,t]of Object.entries(a)){let n=t;for(let t of n)s.set(e,t),c.has(t)||c.set(t,[]),c.get(t).push(e),s.set(t,e),c.has(e)||c.set(e,[]),c.get(e).push(t)}let l={};function u(e){if(r.has(e))return`boolean`;let t=c.get(e)||[];for(let e of t)if(r.has(e))return`boolean`;return`string`}let d=new Set([...r,...i,...Object.keys(a),...Object.values(a).flat(),...Object.keys(o)]);for(let e of d)l[e]||(l[e]={type:u(e),default:o[e]});for(let[e,t]of s.entries())e.length===1&&l[t]&&!l[t].short&&(l[t].short=e);let f=[],p={};for(let t=0;t<e.length;t++){let n=e[t];if(n===`--`){f.push(...e.slice(t));break}if(n.startsWith(`--no-`)){let e=n.slice(5);p[e]=!0;continue}f.push(n)}let m;try{m=n({args:f,options:Object.keys(l).length>0?l:void 0,allowPositionals:!0,strict:!1})}catch{m={values:{},positionals:f}}let h={_:[]};h._=m.positionals;for(let[e,t]of Object.entries(m.values))h[e]=t;for(let[e]of Object.entries(p)){h[e]=!1;let t=s.get(e);t&&(h[t]=!1);let n=c.get(e);if(n)for(let e of n)h[e]=!1}for(let[e,t]of s.entries())h[e]!==void 0&&h[t]===void 0&&(h[t]=h[e]),h[t]!==void 0&&h[e]===void 0&&(h[e]=h[t]);return h}function ze(e,t){let n={boolean:[],string:[],alias:{},default:{}},r=Be(t);for(let e of r){if(e.type===`positional`)continue;e.type===`string`||e.type===`enum`?n.string.push(e.name):e.type===`boolean`&&n.boolean.push(e.name),e.default!==void 0&&(n.default[e.name]=e.default),e.alias&&(n.alias[e.name]=e.alias);let t=Ae(e.name),r=je(e.name);if(t!==e.name||r!==e.name){let i=Fe(n.alias[e.name]||[]);t!==e.name&&!i.includes(t)&&i.push(t),r!==e.name&&!i.includes(r)&&i.push(r),i.length>0&&(n.alias[e.name]=i)}}let i=Re(e,n),[...a]=i._,o=new Proxy(i,{get(e,t){return e[t]??e[Ae(t)]??e[je(t)]}});for(let[,e]of r.entries())if(e.type===`positional`){let t=a.shift();if(t!==void 0)o[e.name]=t;else if(e.default===void 0&&e.required!==!1)throw new Ke(`Missing required positional argument: ${e.name.toUpperCase()}`,`EARG`);else o[e.name]=e.default}else if(e.type===`enum`){let t=o[e.name],n=e.options||[];if(t!==void 0&&n.length>0&&!n.includes(t))throw new Ke(`Invalid value for argument: ${Xe(`--${e.name}`)} (${Xe(t)}). Expected one of: ${n.map(e=>Xe(e)).join(`, `)}.`,`EARG`)}else if(e.required&&o[e.name]===void 0)throw new Ke(`Missing required argument: --${e.name}`,`EARG`);return o}function Be(e){let t=[];for(let[n,r]of Object.entries(e||{}))t.push({...r,name:n,alias:Fe(r.alias)});return t}function T(e){return e}async function Ve(e,t){let n=await Le(e.args||{}),r=ze(t.rawArgs,n),i={rawArgs:t.rawArgs,args:r,data:t.data,cmd:e};typeof e.setup==`function`&&await e.setup(i);let a;try{let n=await Le(e.subCommands);if(n&&Object.keys(n).length>0){let r=t.rawArgs.findIndex(e=>!e.startsWith(`-`)),i=t.rawArgs[r];if(i){if(!n[i])throw new Ke(`Unknown command ${Xe(i)}`,`E_UNKNOWN_COMMAND`);let e=await Le(n[i]);e&&await Ve(e,{rawArgs:t.rawArgs.slice(r+1)})}else if(!e.run)throw new Ke(`No command specified.`,`E_NO_COMMAND`)}typeof e.run==`function`&&(a=await e.run(i))}finally{typeof e.cleanup==`function`&&await e.cleanup(i)}return{result:a}}async function He(e,t,n){let r=await Le(e.subCommands);if(r&&Object.keys(r).length>0){let n=t.findIndex(e=>!e.startsWith(`-`)),i=t[n],a=await Le(r[i]);if(a)return He(a,t.slice(n+1),e)}return[e,n]}async function Ue(e,t){try{console.log(await We(e,t)+`
4
4
  `)}catch(e){console.error(e)}}async function We(e,t){let n=await Le(e.meta||{}),r=Be(await Le(e.args||{})),i=await Le(t?.meta||{}),a=`${i.name?`${i.name} `:``}`+(n.name||process.argv[1]),o=[],s=[],c=[],l=[];for(let e of r)if(e.type===`positional`){let t=e.name.toUpperCase(),n=e.required!==!1&&e.default===void 0,r=e.default?`="${e.default}"`:``;s.push([Xe(t+r),e.description||``,e.valueHint?`<${e.valueHint}>`:``]),l.push(n?`<${t}>`:`[${t}]`)}else{let t=e.required===!0&&e.default===void 0,n=[...(e.alias||[]).map(e=>`-${e}`),`--${e.name}`].join(`, `)+(e.type===`string`&&(e.valueHint||e.default)?`=${e.valueHint?`<${e.valueHint}>`:`"${e.default||``}"`}`:``)+(e.type===`enum`&&e.options?`=<${e.options.join(`|`)}>`:``);if(o.push([Xe(n+(t?` (required)`:``)),e.description||``]),e.type===`boolean`&&(e.default===!0||e.negativeDescription)&&!$e.test(e.name)){let n=[...(e.alias||[]).map(e=>`--no-${e}`),`--no-${e.name}`].join(`, `);o.push([Xe(n+(t?` (required)`:``)),e.negativeDescription||``])}t&&l.push(n)}if(e.subCommands){let t=[],n=await Le(e.subCommands);for(let[e,r]of Object.entries(n)){let n=await Le((await Le(r))?.meta);n?.hidden||(c.push([Xe(e),n?.description||``]),t.push(e))}l.push(t.join(`|`))}let u=[],d=n.version||i.version;u.push(Ze(`${n.description} (${a+(d?` v${d}`:``)})`),``);let f=o.length>0||s.length>0;return u.push(`${Qe(Ye(`USAGE`))} ${Xe(`${a}${f?` [OPTIONS]`:``} ${l.join(` `)}`)}`,``),s.length>0&&(u.push(Qe(Ye(`ARGUMENTS`)),``),u.push(Ie(s,` `)),u.push(``)),o.length>0&&(u.push(Qe(Ye(`OPTIONS`)),``),u.push(Ie(o,` `)),u.push(``)),c.length>0&&(u.push(Qe(Ye(`COMMANDS`)),``),u.push(Ie(c,` `)),u.push(``,`Use ${Xe(`${a} <command> --help`)} for more information about a command.`)),u.filter(e=>typeof e==`string`).join(`
5
5
  `)}async function Ge(e,t={}){let n=t.rawArgs||process.argv.slice(2),r=t.showUsage||Ue;try{if(n.includes(`--help`)||n.includes(`-h`))await r(...await He(e,n)),process.exit(0);else if(n.length===1&&n[0]===`--version`){let t=typeof e.meta==`function`?await e.meta():await e.meta;if(!t?.version)throw new Ke(`No version specified`,`E_NO_VERSION`);console.log(t.version)}else await Ve(e,{rawArgs:n})}catch(t){t instanceof Ke?(await r(...await He(e,n)),console.error(t.message)):console.error(t,`
6
- `),process.exit(1)}}var Ke,qe,Je,Ye,Xe,Ze,Qe,$e,E=S((()=>{Pe(),Ke=class extends Error{code;constructor(e,t){super(e),this.name=`CLIError`,this.code=t}},qe=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),Je=(e,t=39)=>n=>qe?n:`\u001B[${e}m${n}\u001B[${t}m`,Ye=Je(1,22),Xe=Je(36),Ze=Je(90),Qe=Je(4,24),$e=/^no[-A-Z]/}));E();var et=`0.4.0`;const tt=e(import.meta.url);async function nt(e=!1){let t=tt.resolve(`agent-browser/package.json`),n=[f(a(t),`bin`,`agent-browser.js`),`install`];e&&n.push(`--with-deps`);let i=await new Promise((e,t)=>{let i=r(process.execPath,n,{stdio:`inherit`});i.once(`error`,t),i.once(`exit`,(n,r)=>{r?t(Error(`agent-browser install stopped by ${r}`)):e(n??1)})});if(i!==0)throw Error(`agent-browser install exited with code ${i}`)}const rt=T({meta:{name:`browser`,description:`Manage the Kapture browser runtime`},subCommands:{install:T({meta:{name:`install`,description:`Install the Chrome runtime used by agent-browser`},args:{"with-deps":{type:`boolean`,default:!1,description:`Also install Linux system dependencies`}},async run({args:e}){await nt(e[`with-deps`])}})}});function it(e,t,n,r,i,a={}){let{threshold:o=.1,alpha:s=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=a;if(!at(e)||!at(t)||n&&!at(n))throw Error(`Image data: Uint8Array, Uint8ClampedArray or Buffer expected.`);if(e.length!==t.length||n&&n.length!==e.length)throw Error(`Image sizes do not match.`);if(e.length!==r*i*4)throw Error(`Image data size does not match width/height.`);let p=r*i,m=new Uint32Array(e.buffer,e.byteOffset,p),h=new Uint32Array(t.buffer,t.byteOffset,p),g=!0;for(let e=0;e<p;e++)if(m[e]!==h[e]){g=!1;break}if(g){if(n&&!f)for(let t=0;t<p;t++)ut(e,4*t,s,n);return 0}let _=35215*o*o,[ee,v,y]=c,[te,b,x]=l,[ne,re,ie]=d||l,ae=0;for(let a=0;a<i;a++)for(let o=0;o<r;o++){let c=a*r+o,l=c*4,d=m[c]===h[c]?0:ct(e,t,l,l,!1);if(Math.abs(d)>_){let s=ot(e,o,a,r,i,m,h)||ot(t,o,a,r,i,h,m);!u&&s?n&&!f&&lt(n,l,ee,v,y):(n&&(d<0?lt(n,l,ne,re,ie):lt(n,l,te,b,x)),ae++)}else n&&!f&&ut(e,l,s,n)}return ae}function at(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function ot(e,t,n,r,i,a,o){let s=Math.max(t-1,0),c=Math.max(n-1,0),l=Math.min(t+1,r-1),u=Math.min(n+1,i-1),d=n*r+t,f=+(t===s||t===l||n===c||n===u),p=0,m=0,h=0,g=0,_=0,ee=0;for(let i=s;i<=l;i++)for(let a=c;a<=u;a++){if(i===t&&a===n)continue;let o=ct(e,e,d*4,(a*r+i)*4,!0);if(o===0){if(f++,f>2)return!1}else o<p?(p=o,h=i,g=a):o>m&&(m=o,_=i,ee=a)}return p===0||m===0?!1:st(a,h,g,r,i)&&st(o,h,g,r,i)||st(a,_,ee,r,i)&&st(o,_,ee,r,i)}function st(e,t,n,r,i){let a=Math.max(t-1,0),o=Math.max(n-1,0),s=Math.min(t+1,r-1),c=Math.min(n+1,i-1),l=e[n*r+t],u=+(t===a||t===s||n===o||n===c);for(let i=a;i<=s;i++)for(let a=o;a<=c;a++)if((i!==t||a!==n)&&(u+=+(l===e[a*r+i]),u>2))return!0;return!1}function ct(e,t,n,r,i){let a=e[n],o=e[n+1],s=e[n+2],c=e[n+3],l=t[r],u=t[r+1],d=t[r+2],f=t[r+3],p=a-l,m=o-u,h=s-d,g=c-f;if(!p&&!m&&!h&&!g)return 0;if(c<255||f<255){let e=48+n%2*159,t=48+159*((n/1.618033988749895|0)%2),r=48+159*((n/2.618033988749895|0)%2);p=(a*c-l*f-e*g)/255,m=(o*c-u*f-t*g)/255,h=(s*c-d*f-r*g)/255}let _=p*.29889531+m*.58662247+h*.11448223;if(i)return _;let ee=p*.59597799-m*.2741761-h*.32180189,v=p*.21147017-m*.52261711+h*.31114694,y=.5053*_*_+.299*ee*ee+.1957*v*v;return _>0?-y:y}function lt(e,t,n,r,i){e[t+0]=n,e[t+1]=r,e[t+2]=i,e[t+3]=255}function ut(e,t,n,r){let i=255+(e[t]*.29889531+e[t+1]*.58662247+e[t+2]*.11448223-255)*n*e[t+3]/255;lt(r,t,i,i,i)}var dt=S((()=>{})),ft=C(((e,t)=>{let n=w(`util`),r=w(`stream`),i=t.exports=function(){r.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};n.inherits(i,r),i.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},i.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},i.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},i.prototype.destroySoon=i.prototype.end,i.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},i.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},i.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},i.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},i.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),pt=C((e=>{let t=[{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]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),mt=C(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),ht=C(((e,t)=>{let n=pt(),r=mt();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},a.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},a.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},a.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},a.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),gt=C(((e,t)=>{let n=w(`util`),r=ft(),i=ht(),a=t.exports=function(e){r.call(this);let t=[],n=this;this._filter=new i(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};n.inherits(a,r)})),_t=C(((e,t)=>{t.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}})),vt=C(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),yt=C(((e,t)=>{let n=_t(),r=vt(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),bt=C((e=>{let t=pt(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function i(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function a(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function o(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),xt=C(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),St=C(((e,t)=>{let n=w(`util`),r=w(`zlib`),i=ft(),a=gt(),o=yt(),s=bt(),c=xt(),l=t.exports=function(e){i.call(this),this._parser=new o(e,{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=e,this.writable=!0,this._parser.start()};n.inherits(l,i),l.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},l.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=r.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 e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:t});let n=e,i=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&i(e)}),this._filter.on(`complete`,this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},l.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new a(this._bitmapInfo)},l.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},l.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},l.prototype._simpleTransparency=function(){this._metaData.alpha=!0},l.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},l.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},l.prototype._complete=function(e){if(this.errord)return;let t;try{let n=s.dataToBitMap(e,this._bitmapInfo);t=c(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),Ct=C(((e,t)=>{let n=_t();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),wt=C(((e,t)=>{let n=mt();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function a(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function o(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function s(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function c(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function l(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function u(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function d(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function f(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let p={0:r,1:a,2:s,3:l,4:d},m={0:i,1:o,2:c,3:u,4:f};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=m[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,p[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),Tt=C(((e,t)=>{let n=_t(),r=vt(),i=Ct(),a=wt(),o=w(`zlib`),s=t.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||o.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:n.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:n.COLORTYPE_COLOR_ALPHA,[n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};s.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},s.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},s.prototype.filterData=function(e,t,r){let o=i(e,t,r,this._options),s=n.COLORTYPE_TO_BPP_MAP[this._options.colorType];return a(o,t,r,this._options,s)},s.prototype._packChunk=function(e,t){let n=t?t.length:0,i=Buffer.alloc(n+12);return i.writeUInt32BE(n,0),i.writeUInt32BE(e,4),t&&t.copy(i,8),i.writeInt32BE(r.crc32(i.slice(4,i.length-4)),i.length-4),i},s.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*n.GAMMA_DIVISION),0),this._packChunk(n.TYPE_gAMA,t)},s.prototype.packIHDR=function(e,t){let r=Buffer.alloc(13);return r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(n.TYPE_IHDR,r)},s.prototype.packIDAT=function(e){return this._packChunk(n.TYPE_IDAT,e)},s.prototype.packIEND=function(){return this._packChunk(n.TYPE_IEND,null)}})),Et=C(((e,t)=>{let n=w(`util`),r=w(`stream`),i=_t(),a=Tt(),o=t.exports=function(e){r.call(this);let t=e||{};this._packer=new a(t),this._deflate=this._packer.createDeflate(),this.readable=!0};n.inherits(o,r),o.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(i.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let a=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(a)}})),Dt=C(((e,t)=>{let n=w(`assert`).ok,r=w(`zlib`),i=w(`util`),a=w(`buffer`).kMaxLength;function o(e){if(!(this instanceof o))return new o(e);e&&e.chunkSize<r.Z_MIN_CHUNK&&(e.chunkSize=r.Z_MIN_CHUNK),r.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function s(e){return new o(e)}function c(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}o.prototype._processChunk=function(e,t,i){if(typeof i==`function`)return r.Inflate._processChunk.call(this,e,t,i);let o=this,s=e&&e.length,l=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(o._hadError)return;let r=l-t;if(n(r>=0,`have should not go down`),r>0){let e=o._buffer.slice(o._offset,o._offset+r);if(o._offset+=r,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||o._offset>=o._chunkSize)&&(l=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),t===0&&(d+=s-e,s=e,!0)}n(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,l),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=a)throw c(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+a.toString(16)+` bytes`);let _=Buffer.concat(f,p);return c(this),_},i.inherits(o,r.Inflate);function l(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=r.Z_FINISH,e._processChunk(t,n)}function u(e,t){return l(new o(t),e)}t.exports=e=u,e.Inflate=o,e.createInflate=s,e.inflateSync=u})),Ot=C(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.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`)}})),kt=C((e=>{let t=Ot(),n=ht();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),At=C(((e,t)=>{let n=!0,r=w(`zlib`),i=Dt();r.deflateSync||(n=!1);let a=Ot(),o=kt(),s=yt(),c=bt(),l=xt();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let u;function d(e){u=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.alpha=!0}let _;function ee(e){_=e}let v=[];function y(e){v.push(e)}let te=new a(e);if(new s(t,{read:te.read.bind(te),error:d,metadata:p,gamma:ee,palette:h,transColor:m,inflateData:y,simpleTransparency:g}).start(),te.process(),u)throw u;let b=Buffer.concat(v);v.length=0;let x;if(f.interlace)x=r.inflateSync(b);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.height;x=i(b,{chunkSize:e,maxLength:e})}if(b=null,!x||!x.length)throw Error(`bad png - invalid inflate data response`);let ne=o.process(x,f);b=null;let re=c.dataToBitMap(ne,f);ne=null;let ie=l(re,f,t.skipRescale);return f.data=ie,f.gamma=_||0,f}})),jt=C(((e,t)=>{let n=!0,r=w(`zlib`);r.deflateSync||(n=!1);let i=_t(),a=Tt();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let o=new a(t||{}),s=[];s.push(Buffer.from(i.PNG_SIGNATURE)),s.push(o.packIHDR(e.width,e.height)),e.gamma&&s.push(o.packGAMA(e.gamma));let c=o.filterData(e.data,e.width,e.height),l=r.deflateSync(c,o.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(o.packIDAT(l)),s.push(o.packIEND()),Buffer.concat(s)}})),Mt=C((e=>{let t=At(),n=jt();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),Nt=C((e=>{let t=w(`util`),n=w(`stream`),r=St(),i=Et(),a=Mt(),o=e.PNG=function(e){n.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new r(e),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(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new i(e),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`))};t.inherits(o,n),o.sync=a,o.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},o.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},o.prototype.write=function(e){return this._parser.write(e),!0},o.prototype.end=function(e){this._parser.end(e)},o.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},o.prototype._gamma=function(e){this.gamma=e},o.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},o.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},o.prototype.bitblt=function(e,t,n,r,i,a,s){return o.bitblt(this,e,t,n,r,i,a,s),this},o.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},o.prototype.adjustGamma=function(){o.adjustGamma(this)}}));function D(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}function Pt(e){return e&&Object.assign(Lt,e),Lt}var Ft,It,Lt,Rt=S((()=>{Object.freeze({status:`aborted`}),Ft=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},It=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},Lt={}}));function zt(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Bt(e,t){return typeof t==`bigint`?t.toString():t}function Vt(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ht(e){return e==null}function Ut(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Wt(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==hn)return r===void 0&&(r=hn,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Gt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Kt(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function qt(e){return JSON.stringify(e)}function Jt(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}function Yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xt(e){if(Yt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Yt(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Zt(e){return Xt(e)?{...e}:Array.isArray(e)?[...e]:e}function Qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $t(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function k(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function en(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function tn(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return $t(e,Kt(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Gt(this,`shape`,e),e},checks:[]}))}function nn(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return $t(e,Kt(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Gt(this,`shape`,r),r},checks:[]}))}function rn(e,t){if(!Xt(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Gt(this,`shape`,n),n}}))}function an(e,t){if(!Xt(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Gt(this,`shape`,n),n}}))}function on(e,t){return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Gt(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function sn(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return $t(t,Kt(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Gt(this,`shape`,i),i},checks:[]}))}function cn(e,t,n){return $t(t,Kt(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Gt(this,`shape`,i),i}}))}function ln(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function un(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function dn(e){return typeof e==`string`?e:e?.message}function fn(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=dn(e.inst?._zod.def?.error?.(e))??dn(t?.error?.(e))??dn(n.customError?.(e))??dn(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function pn(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function mn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var hn,gn,_n,vn,yn,bn=S((()=>{hn=Symbol(`evaluating`),gn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{},_n=Vt(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}}),vn=new Set([`string`,`number`,`symbol`]),yn={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}}));function xn(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Sn(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}var Cn,wn,Tn,En=S((()=>{Rt(),bn(),Cn=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},wn=D(`$ZodError`,Cn),Tn=D(`$ZodError`,Cn,{Parent:Error})})),Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn=S((()=>{Rt(),En(),bn(),Dn=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Ft;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>fn(e,a,Pt())));throw gn(t,i?.callee),t}return o.value},On=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>fn(e,a,Pt())));throw gn(t,i?.callee),t}return o.value},kn=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ft;return a.issues.length?{success:!1,error:new(e??wn)(a.issues.map(e=>fn(e,i,Pt())))}:{success:!0,data:a.value}},An=kn(Tn),jn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>fn(e,i,Pt())))}:{success:!0,data:a.value}},Mn=jn(Tn),Nn=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Dn(e)(t,n,i)},Pn=e=>(t,n,r)=>Dn(e)(t,n,r),Fn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return On(e)(t,n,i)},In=e=>async(t,n,r)=>On(e)(t,n,r),Ln=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return kn(e)(t,n,i)},Rn=e=>(t,n,r)=>kn(e)(t,n,r),zn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return jn(e)(t,n,i)},Bn=e=>async(t,n,r)=>jn(e)(t,n,r)}));function Hn(){return new RegExp(nr,`u`)}function Un(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Wn(e){return RegExp(`^${Un(e)}$`)}function Gn(e){let t=Un({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${ur}T(?:${r})$`)}var Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr=S((()=>{Kn=/^[cC][^\s-]{8,}$/,qn=/^[0-9a-z]+$/,Jn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yn=/^[0-9a-vA-V]{20}$/,Xn=/^[A-Za-z0-9]{27}$/,Zn=/^[a-zA-Z0-9_-]{21}$/,Qn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$n=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,er=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nr=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,rr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ir=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ar=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,or=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cr=/^[A-Za-z0-9_-]*$/,lr=/^\+[1-9]\d{6,14}$/,ur=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,dr=RegExp(`^${ur}$`),fr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},pr=/^-?\d+$/,mr=/^-?\d+(?:\.\d+)?$/,hr=/^(?:true|false)$/i,gr=/^[^A-Z]*$/,_r=/^[^a-z]*$/})),A,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr=S((()=>{Rt(),vr(),bn(),A=D(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),yr={number:`number`,bigint:`bigint`,object:`date`},br=D(`$ZodCheckLessThan`,(e,t)=>{A.init(e,t);let n=yr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xr=D(`$ZodCheckGreaterThan`,(e,t)=>{A.init(e,t);let n=yr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Sr=D(`$ZodCheckMultipleOf`,(e,t)=>{A.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Wt(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Cr=D(`$ZodCheckNumberFormat`,(e,t)=>{A.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=yn[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=pr)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),wr=D(`$ZodCheckMaxLength`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=pn(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Tr=D(`$ZodCheckMinLength`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=pn(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Er=D(`$ZodCheckLengthEquals`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=pn(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Dr=D(`$ZodCheckStringFormat`,(e,t)=>{var n,r;A.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Or=D(`$ZodCheckRegex`,(e,t)=>{Dr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),kr=D(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=gr,Dr.init(e,t)}),Ar=D(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=_r,Dr.init(e,t)}),jr=D(`$ZodCheckIncludes`,(e,t)=>{A.init(e,t);let n=Qt(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Mr=D(`$ZodCheckStartsWith`,(e,t)=>{A.init(e,t);let n=RegExp(`^${Qt(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Nr=D(`$ZodCheckEndsWith`,(e,t)=>{A.init(e,t);let n=RegExp(`.*${Qt(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Pr=D(`$ZodCheckOverwrite`,(e,t)=>{A.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}})})),Ir,Lr=S((()=>{Ir=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
6
+ `),process.exit(1)}}var Ke,qe,Je,Ye,Xe,Ze,Qe,$e,E=S((()=>{Pe(),Ke=class extends Error{code;constructor(e,t){super(e),this.name=`CLIError`,this.code=t}},qe=(()=>{let e=globalThis.process?.env??{};return e.NO_COLOR===`1`||e.TERM===`dumb`||e.TEST||e.CI})(),Je=(e,t=39)=>n=>qe?n:`\u001B[${e}m${n}\u001B[${t}m`,Ye=Je(1,22),Xe=Je(36),Ze=Je(90),Qe=Je(4,24),$e=/^no[-A-Z]/}));E();var et=`0.5.0`;const tt=e(import.meta.url);async function nt(e=!1){let t=tt.resolve(`agent-browser/package.json`),n=[f(a(t),`bin`,`agent-browser.js`),`install`];e&&n.push(`--with-deps`);let i=await new Promise((e,t)=>{let i=r(process.execPath,n,{stdio:`inherit`});i.once(`error`,t),i.once(`exit`,(n,r)=>{r?t(Error(`agent-browser install stopped by ${r}`)):e(n??1)})});if(i!==0)throw Error(`agent-browser install exited with code ${i}`)}const rt=T({meta:{name:`browser`,description:`Manage the Kapture browser runtime`},subCommands:{install:T({meta:{name:`install`,description:`Install the Chrome runtime used by agent-browser`},args:{"with-deps":{type:`boolean`,default:!1,description:`Also install Linux system dependencies`}},async run({args:e}){await nt(e[`with-deps`])}})}});function it(e,t,n,r,i,a={}){let{threshold:o=.1,alpha:s=.1,aaColor:c=[255,255,0],diffColor:l=[255,0,0],includeAA:u,diffColorAlt:d,diffMask:f}=a;if(!at(e)||!at(t)||n&&!at(n))throw Error(`Image data: Uint8Array, Uint8ClampedArray or Buffer expected.`);if(e.length!==t.length||n&&n.length!==e.length)throw Error(`Image sizes do not match.`);if(e.length!==r*i*4)throw Error(`Image data size does not match width/height.`);let p=r*i,m=new Uint32Array(e.buffer,e.byteOffset,p),h=new Uint32Array(t.buffer,t.byteOffset,p),g=!0;for(let e=0;e<p;e++)if(m[e]!==h[e]){g=!1;break}if(g){if(n&&!f)for(let t=0;t<p;t++)ut(e,4*t,s,n);return 0}let _=35215*o*o,[ee,v,y]=c,[te,b,x]=l,[ne,re,ie]=d||l,ae=0;for(let a=0;a<i;a++)for(let o=0;o<r;o++){let c=a*r+o,l=c*4,d=m[c]===h[c]?0:ct(e,t,l,l,!1);if(Math.abs(d)>_){let s=ot(e,o,a,r,i,m,h)||ot(t,o,a,r,i,h,m);!u&&s?n&&!f&&lt(n,l,ee,v,y):(n&&(d<0?lt(n,l,ne,re,ie):lt(n,l,te,b,x)),ae++)}else n&&!f&&ut(e,l,s,n)}return ae}function at(e){return ArrayBuffer.isView(e)&&e.BYTES_PER_ELEMENT===1}function ot(e,t,n,r,i,a,o){let s=Math.max(t-1,0),c=Math.max(n-1,0),l=Math.min(t+1,r-1),u=Math.min(n+1,i-1),d=n*r+t,f=+(t===s||t===l||n===c||n===u),p=0,m=0,h=0,g=0,_=0,ee=0;for(let i=s;i<=l;i++)for(let a=c;a<=u;a++){if(i===t&&a===n)continue;let o=ct(e,e,d*4,(a*r+i)*4,!0);if(o===0){if(f++,f>2)return!1}else o<p?(p=o,h=i,g=a):o>m&&(m=o,_=i,ee=a)}return p===0||m===0?!1:st(a,h,g,r,i)&&st(o,h,g,r,i)||st(a,_,ee,r,i)&&st(o,_,ee,r,i)}function st(e,t,n,r,i){let a=Math.max(t-1,0),o=Math.max(n-1,0),s=Math.min(t+1,r-1),c=Math.min(n+1,i-1),l=e[n*r+t],u=+(t===a||t===s||n===o||n===c);for(let i=a;i<=s;i++)for(let a=o;a<=c;a++)if((i!==t||a!==n)&&(u+=+(l===e[a*r+i]),u>2))return!0;return!1}function ct(e,t,n,r,i){let a=e[n],o=e[n+1],s=e[n+2],c=e[n+3],l=t[r],u=t[r+1],d=t[r+2],f=t[r+3],p=a-l,m=o-u,h=s-d,g=c-f;if(!p&&!m&&!h&&!g)return 0;if(c<255||f<255){let e=48+n%2*159,t=48+159*((n/1.618033988749895|0)%2),r=48+159*((n/2.618033988749895|0)%2);p=(a*c-l*f-e*g)/255,m=(o*c-u*f-t*g)/255,h=(s*c-d*f-r*g)/255}let _=p*.29889531+m*.58662247+h*.11448223;if(i)return _;let ee=p*.59597799-m*.2741761-h*.32180189,v=p*.21147017-m*.52261711+h*.31114694,y=.5053*_*_+.299*ee*ee+.1957*v*v;return _>0?-y:y}function lt(e,t,n,r,i){e[t+0]=n,e[t+1]=r,e[t+2]=i,e[t+3]=255}function ut(e,t,n,r){let i=255+(e[t]*.29889531+e[t+1]*.58662247+e[t+2]*.11448223-255)*n*e[t+3]/255;lt(r,t,i,i,i)}var dt=S((()=>{})),ft=C(((e,t)=>{let n=w(`util`),r=w(`stream`),i=t.exports=function(){r.call(this),this._buffers=[],this._buffered=0,this._reads=[],this._paused=!1,this._encoding=`utf8`,this.writable=!0};n.inherits(i,r),i.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t}),process.nextTick(function(){this._process(),this._paused&&this._reads&&this._reads.length>0&&(this._paused=!1,this.emit(`drain`))}.bind(this))},i.prototype.write=function(e,t){if(!this.writable)return this.emit(`error`,Error(`Stream not writable`)),!1;let n;return n=Buffer.isBuffer(e)?e:Buffer.from(e,t||this._encoding),this._buffers.push(n),this._buffered+=n.length,this._process(),this._reads&&this._reads.length===0&&(this._paused=!0),this.writable&&!this._paused},i.prototype.end=function(e,t){e&&this.write(e,t),this.writable=!1,this._buffers&&(this._buffers.length===0?this._end():(this._buffers.push(null),this._process()))},i.prototype.destroySoon=i.prototype.end,i.prototype._end=function(){this._reads.length>0&&this.emit(`error`,Error(`Unexpected end of input`)),this.destroy()},i.prototype.destroy=function(){this._buffers&&(this.writable=!1,this._reads=null,this._buffers=null,this.emit(`close`))},i.prototype._processReadAllowingLess=function(e){this._reads.shift();let t=this._buffers[0];t.length>e.length?(this._buffered-=e.length,this._buffers[0]=t.slice(e.length),e.func.call(this,t.slice(0,e.length))):(this._buffered-=t.length,this._buffers.shift(),e.func.call(this,t))},i.prototype._processRead=function(e){this._reads.shift();let t=0,n=0,r=Buffer.alloc(e.length);for(;t<e.length;){let i=this._buffers[n++],a=Math.min(i.length,e.length-t);i.copy(r,t,0,a),t+=a,a!==i.length&&(this._buffers[--n]=i.slice(a))}n>0&&this._buffers.splice(0,n),this._buffered-=e.length,e.func.call(this,r)},i.prototype._process=function(){try{for(;this._buffered>0&&this._reads&&this._reads.length>0;){let e=this._reads[0];if(e.allowLess)this._processReadAllowingLess(e);else if(this._buffered>=e.length)this._processRead(e);else break}this._buffers&&!this.writable&&this._end()}catch(e){this.emit(`error`,e)}}})),pt=C((e=>{let t=[{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]}];e.getImagePasses=function(e,n){let r=[],i=e%8,a=n%8,o=(e-i)/8,s=(n-a)/8;for(let e=0;e<t.length;e++){let n=t[e],c=o*n.x.length,l=s*n.y.length;for(let e=0;e<n.x.length&&n.x[e]<i;e++)c++;for(let e=0;e<n.y.length&&n.y[e]<a;e++)l++;c>0&&l>0&&r.push({width:c,height:l,index:e})}return r},e.getInterlaceIterator=function(e){return function(n,r,i){let a=n%t[i].x.length,o=(n-a)/t[i].x.length*8+t[i].x[a],s=r%t[i].y.length,c=(r-s)/t[i].y.length*8+t[i].y[s];return o*4+c*e*4}}})),mt=C(((e,t)=>{t.exports=function(e,t,n){let r=e+t-n,i=Math.abs(r-e),a=Math.abs(r-t),o=Math.abs(r-n);return i<=a&&i<=o?e:a<=o?t:n}})),ht=C(((e,t)=>{let n=pt(),r=mt();function i(e,t,n){let r=e*t;return n!==8&&(r=Math.ceil(r/(8/n))),r}let a=t.exports=function(e,t){let r=e.width,a=e.height,o=e.interlace,s=e.bpp,c=e.depth;if(this.read=t.read,this.write=t.write,this.complete=t.complete,this._imageIndex=0,this._images=[],o){let e=n.getImagePasses(r,a);for(let t=0;t<e.length;t++)this._images.push({byteWidth:i(e[t].width,s,c),height:e[t].height,lineIndex:0})}else this._images.push({byteWidth:i(r,s,c),height:a,lineIndex:0});this._xComparison=c===8?s:c===16?s*2:1};a.prototype.start=function(){this.read(this._images[this._imageIndex].byteWidth+1,this._reverseFilterLine.bind(this))},a.prototype._unFilterType1=function(e,t,n){let r=this._xComparison,i=r-1;for(let a=0;a<n;a++){let n=e[1+a],o=a>i?t[a-r]:0;t[a]=n+o}},a.prototype._unFilterType2=function(e,t,n){let r=this._lastLine;for(let i=0;i<n;i++){let n=e[1+i],a=r?r[i]:0;t[i]=n+a}},a.prototype._unFilterType3=function(e,t,n){let r=this._xComparison,i=r-1,a=this._lastLine;for(let o=0;o<n;o++){let n=e[1+o],s=a?a[o]:0,c=o>i?t[o-r]:0,l=Math.floor((c+s)/2);t[o]=n+l}},a.prototype._unFilterType4=function(e,t,n){let i=this._xComparison,a=i-1,o=this._lastLine;for(let s=0;s<n;s++){let n=e[1+s],c=o?o[s]:0,l=s>a?t[s-i]:0,u=s>a&&o?o[s-i]:0,d=r(l,c,u);t[s]=n+d}},a.prototype._reverseFilterLine=function(e){let t=e[0],n,r=this._images[this._imageIndex],i=r.byteWidth;if(t===0)n=e.slice(1,i+1);else switch(n=Buffer.alloc(i),t){case 1:this._unFilterType1(e,n,i);break;case 2:this._unFilterType2(e,n,i);break;case 3:this._unFilterType3(e,n,i);break;case 4:this._unFilterType4(e,n,i);break;default:throw Error(`Unrecognised filter type - `+t)}this.write(n),r.lineIndex++,r.lineIndex>=r.height?(this._lastLine=null,this._imageIndex++,r=this._images[this._imageIndex]):this._lastLine=n,r?this.read(r.byteWidth+1,this._reverseFilterLine.bind(this)):(this._lastLine=null,this.complete())}})),gt=C(((e,t)=>{let n=w(`util`),r=ft(),i=ht(),a=t.exports=function(e){r.call(this);let t=[],n=this;this._filter=new i(e,{read:this.read.bind(this),write:function(e){t.push(e)},complete:function(){n.emit(`complete`,Buffer.concat(t))}}),this._filter.start()};n.inherits(a,r)})),_t=C(((e,t)=>{t.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}})),vt=C(((e,t)=>{let n=[];(function(){for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t&1?t=3988292384^t>>>1:t>>>=1;n[e]=t}})();let r=t.exports=function(){this._crc=-1};r.prototype.write=function(e){for(let t=0;t<e.length;t++)this._crc=n[(this._crc^e[t])&255]^this._crc>>>8;return!0},r.prototype.crc32=function(){return this._crc^-1},r.crc32=function(e){let t=-1;for(let r=0;r<e.length;r++)t=n[(t^e[r])&255]^t>>>8;return t^-1}})),yt=C(((e,t)=>{let n=_t(),r=vt(),i=t.exports=function(e,t){this._options=e,e.checkCRC=e.checkCRC!==!1,this._hasIHDR=!1,this._hasIEND=!1,this._emittedHeadersFinished=!1,this._palette=[],this._colorType=0,this._chunks={},this._chunks[n.TYPE_IHDR]=this._handleIHDR.bind(this),this._chunks[n.TYPE_IEND]=this._handleIEND.bind(this),this._chunks[n.TYPE_IDAT]=this._handleIDAT.bind(this),this._chunks[n.TYPE_PLTE]=this._handlePLTE.bind(this),this._chunks[n.TYPE_tRNS]=this._handleTRNS.bind(this),this._chunks[n.TYPE_gAMA]=this._handleGAMA.bind(this),this.read=t.read,this.error=t.error,this.metadata=t.metadata,this.gamma=t.gamma,this.transColor=t.transColor,this.palette=t.palette,this.parsed=t.parsed,this.inflateData=t.inflateData,this.finished=t.finished,this.simpleTransparency=t.simpleTransparency,this.headersFinished=t.headersFinished||function(){}};i.prototype.start=function(){this.read(n.PNG_SIGNATURE.length,this._parseSignature.bind(this))},i.prototype._parseSignature=function(e){let t=n.PNG_SIGNATURE;for(let n=0;n<t.length;n++)if(e[n]!==t[n]){this.error(Error(`Invalid file signature`));return}this.read(8,this._parseChunkBegin.bind(this))},i.prototype._parseChunkBegin=function(e){let t=e.readUInt32BE(0),i=e.readUInt32BE(4),a=``;for(let t=4;t<8;t++)a+=String.fromCharCode(e[t]);let o=!!(e[4]&32);if(!this._hasIHDR&&i!==n.TYPE_IHDR){this.error(Error(`Expected IHDR on beggining`));return}if(this._crc=new r,this._crc.write(Buffer.from(a)),this._chunks[i])return this._chunks[i](t);if(!o){this.error(Error(`Unsupported critical chunk type `+a));return}this.read(t+4,this._skipChunk.bind(this))},i.prototype._skipChunk=function(){this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleChunkEnd=function(){this.read(4,this._parseChunkEnd.bind(this))},i.prototype._parseChunkEnd=function(e){let t=e.readInt32BE(0),n=this._crc.crc32();if(this._options.checkCRC&&n!==t){this.error(Error(`Crc error - `+t+` - `+n));return}this._hasIEND||this.read(8,this._parseChunkBegin.bind(this))},i.prototype._handleIHDR=function(e){this.read(e,this._parseIHDR.bind(this))},i.prototype._parseIHDR=function(e){this._crc.write(e);let t=e.readUInt32BE(0),r=e.readUInt32BE(4),i=e[8],a=e[9],o=e[10],s=e[11],c=e[12];if(i!==8&&i!==4&&i!==2&&i!==1&&i!==16){this.error(Error(`Unsupported bit depth `+i));return}if(!(a in n.COLORTYPE_TO_BPP_MAP)){this.error(Error(`Unsupported color type`));return}if(o!==0){this.error(Error(`Unsupported compression method`));return}if(s!==0){this.error(Error(`Unsupported filter method`));return}if(c!==0&&c!==1){this.error(Error(`Unsupported interlace method`));return}this._colorType=a;let l=n.COLORTYPE_TO_BPP_MAP[this._colorType];this._hasIHDR=!0,this.metadata({width:t,height:r,depth:i,interlace:!!c,palette:!!(a&n.COLORTYPE_PALETTE),color:!!(a&n.COLORTYPE_COLOR),alpha:!!(a&n.COLORTYPE_ALPHA),bpp:l,colorType:a}),this._handleChunkEnd()},i.prototype._handlePLTE=function(e){this.read(e,this._parsePLTE.bind(this))},i.prototype._parsePLTE=function(e){this._crc.write(e);let t=Math.floor(e.length/3);for(let n=0;n<t;n++)this._palette.push([e[n*3],e[n*3+1],e[n*3+2],255]);this.palette(this._palette),this._handleChunkEnd()},i.prototype._handleTRNS=function(e){this.simpleTransparency(),this.read(e,this._parseTRNS.bind(this))},i.prototype._parseTRNS=function(e){if(this._crc.write(e),this._colorType===n.COLORTYPE_PALETTE_COLOR){if(this._palette.length===0){this.error(Error(`Transparency chunk must be after palette`));return}if(e.length>this._palette.length){this.error(Error(`More transparent colors than palette size`));return}for(let t=0;t<e.length;t++)this._palette[t][3]=e[t];this.palette(this._palette)}this._colorType===n.COLORTYPE_GRAYSCALE&&this.transColor([e.readUInt16BE(0)]),this._colorType===n.COLORTYPE_COLOR&&this.transColor([e.readUInt16BE(0),e.readUInt16BE(2),e.readUInt16BE(4)]),this._handleChunkEnd()},i.prototype._handleGAMA=function(e){this.read(e,this._parseGAMA.bind(this))},i.prototype._parseGAMA=function(e){this._crc.write(e),this.gamma(e.readUInt32BE(0)/n.GAMMA_DIVISION),this._handleChunkEnd()},i.prototype._handleIDAT=function(e){this._emittedHeadersFinished||(this._emittedHeadersFinished=!0,this.headersFinished()),this.read(-e,this._parseIDAT.bind(this,e))},i.prototype._parseIDAT=function(e,t){if(this._crc.write(t),this._colorType===n.COLORTYPE_PALETTE_COLOR&&this._palette.length===0)throw Error(`Expected palette not found`);this.inflateData(t);let r=e-t.length;r>0?this._handleIDAT(r):this._handleChunkEnd()},i.prototype._handleIEND=function(e){this.read(e,this._parseIEND.bind(this))},i.prototype._parseIEND=function(e){this._crc.write(e),this._hasIEND=!0,this._handleChunkEnd(),this.finished&&this.finished()}})),bt=C((e=>{let t=pt(),n=[function(){},function(e,t,n,r){if(r===t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=255},function(e,t,n,r){if(r+1>=t.length)throw Error(`Ran out of data`);let i=t[r];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=t[r+1]},function(e,t,n,r){if(r+2>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=255},function(e,t,n,r){if(r+3>=t.length)throw Error(`Ran out of data`);e[n]=t[r],e[n+1]=t[r+1],e[n+2]=t[r+2],e[n+3]=t[r+3]}],r=[function(){},function(e,t,n,r){let i=t[0];e[n]=i,e[n+1]=i,e[n+2]=i,e[n+3]=r},function(e,t,n){let r=t[0];e[n]=r,e[n+1]=r,e[n+2]=r,e[n+3]=t[1]},function(e,t,n,r){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=r},function(e,t,n){e[n]=t[0],e[n+1]=t[1],e[n+2]=t[2],e[n+3]=t[3]}];function i(e,t){let n=[],r=0;function i(){if(r===e.length)throw Error(`Ran out of data`);let i=e[r];r++;let a,o,s,c,l,u,d,f;switch(t){default:throw Error(`unrecognised depth`);case 16:d=e[r],r++,n.push((i<<8)+d);break;case 4:d=i&15,f=i>>4,n.push(f,d);break;case 2:l=i&3,u=i>>2&3,d=i>>4&3,f=i>>6&3,n.push(f,d,u,l);break;case 1:a=i&1,o=i>>1&1,s=i>>2&1,c=i>>3&1,l=i>>4&1,u=i>>5&1,d=i>>6&1,f=i>>7&1,n.push(f,d,u,l,c,s,o,a)}}return{get:function(e){for(;n.length<e;)i();let t=n.slice(0,e);return n=n.slice(e),t},resetAfterLine:function(){n.length=0},end:function(){if(r!==e.length)throw Error(`extra data found`)}}}function a(e,t,r,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++)for(let c=0;c<s;c++){let s=r(c,e,l);n[i](t,a,s,o),o+=i}return o}function o(e,t,n,i,a,o){let s=e.width,c=e.height,l=e.index;for(let e=0;e<c;e++){for(let c=0;c<s;c++){let s=a.get(i),u=n(c,e,l);r[i](t,s,u,o)}a.resetAfterLine()}}e.dataToBitMap=function(e,n){let r=n.width,s=n.height,c=n.depth,l=n.bpp,u=n.interlace,d;c!==8&&(d=i(e,c));let f;f=c<=8?Buffer.alloc(r*s*4):new Uint16Array(r*s*4);let p=2**c-1,m=0,h,g;if(u)h=t.getImagePasses(r,s),g=t.getInterlaceIterator(r,s);else{let e=0;g=function(){let t=e;return e+=4,t},h=[{width:r,height:s}]}for(let t=0;t<h.length;t++)c===8?m=a(h[t],f,g,l,e,m):o(h[t],f,g,l,d,p);if(c===8){if(m!==e.length)throw Error(`extra data found`)}else d.end();return f}})),xt=C(((e,t)=>{function n(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=i[e[a]];if(!n)throw Error(`index `+e[a]+` not in palette`);for(let e=0;e<4;e++)t[a+e]=n[e];a+=4}}function r(e,t,n,r,i){let a=0;for(let o=0;o<r;o++)for(let r=0;r<n;r++){let n=!1;if(i.length===1?i[0]===e[a]&&(n=!0):i[0]===e[a]&&i[1]===e[a+1]&&i[2]===e[a+2]&&(n=!0),n)for(let e=0;e<4;e++)t[a+e]=0;a+=4}}function i(e,t,n,r,i){let a=2**i-1,o=0;for(let i=0;i<r;i++)for(let r=0;r<n;r++){for(let n=0;n<4;n++)t[o+n]=Math.floor(e[o+n]*255/a+.5);o+=4}}t.exports=function(e,t,a=!1){let o=t.depth,s=t.width,c=t.height,l=t.colorType,u=t.transColor,d=t.palette,f=e;return l===3?n(e,f,s,c,d):(u&&r(e,f,s,c,u),o!==8&&!a&&(o===16&&(f=Buffer.alloc(s*c*4)),i(e,f,s,c,o))),f}})),St=C(((e,t)=>{let n=w(`util`),r=w(`zlib`),i=ft(),a=gt(),o=yt(),s=bt(),c=xt(),l=t.exports=function(e){i.call(this),this._parser=new o(e,{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=e,this.writable=!0,this._parser.start()};n.inherits(l,i),l.prototype._handleError=function(e){this.emit(`error`,e),this.writable=!1,this.destroy(),this._inflate&&this._inflate.destroy&&this._inflate.destroy(),this._filter&&(this._filter.destroy(),this._filter.on(`error`,function(){})),this.errord=!0},l.prototype._inflateData=function(e){if(!this._inflate){if(this._bitmapInfo.interlace)this._inflate=r.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 e=((this._bitmapInfo.width*this._bitmapInfo.bpp*this._bitmapInfo.depth+7>>3)+1)*this._bitmapInfo.height,t=Math.max(e,r.Z_MIN_CHUNK);this._inflate=r.createInflate({chunkSize:t});let n=e,i=this.emit.bind(this,`error`);this._inflate.on(`error`,function(e){n&&i(e)}),this._filter.on(`complete`,this._complete.bind(this));let a=this._filter.write.bind(this._filter);this._inflate.on(`data`,function(e){n&&(e.length>n&&(e=e.slice(0,n)),n-=e.length,a(e))}),this._inflate.on(`end`,this._filter.end.bind(this._filter))}}this._inflate.write(e)},l.prototype._handleMetaData=function(e){this._metaData=e,this._bitmapInfo=Object.create(e),this._filter=new a(this._bitmapInfo)},l.prototype._handleTransColor=function(e){this._bitmapInfo.transColor=e},l.prototype._handlePalette=function(e){this._bitmapInfo.palette=e},l.prototype._simpleTransparency=function(){this._metaData.alpha=!0},l.prototype._headersFinished=function(){this.emit(`metadata`,this._metaData)},l.prototype._finished=function(){this.errord||(this._inflate?this._inflate.end():this.emit(`error`,`No Inflate block`))},l.prototype._complete=function(e){if(this.errord)return;let t;try{let n=s.dataToBitMap(e,this._bitmapInfo);t=c(n,this._bitmapInfo,this._options.skipRescale),n=null}catch(e){this._handleError(e);return}this.emit(`parsed`,t)}})),Ct=C(((e,t)=>{let n=_t();t.exports=function(e,t,r,i){let a=[n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(i.colorType)!==-1;if(i.colorType===i.inputColorType){let t=(function(){let e=new ArrayBuffer(2);return new DataView(e).setInt16(0,256,!0),new Int16Array(e)[0]!==256})();if(i.bitDepth===8||i.bitDepth===16&&t)return e}let o=i.bitDepth===16?new Uint16Array(e.buffer):e,s=255,c=n.COLORTYPE_TO_BPP_MAP[i.inputColorType];c===4&&!i.inputHasAlpha&&(c=3);let l=n.COLORTYPE_TO_BPP_MAP[i.colorType];i.bitDepth===16&&(s=65535,l*=2);let u=Buffer.alloc(t*r*l),d=0,f=0,p=i.bgColor||{};p.red===void 0&&(p.red=s),p.green===void 0&&(p.green=s),p.blue===void 0&&(p.blue=s);function m(){let e,t,r,c=s;switch(i.inputColorType){case n.COLORTYPE_COLOR_ALPHA:c=o[d+3],e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_COLOR:e=o[d],t=o[d+1],r=o[d+2];break;case n.COLORTYPE_ALPHA:c=o[d+1],e=o[d],t=e,r=e;break;case n.COLORTYPE_GRAYSCALE:e=o[d],t=e,r=e;break;default:throw Error(`input color type:`+i.inputColorType+` is not supported at present`)}return i.inputHasAlpha&&(a||(c/=s,e=Math.min(Math.max(Math.round((1-c)*p.red+c*e),0),s),t=Math.min(Math.max(Math.round((1-c)*p.green+c*t),0),s),r=Math.min(Math.max(Math.round((1-c)*p.blue+c*r),0),s))),{red:e,green:t,blue:r,alpha:c}}for(let e=0;e<r;e++)for(let e=0;e<t;e++){let e=m(o,d);switch(i.colorType){case n.COLORTYPE_COLOR_ALPHA:case n.COLORTYPE_COLOR:i.bitDepth===8?(u[f]=e.red,u[f+1]=e.green,u[f+2]=e.blue,a&&(u[f+3]=e.alpha)):(u.writeUInt16BE(e.red,f),u.writeUInt16BE(e.green,f+2),u.writeUInt16BE(e.blue,f+4),a&&u.writeUInt16BE(e.alpha,f+6));break;case n.COLORTYPE_ALPHA:case n.COLORTYPE_GRAYSCALE:{let t=(e.red+e.green+e.blue)/3;i.bitDepth===8?(u[f]=t,a&&(u[f+1]=e.alpha)):(u.writeUInt16BE(t,f),a&&u.writeUInt16BE(e.alpha,f+2));break}default:throw Error(`unrecognised color Type `+i.colorType)}d+=c,f+=l}return u}})),wt=C(((e,t)=>{let n=mt();function r(e,t,n,r,i){for(let a=0;a<n;a++)r[i+a]=e[t+a]}function i(e,t,n){let r=0,i=t+n;for(let n=t;n<i;n++)r+=Math.abs(e[n]);return r}function a(e,t,n,r,i,a){for(let o=0;o<n;o++){let n=o>=a?e[t+o-a]:0,s=e[t+o]-n;r[i+o]=s}}function o(e,t,n,r){let i=0;for(let a=0;a<n;a++){let n=a>=r?e[t+a-r]:0,o=e[t+a]-n;i+=Math.abs(o)}return i}function s(e,t,n,r,i){for(let a=0;a<n;a++){let o=t>0?e[t+a-n]:0,s=e[t+a]-o;r[i+a]=s}}function c(e,t,n){let r=0,i=t+n;for(let a=t;a<i;a++){let i=t>0?e[a-n]:0,o=e[a]-i;r+=Math.abs(o)}return r}function l(e,t,n,r,i,a){for(let o=0;o<n;o++){let s=o>=a?e[t+o-a]:0,c=t>0?e[t+o-n]:0,l=e[t+o]-(s+c>>1);r[i+o]=l}}function u(e,t,n,r){let i=0;for(let a=0;a<n;a++){let o=a>=r?e[t+a-r]:0,s=t>0?e[t+a-n]:0,c=e[t+a]-(o+s>>1);i+=Math.abs(c)}return i}function d(e,t,r,i,a,o){for(let s=0;s<r;s++){let c=s>=o?e[t+s-o]:0,l=t>0?e[t+s-r]:0,u=t>0&&s>=o?e[t+s-(r+o)]:0,d=e[t+s]-n(c,l,u);i[a+s]=d}}function f(e,t,r,i){let a=0;for(let o=0;o<r;o++){let s=o>=i?e[t+o-i]:0,c=t>0?e[t+o-r]:0,l=t>0&&o>=i?e[t+o-(r+i)]:0,u=e[t+o]-n(s,c,l);a+=Math.abs(u)}return a}let p={0:r,1:a,2:s,3:l,4:d},m={0:i,1:o,2:c,3:u,4:f};t.exports=function(e,t,n,r,i){let a;if(!(`filterType`in r)||r.filterType===-1)a=[0,1,2,3,4];else if(typeof r.filterType==`number`)a=[r.filterType];else throw Error(`unrecognised filter types`);r.bitDepth===16&&(i*=2);let o=t*i,s=0,c=0,l=Buffer.alloc((o+1)*n),u=a[0];for(let t=0;t<n;t++){if(a.length>1){let t=1/0;for(let n=0;n<a.length;n++){let r=m[a[n]](e,c,o,i);r<t&&(u=a[n],t=r)}}l[s]=u,s++,p[u](e,c,o,l,s,i),s+=o,c+=o}return l}})),Tt=C(((e,t)=>{let n=_t(),r=vt(),i=Ct(),a=wt(),o=w(`zlib`),s=t.exports=function(e){if(this._options=e,e.deflateChunkSize=e.deflateChunkSize||32768,e.deflateLevel=e.deflateLevel==null?9:e.deflateLevel,e.deflateStrategy=e.deflateStrategy==null?3:e.deflateStrategy,e.inputHasAlpha=e.inputHasAlpha==null||e.inputHasAlpha,e.deflateFactory=e.deflateFactory||o.createDeflate,e.bitDepth=e.bitDepth||8,e.colorType=typeof e.colorType==`number`?e.colorType:n.COLORTYPE_COLOR_ALPHA,e.inputColorType=typeof e.inputColorType==`number`?e.inputColorType:n.COLORTYPE_COLOR_ALPHA,[n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.colorType)===-1)throw Error(`option color type:`+e.colorType+` is not supported at present`);if([n.COLORTYPE_GRAYSCALE,n.COLORTYPE_COLOR,n.COLORTYPE_COLOR_ALPHA,n.COLORTYPE_ALPHA].indexOf(e.inputColorType)===-1)throw Error(`option input color type:`+e.inputColorType+` is not supported at present`);if(e.bitDepth!==8&&e.bitDepth!==16)throw Error(`option bit depth:`+e.bitDepth+` is not supported at present`)};s.prototype.getDeflateOptions=function(){return{chunkSize:this._options.deflateChunkSize,level:this._options.deflateLevel,strategy:this._options.deflateStrategy}},s.prototype.createDeflate=function(){return this._options.deflateFactory(this.getDeflateOptions())},s.prototype.filterData=function(e,t,r){let o=i(e,t,r,this._options),s=n.COLORTYPE_TO_BPP_MAP[this._options.colorType];return a(o,t,r,this._options,s)},s.prototype._packChunk=function(e,t){let n=t?t.length:0,i=Buffer.alloc(n+12);return i.writeUInt32BE(n,0),i.writeUInt32BE(e,4),t&&t.copy(i,8),i.writeInt32BE(r.crc32(i.slice(4,i.length-4)),i.length-4),i},s.prototype.packGAMA=function(e){let t=Buffer.alloc(4);return t.writeUInt32BE(Math.floor(e*n.GAMMA_DIVISION),0),this._packChunk(n.TYPE_gAMA,t)},s.prototype.packIHDR=function(e,t){let r=Buffer.alloc(13);return r.writeUInt32BE(e,0),r.writeUInt32BE(t,4),r[8]=this._options.bitDepth,r[9]=this._options.colorType,r[10]=0,r[11]=0,r[12]=0,this._packChunk(n.TYPE_IHDR,r)},s.prototype.packIDAT=function(e){return this._packChunk(n.TYPE_IDAT,e)},s.prototype.packIEND=function(){return this._packChunk(n.TYPE_IEND,null)}})),Et=C(((e,t)=>{let n=w(`util`),r=w(`stream`),i=_t(),a=Tt(),o=t.exports=function(e){r.call(this);let t=e||{};this._packer=new a(t),this._deflate=this._packer.createDeflate(),this.readable=!0};n.inherits(o,r),o.prototype.pack=function(e,t,n,r){this.emit(`data`,Buffer.from(i.PNG_SIGNATURE)),this.emit(`data`,this._packer.packIHDR(t,n)),r&&this.emit(`data`,this._packer.packGAMA(r));let a=this._packer.filterData(e,t,n);this._deflate.on(`error`,this.emit.bind(this,`error`)),this._deflate.on(`data`,function(e){this.emit(`data`,this._packer.packIDAT(e))}.bind(this)),this._deflate.on(`end`,function(){this.emit(`data`,this._packer.packIEND()),this.emit(`end`)}.bind(this)),this._deflate.end(a)}})),Dt=C(((e,t)=>{let n=w(`assert`).ok,r=w(`zlib`),i=w(`util`),a=w(`buffer`).kMaxLength;function o(e){if(!(this instanceof o))return new o(e);e&&e.chunkSize<r.Z_MIN_CHUNK&&(e.chunkSize=r.Z_MIN_CHUNK),r.Inflate.call(this,e),this._offset=this._offset===void 0?this._outOffset:this._offset,this._buffer=this._buffer||this._outBuffer,e&&e.maxLength!=null&&(this._maxLength=e.maxLength)}function s(e){return new o(e)}function c(e,t){t&&process.nextTick(t),e._handle&&=(e._handle.close(),null)}o.prototype._processChunk=function(e,t,i){if(typeof i==`function`)return r.Inflate._processChunk.call(this,e,t,i);let o=this,s=e&&e.length,l=this._chunkSize-this._offset,u=this._maxLength,d=0,f=[],p=0,m;this.on(`error`,function(e){m=e});function h(e,t){if(o._hadError)return;let r=l-t;if(n(r>=0,`have should not go down`),r>0){let e=o._buffer.slice(o._offset,o._offset+r);if(o._offset+=r,e.length>u&&(e=e.slice(0,u)),f.push(e),p+=e.length,u-=e.length,u===0)return!1}return(t===0||o._offset>=o._chunkSize)&&(l=o._chunkSize,o._offset=0,o._buffer=Buffer.allocUnsafe(o._chunkSize)),t===0&&(d+=s-e,s=e,!0)}n(this._handle,`zlib binding closed`);let g;do g=this._handle.writeSync(t,e,d,s,this._buffer,this._offset,l),g||=this._writeState;while(!this._hadError&&h(g[0],g[1]));if(this._hadError)throw m;if(p>=a)throw c(this),RangeError(`Cannot create final Buffer. It would be larger than 0x`+a.toString(16)+` bytes`);let _=Buffer.concat(f,p);return c(this),_},i.inherits(o,r.Inflate);function l(e,t){if(typeof t==`string`&&(t=Buffer.from(t)),!(t instanceof Buffer))throw TypeError(`Not a string or buffer`);let n=e._finishFlushFlag;return n??=r.Z_FINISH,e._processChunk(t,n)}function u(e,t){return l(new o(t),e)}t.exports=e=u,e.Inflate=o,e.createInflate=s,e.inflateSync=u})),Ot=C(((e,t)=>{let n=t.exports=function(e){this._buffer=e,this._reads=[]};n.prototype.read=function(e,t){this._reads.push({length:Math.abs(e),allowLess:e<0,func:t})},n.prototype.process=function(){for(;this._reads.length>0&&this._buffer.length;){let e=this._reads[0];if(this._buffer.length&&(this._buffer.length>=e.length||e.allowLess)){this._reads.shift();let t=this._buffer;this._buffer=t.slice(e.length),e.func.call(this,t.slice(0,e.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`)}})),kt=C((e=>{let t=Ot(),n=ht();e.process=function(e,r){let i=[],a=new t(e);return new n(r,{read:a.read.bind(a),write:function(e){i.push(e)},complete:function(){}}).start(),a.process(),Buffer.concat(i)}})),At=C(((e,t)=>{let n=!0,r=w(`zlib`),i=Dt();r.deflateSync||(n=!1);let a=Ot(),o=kt(),s=yt(),c=bt(),l=xt();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let u;function d(e){u=e}let f;function p(e){f=e}function m(e){f.transColor=e}function h(e){f.palette=e}function g(){f.alpha=!0}let _;function ee(e){_=e}let v=[];function y(e){v.push(e)}let te=new a(e);if(new s(t,{read:te.read.bind(te),error:d,metadata:p,gamma:ee,palette:h,transColor:m,inflateData:y,simpleTransparency:g}).start(),te.process(),u)throw u;let b=Buffer.concat(v);v.length=0;let x;if(f.interlace)x=r.inflateSync(b);else{let e=((f.width*f.bpp*f.depth+7>>3)+1)*f.height;x=i(b,{chunkSize:e,maxLength:e})}if(b=null,!x||!x.length)throw Error(`bad png - invalid inflate data response`);let ne=o.process(x,f);b=null;let re=c.dataToBitMap(ne,f);ne=null;let ie=l(re,f,t.skipRescale);return f.data=ie,f.gamma=_||0,f}})),jt=C(((e,t)=>{let n=!0,r=w(`zlib`);r.deflateSync||(n=!1);let i=_t(),a=Tt();t.exports=function(e,t){if(!n)throw Error(`To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0`);let o=new a(t||{}),s=[];s.push(Buffer.from(i.PNG_SIGNATURE)),s.push(o.packIHDR(e.width,e.height)),e.gamma&&s.push(o.packGAMA(e.gamma));let c=o.filterData(e.data,e.width,e.height),l=r.deflateSync(c,o.getDeflateOptions());if(c=null,!l||!l.length)throw Error(`bad png - invalid compressed data response`);return s.push(o.packIDAT(l)),s.push(o.packIEND()),Buffer.concat(s)}})),Mt=C((e=>{let t=At(),n=jt();e.read=function(e,n){return t(e,n||{})},e.write=function(e,t){return n(e,t)}})),Nt=C((e=>{let t=w(`util`),n=w(`stream`),r=St(),i=Et(),a=Mt(),o=e.PNG=function(e){n.call(this),e||={},this.width=e.width|0,this.height=e.height|0,this.data=this.width>0&&this.height>0?Buffer.alloc(4*this.width*this.height):null,e.fill&&this.data&&this.data.fill(0),this.gamma=0,this.readable=this.writable=!0,this._parser=new r(e),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(e){this.data=e,this.emit(`parsed`,e)}.bind(this)),this._packer=new i(e),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`))};t.inherits(o,n),o.sync=a,o.prototype.pack=function(){return!this.data||!this.data.length?(this.emit(`error`,`No data provided`),this):(process.nextTick(function(){this._packer.pack(this.data,this.width,this.height,this.gamma)}.bind(this)),this)},o.prototype.parse=function(e,t){if(t){let e,n;e=function(e){this.removeListener(`error`,n),this.data=e,t(null,this)}.bind(this),n=function(n){this.removeListener(`parsed`,e),t(n,null)}.bind(this),this.once(`parsed`,e),this.once(`error`,n)}return this.end(e),this},o.prototype.write=function(e){return this._parser.write(e),!0},o.prototype.end=function(e){this._parser.end(e)},o.prototype._metadata=function(e){this.width=e.width,this.height=e.height,this.emit(`metadata`,e)},o.prototype._gamma=function(e){this.gamma=e},o.prototype._handleClose=function(){!this._parser.writable&&!this._packer.readable&&this.emit(`close`)},o.bitblt=function(e,t,n,r,i,a,o,s){if(n|=0,r|=0,i|=0,a|=0,o|=0,s|=0,n>e.width||r>e.height||n+i>e.width||r+a>e.height)throw Error(`bitblt reading outside image`);if(o>t.width||s>t.height||o+i>t.width||s+a>t.height)throw Error(`bitblt writing outside image`);for(let c=0;c<a;c++)e.data.copy(t.data,(s+c)*t.width+o<<2,(r+c)*e.width+n<<2,(r+c)*e.width+n+i<<2)},o.prototype.bitblt=function(e,t,n,r,i,a,s){return o.bitblt(this,e,t,n,r,i,a,s),this},o.adjustGamma=function(e){if(e.gamma){for(let t=0;t<e.height;t++)for(let n=0;n<e.width;n++){let r=e.width*t+n<<2;for(let t=0;t<3;t++){let n=e.data[r+t]/255;n**=1/2.2/e.gamma,e.data[r+t]=Math.round(n*255)}}e.gamma=0}},o.prototype.adjustGamma=function(){o.adjustGamma(this)}}));function D(e,t,n){function r(n,r){if(n._zod||Object.defineProperty(n,"_zod",{value:{def:r,constr:o,traits:new Set},enumerable:!1}),n._zod.traits.has(e))return;n._zod.traits.add(e),t(n,r);let i=o.prototype,a=Object.keys(i);for(let e=0;e<a.length;e++){let t=a[e];t in n||(n[t]=i[t].bind(n))}}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}function Pt(e){return e&&Object.assign(Lt,e),Lt}var Ft,It,Lt,Rt=S((()=>{Object.freeze({status:`aborted`}),Ft=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},It=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}},Lt={}}));function zt(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Bt(e,t){return typeof t==`bigint`?t.toString():t}function Vt(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Ht(e){return e==null}function Ut(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Wt(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=t.toString(),i=(r.split(`.`)[1]||``).length;if(i===0&&/\d?e-\d?/.test(r)){let e=r.match(/\d?e-(\d?)/);e?.[1]&&(i=Number.parseInt(e[1]))}let a=n>i?n:i;return Number.parseInt(e.toFixed(a).replace(`.`,``))%Number.parseInt(t.toFixed(a).replace(`.`,``))/10**a}function O(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==hn)return r===void 0&&(r=hn,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Gt(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Kt(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function qt(e){return JSON.stringify(e)}function Jt(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}function Yt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xt(e){if(Yt(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Yt(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Zt(e){return Xt(e)?{...e}:Array.isArray(e)?[...e]:e}function Qt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function $t(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function k(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function en(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function tn(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return $t(e,Kt(e._zod.def,{get shape(){let e={};for(let r in t){if(!(r in n.shape))throw Error(`Unrecognized key: "${r}"`);t[r]&&(e[r]=n.shape[r])}return Gt(this,`shape`,e),e},checks:[]}))}function nn(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return $t(e,Kt(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e in t){if(!(e in n.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete r[e]}return Gt(this,`shape`,r),r},checks:[]}))}function rn(e,t){if(!Xt(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e in t)if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Gt(this,`shape`,n),n}}))}function an(e,t){if(!Xt(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Gt(this,`shape`,n),n}}))}function on(e,t){return $t(e,Kt(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Gt(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:[]}))}function sn(e,t,n){let r=t._zod.def.checks;if(r&&r.length>0)throw Error(`.partial() cannot be used on object schemas containing refinements`);return $t(t,Kt(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Gt(this,`shape`,i),i},checks:[]}))}function cn(e,t,n){return $t(t,Kt(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return Gt(this,`shape`,i),i}}))}function ln(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function un(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function dn(e){return typeof e==`string`?e:e?.message}function fn(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=dn(e.inst?._zod.def?.error?.(e))??dn(t?.error?.(e))??dn(n.customError?.(e))??dn(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function pn(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function mn(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var hn,gn,_n,vn,yn,bn=S((()=>{hn=Symbol(`evaluating`),gn=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{},_n=Vt(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}}),vn=new Set([`string`,`number`,`symbol`]),yn={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}}));function xn(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Sn(e,t=e=>e.message){let n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`&&i.errors.length)i.errors.map(e=>r({issues:e}));else if(i.code===`invalid_key`)r({issues:i.issues});else if(i.code===`invalid_element`)r({issues:i.issues});else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(e),n}var Cn,wn,Tn,En=S((()=>{Rt(),bn(),Cn=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),e.message=JSON.stringify(t,Bt,2),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},wn=D(`$ZodError`,Cn),Tn=D(`$ZodError`,Cn,{Parent:Error})})),Dn,On,kn,An,jn,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn=S((()=>{Rt(),En(),bn(),Dn=e=>(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new Ft;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>fn(e,a,Pt())));throw gn(t,i?.callee),t}return o.value},On=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>fn(e,a,Pt())));throw gn(t,i?.callee),t}return o.value},kn=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ft;return a.issues.length?{success:!1,error:new(e??wn)(a.issues.map(e=>fn(e,i,Pt())))}:{success:!0,data:a.value}},An=kn(Tn),jn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>fn(e,i,Pt())))}:{success:!0,data:a.value}},Mn=jn(Tn),Nn=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return Dn(e)(t,n,i)},Pn=e=>(t,n,r)=>Dn(e)(t,n,r),Fn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return On(e)(t,n,i)},In=e=>async(t,n,r)=>On(e)(t,n,r),Ln=e=>(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return kn(e)(t,n,i)},Rn=e=>(t,n,r)=>kn(e)(t,n,r),zn=e=>async(t,n,r)=>{let i=r?Object.assign(r,{direction:`backward`}):{direction:`backward`};return jn(e)(t,n,i)},Bn=e=>async(t,n,r)=>jn(e)(t,n,r)}));function Hn(){return new RegExp(nr,`u`)}function Un(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Wn(e){return RegExp(`^${Un(e)}$`)}function Gn(e){let t=Un({precision:e.precision}),n=[`Z`];e.local&&n.push(``),e.offset&&n.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let r=`${t}(?:${n.join(`|`)})`;return RegExp(`^${ur}T(?:${r})$`)}var Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r,vr=S((()=>{Kn=/^[cC][^\s-]{8,}$/,qn=/^[0-9a-z]+$/,Jn=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Yn=/^[0-9a-vA-V]{20}$/,Xn=/^[A-Za-z0-9]{27}$/,Zn=/^[a-zA-Z0-9_-]{21}$/,Qn=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,$n=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,er=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,tr=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,nr=`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,rr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ir=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ar=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,or=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,sr=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cr=/^[A-Za-z0-9_-]*$/,lr=/^\+[1-9]\d{6,14}$/,ur=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`,dr=RegExp(`^${ur}$`),fr=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},pr=/^-?\d+$/,mr=/^-?\d+(?:\.\d+)?$/,hr=/^(?:true|false)$/i,gr=/^[^A-Z]*$/,_r=/^[^a-z]*$/})),A,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or,kr,Ar,jr,Mr,Nr,Pr,Fr=S((()=>{Rt(),vr(),bn(),A=D(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),yr={number:`number`,bigint:`bigint`,object:`date`},br=D(`$ZodCheckLessThan`,(e,t)=>{A.init(e,t);let n=yr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),xr=D(`$ZodCheckGreaterThan`,(e,t)=>{A.init(e,t);let n=yr[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Sr=D(`$ZodCheckMultipleOf`,(e,t)=>{A.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?n.value%t.value===BigInt(0):Wt(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Cr=D(`$ZodCheckNumberFormat`,(e,t)=>{A.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=yn[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=pr)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),wr=D(`$ZodCheckMaxLength`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value;if(r.length<=t.maximum)return;let i=pn(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Tr=D(`$ZodCheckMinLength`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=pn(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Er=D(`$ZodCheckLengthEquals`,(e,t)=>{var n;A.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!Ht(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=pn(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Dr=D(`$ZodCheckStringFormat`,(e,t)=>{var n,r;A.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Or=D(`$ZodCheckRegex`,(e,t)=>{Dr.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),kr=D(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=gr,Dr.init(e,t)}),Ar=D(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=_r,Dr.init(e,t)}),jr=D(`$ZodCheckIncludes`,(e,t)=>{A.init(e,t);let n=Qt(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position}}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Mr=D(`$ZodCheckStartsWith`,(e,t)=>{A.init(e,t);let n=RegExp(`^${Qt(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Nr=D(`$ZodCheckEndsWith`,(e,t)=>{A.init(e,t);let n=RegExp(`.*${Qt(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Pr=D(`$ZodCheckOverwrite`,(e,t)=>{A.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}})})),Ir,Lr=S((()=>{Ir=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
7
7
  `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(`
8
8
  `))}}})),Rr,zr=S((()=>{Rr={major:4,minor:3,patch:6}}));function Br(e){if(e===``)return!0;if(e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}function Vr(e){if(!cr.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Br(t.padEnd(Math.ceil(t.length/4)*4,`=`))}function Hr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}function Ur(e,t,n){e.issues.length&&t.issues.push(...un(n,e.issues)),t.value[n]=e.value}function Wr(e,t,n,r,i){if(e.issues.length){if(i&&!(n in r))return;t.issues.push(...un(n,e.issues))}e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}function Gr(e){let t=Object.keys(e.shape);for(let n of t)if(!e.shape?.[n]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=en(e.shape);return{...e,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Kr(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optout===`optional`;for(let i in t){if(s.has(i))continue;if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Wr(e,n,i,t,u))):Wr(a,n,i,t,u)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a}),e.length?Promise.all(e).then(()=>n):n}function qr(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ln(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>fn(e,r,Pt())))}),t)}function Jr(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Xt(e)&&Xt(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Jr(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Jr(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Yr(e,t,n){let r=new Map,i;for(let n of t.issues)if(n.code===`unrecognized_keys`){i??=n;for(let e of n.keys)r.has(e)||r.set(e,{}),r.get(e).l=!0}else e.issues.push(n);for(let t of n.issues)if(t.code===`unrecognized_keys`)for(let e of t.keys)r.has(e)||r.set(e,{}),r.get(e).r=!0;else e.issues.push(t);let a=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(a.length&&i&&e.issues.push({...i,keys:a}),ln(e))return e;let o=Jr(t.value,n.value);if(!o.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}function Xr(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}function Zr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}function Qr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function $r(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}function ei(e){return e.value=Object.freeze(e.value),e}function ti(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(mn(e))}}var j,ni,M,ri,ii,ai,oi,si,ci,li,ui,di,fi,pi,mi,hi,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi=S((()=>{Fr(),Rt(),Lr(),Vn(),vr(),bn(),zr(),j=D(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Rr;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=ln(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new Ft;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=ln(e,t))});else{if(e.issues.length===t)continue;r||=ln(e,t)}}return i?i.then(()=>e):e},n=(n,i,a)=>{if(ln(n))return n.aborted=!0,n;let o=t(i,r,a);if(o instanceof Promise){if(a.async===!1)throw new Ft;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(i,a)=>{if(a.skipChecks)return e._zod.parse(i,a);if(a.direction===`backward`){let t=e._zod.parse({value:i.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,i,a)):n(t,i,a)}let o=e._zod.parse(i,a);if(o instanceof Promise){if(a.async===!1)throw new Ft;return o.then(e=>t(e,r,a))}return t(o,r,a)}}O(e,`~standard`,()=>({validate:t=>{try{let n=An(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return Mn(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}))}),ni=D(`$ZodString`,(e,t)=>{j.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??fr(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),M=D(`$ZodStringFormat`,(e,t)=>{Dr.init(e,t),ni.init(e,t)}),ri=D(`$ZodGUID`,(e,t)=>{t.pattern??=$n,M.init(e,t)}),ii=D(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=er(e)}else t.pattern??=er();M.init(e,t)}),ai=D(`$ZodEmail`,(e,t)=>{t.pattern??=tr,M.init(e,t)}),oi=D(`$ZodURL`,(e,t)=>{M.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=new URL(r);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(`:`)?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort})),n.value=t.normalize?i.href:r;return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),si=D(`$ZodEmoji`,(e,t)=>{t.pattern??=Hn(),M.init(e,t)}),ci=D(`$ZodNanoID`,(e,t)=>{t.pattern??=Zn,M.init(e,t)}),li=D(`$ZodCUID`,(e,t)=>{t.pattern??=Kn,M.init(e,t)}),ui=D(`$ZodCUID2`,(e,t)=>{t.pattern??=qn,M.init(e,t)}),di=D(`$ZodULID`,(e,t)=>{t.pattern??=Jn,M.init(e,t)}),fi=D(`$ZodXID`,(e,t)=>{t.pattern??=Yn,M.init(e,t)}),pi=D(`$ZodKSUID`,(e,t)=>{t.pattern??=Xn,M.init(e,t)}),mi=D(`$ZodISODateTime`,(e,t)=>{t.pattern??=Gn(t),M.init(e,t)}),hi=D(`$ZodISODate`,(e,t)=>{t.pattern??=dr,M.init(e,t)}),gi=D(`$ZodISOTime`,(e,t)=>{t.pattern??=Wn(t),M.init(e,t)}),_i=D(`$ZodISODuration`,(e,t)=>{t.pattern??=Qn,M.init(e,t)}),vi=D(`$ZodIPv4`,(e,t)=>{t.pattern??=rr,M.init(e,t),e._zod.bag.format=`ipv4`}),yi=D(`$ZodIPv6`,(e,t)=>{t.pattern??=ir,M.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}}),bi=D(`$ZodCIDRv4`,(e,t)=>{t.pattern??=ar,M.init(e,t)}),xi=D(`$ZodCIDRv6`,(e,t)=>{t.pattern??=or,M.init(e,t),e._zod.check=n=>{let r=n.value.split(`/`);try{if(r.length!==2)throw Error();let[e,t]=r;if(!t)throw Error();let n=Number(t);if(`${n}`!==t||n<0||n>128)throw Error();new URL(`http://[${e}]`)}catch{n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}}}),Si=D(`$ZodBase64`,(e,t)=>{t.pattern??=sr,M.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Br(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Ci=D(`$ZodBase64URL`,(e,t)=>{t.pattern??=cr,M.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Vr(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),wi=D(`$ZodE164`,(e,t)=>{t.pattern??=lr,M.init(e,t)}),Ti=D(`$ZodJWT`,(e,t)=>{M.init(e,t),e._zod.check=n=>{Hr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Ei=D(`$ZodNumber`,(e,t)=>{j.init(e,t),e._zod.pattern=e._zod.bag.pattern??mr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:`Infinity`:void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Di=D(`$ZodNumberFormat`,(e,t)=>{Cr.init(e,t),Ei.init(e,t)}),Oi=D(`$ZodBoolean`,(e,t)=>{j.init(e,t),e._zod.pattern=hr,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ki=D(`$ZodUnknown`,(e,t)=>{j.init(e,t),e._zod.parse=e=>e}),Ai=D(`$ZodNever`,(e,t)=>{j.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)}),ji=D(`$ZodArray`,(e,t)=>{j.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;e<i.length;e++){let o=i[e],s=t.element._zod.run({value:o,issues:[]},r);s instanceof Promise?a.push(s.then(t=>Ur(t,n,e))):Ur(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}}),Mi=D(`$ZodObject`,(e,t)=>{if(j.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),n}})}let n=Vt(()=>Gr(t));O(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=Yt,i=t.catchall,a;e._zod.parse=(t,o)=>{a??=n.value;let s=t.value;if(!r(s))return t.issues.push({expected:`object`,code:`invalid_type`,input:s,inst:e}),t;t.value={};let c=[],l=a.shape;for(let e of a.keys){let n=l[e],r=n._zod.optout===`optional`,i=n._zod.run({value:s[e],issues:[]},o);i instanceof Promise?c.push(i.then(n=>Wr(n,t,e,s,r))):Wr(i,t,e,s,r)}return i?Kr(c,s,t,o,n.value,e):c.length?Promise.all(c).then(()=>t):t}}),Ni=D(`$ZodObjectJIT`,(e,t)=>{Mi.init(e,t);let n=e._zod.parse,r=Vt(()=>Gr(t)),i=e=>{let t=new Ir([`shape`,`payload`,`ctx`]),n=r.value,i=e=>{let t=qt(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of n.keys)a[e]=`key_${o++}`;t.write(`const newResult = {};`);for(let r of n.keys){let n=a[r],o=qt(r),s=e[r]?._zod?.optout===`optional`;t.write(`const ${n} = ${i(r)};`),s?t.write(`
9
9
  if (${n}.issues.length) {
@@ -294,7 +294,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
294
294
  }
295
295
  }
296
296
  return { ignoredRegions };
297
- })()`)}async function jc(e,t,n,r,i){let[o,s]=await Promise.all([x(e),x(t)]),c=Bu.PNG.sync.read(o),l=Bu.PNG.sync.read(s),u=Math.max(c.width,l.width),d=Math.max(c.height,l.height),f=Nc(c,u,d),p=Nc(l,u,d),m=Mc(f,p,i?.base??[],i?.head??[]),h=new Bu.PNG({width:u,height:d}),g=it(f.data,p.data,h.data,u,d,{threshold:r,includeAA:!1}),_=u*d-m;return await y(a(n),{recursive:!0}),await se(n,Bu.PNG.sync.write(h)),{changedPixels:g,totalPixels:_,diffRatio:_===0?0:g/_}}function Mc(e,t,n,r){if(n.length===0||r.length===0)return 0;let{width:i,height:a}=e,o=new Uint8Array(i*a);for(let e of n)for(let t of r){let n=Math.max(0,e.x,t.x),r=Math.max(0,e.y,t.y),s=Math.min(i,e.x+e.width,t.x+t.width),c=Math.min(a,e.y+e.height,t.y+t.height);if(!(s<=n||c<=r))for(let e=r;e<c;e+=1)o.fill(1,e*i+n,e*i+s)}let s=0;for(let n=0;n<o.length;n+=1){if(o[n]===0)continue;s+=1;let r=n*4;e.data.fill(0,r,r+4),t.data.fill(0,r,r+4)}return s}function Nc(e,t,n){if(e.width===t&&e.height===n)return e;let r=new Bu.PNG({width:t,height:n}),i=e.width*4;for(let n=0;n<e.height;n+=1){let a=n*i;r.data.set(e.data.subarray(a,a+i),n*t*4)}return r}function Pc(e){return m(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,16)}function Fc(e){let t=[...e.allowedDomains??[`127.0.0.1`,`localhost`]].sort(),n=process.versions.bun,r={browser:`chromium`,browserVersion:e.browserVersion,orchestratorRuntime:e.orchestratorRuntime??(n?`bun ${n}`:`node ${process.version}`),operatingSystem:`${le()}-${ue()}`,architecture:ce(),deviceScaleFactor:e.deviceScaleFactor??1,locale:Ic(e.locale??`en-US`),timezone:Lc(e.timezone??`UTC`),colorScheme:e.colorScheme??`light`,reducedMotion:e.reducedMotion??`reduce`,frozenTime:e.frozenTime??`2026-01-01T00:00:00.000Z`,randomSeed:e.randomSeed??20260101,fontsFingerprint:e.fontsFingerprint??`storybook-bundled-fonts-v1`,stateIsolation:`fresh-browser-process-per-story-side-v1`,network:{mode:`allowlist`,allowedDomains:t,webRtc:`disabled`}};return{id:Pc(r),...r}}function Ic(e){if(!e.trim())throw Error(`Kapture locale must not be empty`);try{let[t]=Intl.getCanonicalLocales(e);if(!t)throw Error(`missing canonical locale`);return t}catch(t){throw Error(`Kapture locale must be a valid BCP 47 tag: ${e}`,{cause:t})}}function Lc(e){if(!e.trim())throw Error(`Kapture timezone must not be empty`);try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}).resolvedOptions().timeZone}catch(t){throw Error(`Kapture timezone must be a valid IANA time zone: ${e}`,{cause:t})}}function Rc(e,t){if(e.id!==t.id||JSON.stringify(e)!==JSON.stringify(t))throw Error(`Kapture environment mismatch: base=${e.id}, head=${t.id}. Base and head must be captured with the exact same environment contract.`)}async function zc(){try{let e=(await Bc()).split(`
297
+ })()`)}async function jc(e,t,n,r,i){let[o,s]=await Promise.all([x(e),x(t)]),c=Bu.PNG.sync.read(o),l=Bu.PNG.sync.read(s),u=Math.max(c.width,l.width),d=Math.max(c.height,l.height),f=Nc(c,u,d),p=Nc(l,u,d),m=Mc(f,p,i?.base??[],i?.head??[]),h=new Bu.PNG({width:u,height:d}),g=it(f.data,p.data,h.data,u,d,{threshold:r,includeAA:!1,diffColor:[255,0,0],aaColor:[255,255,0]}),_=u*d-m.pixels;return await y(a(n),{recursive:!0}),await se(n,Bu.PNG.sync.write(h)),{changedPixels:g,totalPixels:_,diffRatio:_===0?0:g/_,ignoredRegions:m.regions}}function Mc(e,t,n,r){if(n.length===0||r.length===0)return{pixels:0,regions:[]};let{width:i,height:a}=e,o=new Uint8Array(i*a),s=new Map;for(let e of n)for(let t of r){let n=Math.max(0,e.x,t.x),r=Math.max(0,e.y,t.y),c=Math.min(i,e.x+e.width,t.x+t.width),l=Math.min(a,e.y+e.height,t.y+t.height);if(c<=n||l<=r)continue;let u={x:n,y:r,width:c-n,height:l-r};if(s.set(`${n}:${r}:${c}:${l}`,u),s.size>1e4)throw Error(`Too many ignored region intersections`);for(let e=r;e<l;e+=1)o.fill(1,e*i+n,e*i+c)}let c=0;for(let n=0;n<o.length;n+=1){if(o[n]===0)continue;c+=1;let r=n*4;e.data.fill(0,r,r+4),t.data.fill(0,r,r+4)}return{pixels:c,regions:[...s.values()]}}function Nc(e,t,n){if(e.width===t&&e.height===n)return e;let r=new Bu.PNG({width:t,height:n}),i=e.width*4;for(let n=0;n<e.height;n+=1){let a=n*i;r.data.set(e.data.subarray(a,a+i),n*t*4)}return r}function Pc(e){return m(`sha256`).update(JSON.stringify(e)).digest(`hex`).slice(0,16)}function Fc(e){let t=[...e.allowedDomains??[`127.0.0.1`,`localhost`]].sort(),n=process.versions.bun,r={browser:`chromium`,browserVersion:e.browserVersion,orchestratorRuntime:e.orchestratorRuntime??(n?`bun ${n}`:`node ${process.version}`),operatingSystem:`${le()}-${ue()}`,architecture:ce(),deviceScaleFactor:e.deviceScaleFactor??1,locale:Ic(e.locale??`en-US`),timezone:Lc(e.timezone??`UTC`),colorScheme:e.colorScheme??`light`,reducedMotion:e.reducedMotion??`reduce`,frozenTime:e.frozenTime??`2026-01-01T00:00:00.000Z`,randomSeed:e.randomSeed??20260101,fontsFingerprint:e.fontsFingerprint??`storybook-bundled-fonts-v1`,stateIsolation:`fresh-browser-process-per-story-side-v1`,network:{mode:`allowlist`,allowedDomains:t,webRtc:`disabled`}};return{id:Pc(r),...r}}function Ic(e){if(!e.trim())throw Error(`Kapture locale must not be empty`);try{let[t]=Intl.getCanonicalLocales(e);if(!t)throw Error(`missing canonical locale`);return t}catch(t){throw Error(`Kapture locale must be a valid BCP 47 tag: ${e}`,{cause:t})}}function Lc(e){if(!e.trim())throw Error(`Kapture timezone must not be empty`);try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e}).resolvedOptions().timeZone}catch(t){throw Error(`Kapture timezone must be a valid IANA time zone: ${e}`,{cause:t})}}function Rc(e,t){if(e.id!==t.id||JSON.stringify(e)!==JSON.stringify(t))throw Error(`Kapture environment mismatch: base=${e.id}, head=${t.id}. Base and head must be captured with the exact same environment contract.`)}async function zc(){try{let e=(await Bc()).split(`
298
298
  `).filter(Boolean).sort().join(`
299
299
  `);return`fontconfig:${m(`sha256`).update(e).digest(`hex`)}`}catch{return`fontconfig-unavailable:${le()}-${ue()}`}}function Bc(){return new Promise((e,t)=>{let n=r(`fc-list`,[`--format`,`%{file}|%{family}|%{style}\\n`],{stdio:[`ignore`,`pipe`,`ignore`]}),i=[];n.stdout.on(`data`,e=>i.push(e)),n.once(`error`,t),n.once(`close`,n=>{if(n!==0)return t(Error(`fc-list failed (${n})`));e(Buffer.concat(i).toString(`utf8`))})})}function Vc(e){let t=Date.parse(e.frozenTime);if(!Number.isFinite(t))throw Error(`Invalid frozenTime: ${e.frozenTime}`);return`(() => {
300
300
  const NativeDate = globalThis.Date;
@@ -322,7 +322,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
322
322
  configurable: false,
323
323
  writable: false,
324
324
  });
325
- })();`}function Hc(e){let t=new Set;for(let n of Object.values(e.entries)){for(let e of Ku){let r=n[e];r&&t.add(r)}for(let e of[n.instability?.base,n.instability?.head])e?.repeatImage&&t.add(e.repeatImage),e?.diffImage&&t.add(e.diffImage)}return[...t].sort(Jc)}function Uc(e){return Kc({report:Gc(e)})}function Wc(e,t){let n=Hc(e),r=new Set(n),i=new Map;for(let e of t){if(!e.path||!qu.test(e.sha256))throw Error(`Invalid report image digest for ${e.path||`<empty path>`}`);if(i.has(e.path))throw Error(`Duplicate report image digest for ${e.path}`);i.set(e.path,e.sha256)}for(let e of n)if(!i.has(e))throw Error(`Missing report image digest for ${e}`);for(let e of i.keys())if(!r.has(e))throw Error(`Unexpected report image digest for ${e}`);return Kc({report:Gc(e),images:n.map(e=>({path:e,sha256:i.get(e)}))})}function Gc(e){let{contentDigest:t,...n}=e;return n}function Kc(e){return m(`sha256`).update(JSON.stringify(qc(e))).digest(`hex`)}function qc(e){return Array.isArray(e)?e.map(qc):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>Jc(e,t)).map(([e,t])=>[e,qc(t)]))}function Jc(e,t){return e<t?-1:+(e>t)}async function Yc(e){let t=await x(e);return m(`sha256`).update(t).digest(`hex`)}function Xc(e){let t=m(`sha256`).update(e).digest(`hex`).slice(0,12);return`${e.replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120)||`snapshot`}-${t}.png`}async function Zc(e){let{baseManifest:t,headManifest:n,baseRoot:r,headRoot:i,outputDir:a,threshold:o,coverage:s,stability:l}=e;Rc(t.environment,n.environment),await ae(c(a,`images`),{recursive:!0,force:!0}),await y(c(a,`images`),{recursive:!0});let u=s?new Set(s.selectedStoryIds):void 0,d=[...new Set([...Object.keys(t.snapshots),...Object.keys(n.snapshots)])].filter(e=>{if(!u)return!0;let r=n.snapshots[e]??t.snapshots[e];return r?u.has(r.storyId):!1}).sort(),f={};for(let e of d){let s=t.snapshots[e],c=n.snapshots[e];f[e]=await Qc({id:e,base:s,head:c,baseRoot:r,headRoot:i,outputDir:a,threshold:o,stability:l&&s&&c?{base:l.baseManifest.snapshots[e],head:l.headManifest.snapshots[e],baseRoot:l.baseRoot,headRoot:l.headRoot}:void 0})}let p=Object.values(f),m={version:3,baseRevision:t.revision,headRevision:n.revision,environment:t.environment,createdAt:new Date().toISOString(),threshold:o,summary:{total:p.length,unchanged:p.filter(e=>e.status===`unchanged`).length,changed:p.filter(e=>e.status===`changed`).length,unstable:p.filter(e=>e.status===`unstable`).length,added:p.filter(e=>e.status===`added`).length,removed:p.filter(e=>e.status===`removed`).length,errors:p.filter(e=>e.status===`error`).length},...s?{coverage:s}:{},entries:f},h=[];for(let e of Hc(m))h.push({path:e,sha256:await Yc(c(a,e))});return m.contentDigest=Wc(m,h),await se(c(a,`report.json`),`${JSON.stringify(m,null,2)}\n`),m}async function Qc(e){let{id:t,base:n,head:r,baseRoot:a,headRoot:o,outputDir:s,threshold:l,stability:u}=e,d=r??n;if(!d)throw Error(`Snapshot ${t} has no base or head record`);let f={id:t,storyId:d.storyId,title:d.title,name:d.name,viewport:d.viewport},p={...l,...r?.threshold??n?.threshold};if(n?.error||r?.error)return{...f,status:`error`,threshold:p,error:[n?.error,r?.error].filter(Boolean).join(` | `)};if(!n&&r)return{...f,status:`added`,threshold:p,headImage:await el(`head`,r,o,s)};if(n&&!r)return{...f,status:`removed`,threshold:p,baseImage:await el(`base`,n,a,s)};if(!n||!r)throw Error(`Invalid manifest pair for ${t}`);if(n.viewport.width!==r.viewport.width||n.viewport.height!==r.viewport.height)return{...f,status:`error`,threshold:p,error:`Viewport contract differs: base=${n.viewport.width}x${n.viewport.height}, head=${r.viewport.width}x${r.viewport.height}`};if(n.sha256===r.sha256)return{...f,status:`unchanged`,threshold:p};let m=`images/diff/${i(n.imageFile)}`;try{let e=await jc(c(a,n.imageFile),c(o,r.imageFile),c(s,m),p.pixelColorThreshold,{base:n.ignoredRegions??[],head:r.ignoredRegions??[]});if(e.diffRatio<=p.maxChangedPixelRatio)return await ae(c(s,m),{force:!0}),{...f,status:`unchanged`,threshold:p,changedPixels:e.changedPixels,diffRatio:e.diffRatio};let[i,l]=await Promise.all([el(`base`,n,a,s),el(`head`,r,o,s)]),d=u?await $c({id:t,base:n,head:r,baseRepeat:u.base,headRepeat:u.head,baseRoot:a,headRoot:o,baseRepeatRoot:u.baseRoot,headRepeatRoot:u.headRoot,outputDir:s,threshold:p}):void 0;return{...f,status:d?`unstable`:`changed`,threshold:p,baseImage:i,headImage:l,diffImage:m,changedPixels:e.changedPixels,diffRatio:e.diffRatio,...d?{instability:d}:{}}}catch(e){return{...f,status:`error`,threshold:p,error:e instanceof Error?e.message:String(e)}}}async function $c(e){let t={};for(let n of[`base`,`head`]){let r=e[n],a=n===`base`?e.baseRepeat:e.headRepeat;if(!a)throw Error(`Kapture ${n} stability recapture is missing for ${e.id}`);if(a.error)throw Error(`Kapture ${n} stability recapture failed: ${a.error}`);if(r.sha256===a.sha256)continue;let o=n===`base`?e.baseRepeatRoot:e.headRepeatRoot,s=n===`base`?e.baseRoot:e.headRoot,l=`images/${n}-instability-diff/${i(r.imageFile)}`,u=await jc(c(s,r.imageFile),c(o,a.imageFile),c(e.outputDir,l),e.threshold.pixelColorThreshold,{base:r.ignoredRegions??[],head:a.ignoredRegions??[]});if(u.diffRatio<=e.threshold.maxChangedPixelRatio){await ae(c(e.outputDir,l),{force:!0});continue}t[n]={repeatImage:await el(`${n}-repeat`,a,o,e.outputDir),diffImage:l,changedPixels:u.changedPixels,diffRatio:u.diffRatio}}return t.base||t.head?t:void 0}async function el(e,t,n,r){let a=`images/${e}/${i(t.imageFile)}`;return await y(c(r,`images`,e),{recursive:!0}),await _(c(n,t.imageFile),c(r,a)),a}async function tl(e){let t=await re(f(e)),n=fe(async(e,n)=>{try{let r=decodeURIComponent(new URL(e.url??`/`,`http://localhost`).pathname),i=f(t,`.${r}`);if(!nl(t,i)){n.writeHead(403).end(`Forbidden`);return}let a=await re(i);if(!nl(t,a)){n.writeHead(403).end(`Forbidden`);return}if((await oe(a)).isDirectory()&&(a=await re(f(a,`index.html`)),!nl(t,a))){n.writeHead(403).end(`Forbidden`);return}let s=await x(a);n.writeHead(200,{"cache-control":`no-store`,"content-type":Ju[o(a)]??`application/octet-stream`}),n.end(s)}catch{n.writeHead(404).end(`Not found`)}});await rl(n);let r=n.address();if(!r||typeof r==`string`)throw Error(`Static server has no TCP address`);return{url:`http://127.0.0.1:${r.port}/`,close:()=>il(n)}}function nl(e,t){return t===e||t.startsWith(`${e}${p}`)}function rl(e){return new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{e.off(`error`,n),t()})})}function il(e){return new Promise((t,n)=>{e.close(e=>e?n(e):t())})}async function al(e,t){await y(a(e),{recursive:!0}),await se(e,`${JSON.stringify(t,null,2)}\n`)}async function ol(e){return Qu.parse(JSON.parse(await x(e,`utf8`)))}function sl(e){return ud.parse(e)}async function cl(e){let t=c(e,$u),n;try{n=await x(t)}catch(e){return _l(e)?{evidence:{state:`missing`}}:{evidence:{state:`invalid`}}}try{let t=await ll(e,sl(JSON.parse(n.toString(`utf8`))));return{manifest:t,evidence:{state:`valid`,digest:fl(t)}}}catch{return{evidence:{state:`invalid`,digest:hl(n)}}}}async function ll(e,t){let n=!0;for(let[r,i]of Object.entries(t.outputInventory))try{let t=c(e,r),a=await v(t);if(!a.isFile()||a.isSymbolicLink()){n=!1;break}let o=await x(t);if(o.byteLength!==i.size||hl(o)!==i.sha256){n=!1;break}}catch{n=!1;break}if(n)for(let r of t.outputInventoryPrefixes){let i=await ul(e,r),a=Object.keys(t.outputInventory).filter(e=>e.startsWith(r)).sort();if(!i||!dl(i,a)){n=!1;break}}return n?t:ud.parse({...t,complete:!1,diagnostics:[...new Set([...t.diagnostics,`output-inventory-mismatch`])].sort()})}async function ul(e,t){let n=[],r=[t===``?``:t.slice(0,-1)];try{for(;r.length>0;){let t=r.pop(),i=await ne(c(e,t),{withFileTypes:!0});for(let e of i){let i=t?`${t}/${e.name}`:e.name;if(e.isSymbolicLink())return null;if(e.isDirectory())r.push(i);else if(e.isFile())i!==`kapture-dependencies.json`&&n.push(i);else return null;if(n.length+r.length>1e5)return null}}}catch{return null}return n.sort()}function dl(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function fl(e){return hl(JSON.stringify(gl(e)))}function pl(e,t){return{base:e?{state:`valid`,digest:fl(e)}:{state:`missing`},head:t?{state:`valid`,digest:fl(t)}:{state:`missing`}}}function ml(e){return e!==``&&!e.includes(`\\`)&&!e.includes(`\0`)&&!e.startsWith(`/`)&&!/^[A-Za-z]:\//.test(e)&&e!==`.`&&e!==`..`&&!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.split(`/`).some(e=>e===`.`||e===`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function hl(e){return m(`sha256`).update(e).digest(`hex`)}function gl(e){return Array.isArray(e)?e.map(gl):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,gl(t)]))}function _l(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function vl({baseDir:e,headDir:t,changedFiles:n,changedFilesComplete:r=!0,changedFilesEvidence:i}){let[a,o,s,c]=await Promise.all([bl(e),bl(t),Nl(e,`base`),Nl(t,`head`)]);return yl({baseIndex:a,headIndex:o,baseManifest:s.manifest,headManifest:c.manifest,changedFiles:n,changedFilesComplete:r,changedFilesEvidence:i,dependencyManifests:{base:s.evidence,head:c.evidence},initialFallbackReasons:[...s.reason?[s.reason]:[],...c.reason?[c.reason]:[]]})}function yl(e){let t=jl(e.changedFiles.map(wl)),n=xl(e.baseIndex),r=xl(e.headIndex),i=jl([...n.keys(),...r.keys()]),a=[...r.keys()].filter(e=>!n.has(e)).sort(),o=[...n.keys()].filter(e=>!r.has(e)).sort(),s=[...e.initialFallbackReasons??[],...e.changedFilesComplete===!1?[{code:`changed-files-incomplete`}]:[]],{baseManifest:c,headManifest:l}=e,u=e.dependencyManifests??pl(c,l),d=new Set,f=new Set;!c&&!s.some(e=>e.code.startsWith(`base-manifest`))&&s.push({code:`base-manifest-missing`,side:`base`}),!l&&!s.some(e=>e.code.startsWith(`head-manifest`))&&s.push({code:`head-manifest-missing`,side:`head`}),c&&!c.complete&&s.push({code:`manifest-incomplete`,side:`base`}),l&&!l.complete&&s.push({code:`manifest-incomplete`,side:`head`});let p=new Map;if(c&&l){c.globalRuntimeFingerprint!==l.globalRuntimeFingerprint&&s.push({code:`global-runtime`});for(let e of new Set([...Object.keys(c.globalOutputFingerprints),...Object.keys(l.globalOutputFingerprints)]))(c.globalOutputFingerprints[e]!==l.globalOutputFingerprints[e]||!Al(new Set(c.globalOutputStories[e]??[]),new Set(l.globalOutputStories[e]??[])))&&f.add(e);for(let e of new Set([...Object.keys(c.renderedOutputFingerprints),...Object.keys(l.renderedOutputFingerprints)]))c.renderedOutputFingerprints[e]!==l.renderedOutputFingerprints[e]&&d.add(e);if(c.moduleFingerprints&&l.moduleFingerprints)for(let e of new Set([...Object.keys(c.moduleFingerprints),...Object.keys(l.moduleFingerprints)]))c.moduleFingerprints[e]!==l.moduleFingerprints[e]&&d.add(e);for(let e of i){let t=n.get(e),i=r.get(e),a=t?Sl(t,c,`base`,s):void 0,o=i?Sl(i,l,`head`,s):void 0;p.set(e,{base:a,head:o})}let e=new Set,a=new Set;for(let t of[c,l])for(let[n,r]of Object.entries(t.modules)){e.add(n);for(let t of r)e.add(t)}for(let e of p.values()){if(e.base)for(let t of Dl(c,e.base))a.add(t);if(e.head)for(let t of Dl(l,e.head))a.add(t)}for(let e of f){let t=Ol(c,l,e);if(!t||[...t].some(e=>!a.has(e))){s.push({code:`global-output`,path:e});continue}for(let e of t)d.add(e)}for(let e of d)(Tl(e,c.globalInputs)||Tl(e,l.globalInputs))&&s.push({code:`global-input`,path:e});for(let n of t){if(Tl(n,c.globalInputs)||Tl(n,l.globalInputs)){s.push({code:`global-input`,path:n});continue}let t=Tl(n,c.ignoredInputs)&&Tl(n,l.ignoredInputs),r=El(c)&&El(l)&&Tl(n,c.fingerprintedInputs??[])&&Tl(n,l.fingerprintedInputs??[]);!t&&!r&&(!e.has(n)||!a.has(n))&&s.push({code:`unknown-input`,path:n})}}let m=Ml(s);if(m.length>0||!c||!l)return{version:1,selectionMode:`full-fallback`,changedFiles:t,...e.changedFilesEvidence?{changedFilesEvidence:{...e.changedFilesEvidence}}:{},dependencyManifests:Il(u),totalStoryIds:i,selectedStoryIds:i,skippedStoryIds:[],addedStoryIds:a,removedStoryIds:o,fallbackReasons:m};let h=new Set([...a,...o]);for(let e of i){let n=p.get(e);if(!n)continue;if(n.base!==n.head){h.add(e);continue}let r=n.base?Dl(c,n.base):new Set,i=n.head?Dl(l,n.head):new Set;if(!Al(r,i)){h.add(e);continue}let a=new Set([...r,...i]);(t.some(e=>a.has(e))||[...a].some(e=>d.has(e)))&&h.add(e)}let g=[...h].sort();return{version:1,selectionMode:`affected`,changedFiles:t,...e.changedFilesEvidence?{changedFilesEvidence:{...e.changedFilesEvidence}}:{},dependencyManifests:Il(u),totalStoryIds:i,selectedStoryIds:g,skippedStoryIds:i.filter(e=>!h.has(e)),addedStoryIds:a,removedStoryIds:o,fallbackReasons:[]}}async function bl(e){return pd.parse(JSON.parse(await x(c(e,`index.json`),`utf8`)))}function xl(e){return new Map(Object.values(e.entries).filter(e=>e.type===`story`).sort((e,t)=>e.id.localeCompare(t.id)).map(e=>[e.id,e]))}function Sl(e,t,n,r){if(!e.importPath){r.push({code:`story-import-missing`,storyId:e.id,side:n});return}let i;try{i=Cl(t.storybookRoot,e.importPath)}catch{r.push({code:`story-import-missing`,storyId:e.id,side:n});return}if(!t.modules[i]){r.push({code:`story-module-missing`,storyId:e.id,side:n});return}if(t.renderedModules&&!t.renderedModules[i]?.includes(i)){r.push({code:`story-module-missing`,storyId:e.id,side:n});return}return i}function Cl(e,t){let n=t.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(s(n)||/^[A-Za-z]:\//.test(n))throw Error(`Story importPath must be relative`);let r=u.normalize(u.join(e,n));if(r===`..`||r.startsWith(`../`)||r===`.`)throw Error(`Story importPath must stay within project root`);return r}function wl(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(t.length===0||t.includes(`\0`)||s(t)||/^[A-Za-z]:\//.test(t)||t===`..`||t.startsWith(`../`)||t.split(`/`).some(e=>e===`.`||e===`..`)||t.includes(`//`)||t.endsWith(`/`))throw Error(`Changed file must be a normalized project-relative path: ${e}`);return t}function Tl(e,t){return t.some(t=>e===t||l(e,t))}function El(e){return!e.complete||!e.moduleFingerprints?!1:Object.keys(e.modules).every(t=>e.moduleFingerprints?.[t]!==void 0)}function Dl(e,t){let n=kl(e,t),r=e.renderedModules?.[t];return r?new Set(r):n}function Ol(e,t,n){let r=e.globalOutputFingerprints[n]!==void 0,i=t.globalOutputFingerprints[n]!==void 0;if(r&&i&&e.globalOutputFingerprints[n]!==t.globalOutputFingerprints[n])return null;let a=new Set(e.globalOutputStories[n]??[]),o=new Set(t.globalOutputStories[n]??[]);if(r&&a.size===0||i&&o.size===0)return null;let s=new Set([...a,...o]);return s.size>0?s:null}function kl(e,t){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!(!t||n.has(t))){n.add(t);for(let i of e.modules[t]??[])n.has(i)||r.push(i)}}return n}function Al(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function jl(e){return[...new Set(e)].sort()}function Ml(e){let t=new Map;for(let n of e)t.set(Fl(n),n);let n=[...t.values()].sort(Pl);return n.length<=1e3?n:[...n.filter(e=>e.code!==`fallback-reasons-truncated`).slice(0,999),{code:`fallback-reasons-truncated`}].sort(Pl)}async function Nl(e,t){let n=await cl(e);if(n.manifest)return n;let r=`${t}-manifest-${n.evidence.state}`;return{evidence:n.evidence,reason:{code:r,side:t}}}function Pl(e,t){return Fl(e).localeCompare(Fl(t))}function Fl(e){return`${e.code}:${e.side??``}:${e.path??``}:${e.storyId??``}`}function Il(e){return{base:{...e.base},head:{...e.head}}}async function Ll(e){let t=await fetch(new URL(`index.json`,Bl(e)));if(!t.ok)throw Error(`Failed to read Storybook index (${t.status}) from ${e}`);return hd.parse(await t.json())}function Rl(e){return Object.values(e.entries).filter(e=>e.type===`story`).sort((e,t)=>e.id.localeCompare(t.id))}function zl(e,t){let n=new URL(`iframe.html`,Bl(e));return n.searchParams.set(`id`,t),n.searchParams.set(`viewMode`,`story`),n.toString()}function Bl(e){return e.endsWith(`/`)?e:`${e}/`}function Vl(e){let t=Zl(e,`bridge`);if(t.protocolVersion!==4)throw Error(`Unsupported Kapture Storybook protocol ${String(t.protocolVersion)}; expected 4`);let n=$l(t.adapterVersion,`adapterVersion`),r=t.state;if(r===`booting`)return{protocolVersion:4,adapterVersion:n,state:r};if(![`rendering`,`ready`,`error`].includes(r))throw Error(`Invalid Kapture Storybook bridge state: ${String(r)}`);let i=$l(t.storyId,`storyId`),a=ou(t.generation,`generation`),o=nu(t.renderId,`renderId`);if(r===`rendering`)return{protocolVersion:4,adapterVersion:n,state:r,storyId:i,generation:a,renderId:o,parameters:t.parameters===void 0?void 0:Hl(t.parameters)};if(r===`ready`){if(o===void 0)throw Error(`Kapture ready bridge requires renderId`);return{protocolVersion:4,adapterVersion:n,state:r,storyId:i,generation:a,renderId:o,parameters:Hl(t.parameters)}}let s=Zl(t.error,`error`);if(s.kind!==`configuration`&&s.kind!==`storybook`)throw Error(`Invalid Kapture bridge error kind: ${String(s.kind)}`);return{protocolVersion:4,adapterVersion:n,state:`error`,storyId:i,generation:a,renderId:o,error:{kind:s.kind,message:$l(s.message,`error.message`)}}}function Hl(e){let t=Zl(e,`parameters`);return lu({captureEnabled:tu(t.captureEnabled,`captureEnabled`),captureViewports:Ul(t.captureViewports),captureArea:Wl(t.captureArea),captureDelayMs:iu(t.captureDelayMs,`captureDelayMs`),waitForElement:Kl(t.waitForElement),animationState:ql(t.animationState),maskSelectors:Xl(t.maskSelectors,`maskSelectors`),diffIgnoreSelectors:Xl(t.diffIgnoreSelectors,`diffIgnoreSelectors`),waitForFonts:tu(t.waitForFonts,`waitForFonts`),fontAssertions:t.fontAssertions===void 0?void 0:Ql(t.fontAssertions,`fontAssertions`).map((e,t)=>Jl(e,`fontAssertions[${t}]`)),diff:Yl(t.diff)})}function Ul(e){if(e===void 0)return;let t=Ql(e,`captureViewports`);if(t.length===0)throw Error(`Kapture captureViewports must contain at least one viewport; use captureEnabled: false to skip`);return t.map((e,t)=>Gl(e,`captureViewports[${t}]`))}function Wl(e){if(e===void 0||e===`full-page`||e===`viewport`)return e;throw Error(`Invalid Kapture captureArea: ${String(e)}`)}function Gl(e,t){let n=Zl(e,t);return{name:$l(n.name,`${t}.name`),width:au(n.width,`${t}.width`),height:au(n.height,`${t}.height`)}}function Kl(e){if(e===void 0)return;let t=Zl(e,`waitForElement`),n=t.state;if(n!==void 0&&n!==`attached`&&n!==`visible`&&n!==`hidden`&&n!==`detached`)throw Error(`Invalid Kapture waitForElement state: ${String(n)}`);return lu({selector:$l(t.selector,`waitForElement.selector`),state:n,timeoutMs:iu(t.timeoutMs,`waitForElement.timeoutMs`)})}function ql(e){if(e!==void 0)return e===`disabled`||e===`start`||e===`end`?e:{atMs:ru(Zl(e,`animationState`).atMs,`animationState.atMs`)}}function Jl(e,t){let n=Zl(e,t),r=n.weight;if(r!==void 0&&typeof r!=`string`&&typeof r!=`number`)throw Error(`${t}.weight must be a string or number`);return lu({family:$l(n.family,`${t}.family`),glyphs:$l(n.glyphs,`${t}.glyphs`),style:eu(n.style,`${t}.style`),weight:r})}function Yl(e){if(e===void 0)return;let t=Zl(e,`diff`);if(`maxChangedPixelRatio`in t)throw Error(`Kapture diff.maxChangedPixelRatio is not supported; use diff.maxChangedPixelPercentage with a value between 0 and 100`);return lu({pixelColorThreshold:su(t.pixelColorThreshold,`diff.pixelColorThreshold`),maxChangedPixelPercentage:cu(t.maxChangedPixelPercentage,`diff.maxChangedPixelPercentage`)})}function Xl(e,t){if(e!==void 0)return Ql(e,t).map((e,n)=>$l(e,`${t}[${n}]`))}function Zl(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Kapture ${t} must be an object`);return e}function Ql(e,t){if(!Array.isArray(e))throw Error(`Kapture ${t} must be an array`);return e}function $l(e,t){if(typeof e!=`string`||!e.trim())throw Error(`Kapture ${t} must be a non-empty string`);return e}function eu(e,t){return e===void 0?void 0:$l(e,t)}function tu(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Kapture ${t} must be a boolean`);return e}}function nu(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isFinite(e))throw Error(`Kapture ${t} must be a finite number`);return e}}function ru(e,t){let n=nu(e,t);if(n===void 0||n<0)throw Error(`Kapture ${t} must be a non-negative number`);return n}function iu(e,t){return e===void 0?void 0:ru(e,t)}function au(e,t){let n=nu(e,t);if(n===void 0||n<=0)throw Error(`Kapture ${t} must be positive`);return n}function ou(e,t){let n=ru(e,t);if(!Number.isInteger(n))throw Error(`Kapture ${t} must be an integer`);return n}function su(e,t){if(e===void 0)return;let n=ru(e,t);if(n>1)throw Error(`Kapture ${t} must be between 0 and 1`);return n}function cu(e,t){if(e===void 0)return;let n=ru(e,t);if(n>100)throw Error(`Kapture ${t} must be between 0 and 100`);return n}function lu(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function uu(e,t,n){let r=JSON.stringify(t),i=await e.evaluate(`(async () => {
325
+ })();`}function Hc(e){let t=new Set;for(let n of Object.values(e.entries)){for(let e of Ku){let r=n[e];r&&t.add(r)}for(let e of[n.instability?.base,n.instability?.head])e?.repeatImage&&t.add(e.repeatImage),e?.diffImage&&t.add(e.diffImage)}return[...t].sort(Jc)}function Uc(e){return Kc({report:Gc(e)})}function Wc(e,t){let n=Hc(e),r=new Set(n),i=new Map;for(let e of t){if(!e.path||!qu.test(e.sha256))throw Error(`Invalid report image digest for ${e.path||`<empty path>`}`);if(i.has(e.path))throw Error(`Duplicate report image digest for ${e.path}`);i.set(e.path,e.sha256)}for(let e of n)if(!i.has(e))throw Error(`Missing report image digest for ${e}`);for(let e of i.keys())if(!r.has(e))throw Error(`Unexpected report image digest for ${e}`);return Kc({report:Gc(e),images:n.map(e=>({path:e,sha256:i.get(e)}))})}function Gc(e){let{contentDigest:t,...n}=e;return n}function Kc(e){return m(`sha256`).update(JSON.stringify(qc(e))).digest(`hex`)}function qc(e){return Array.isArray(e)?e.map(qc):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>Jc(e,t)).map(([e,t])=>[e,qc(t)]))}function Jc(e,t){return e<t?-1:+(e>t)}async function Yc(e){let t=await x(e);return m(`sha256`).update(t).digest(`hex`)}function Xc(e){let t=m(`sha256`).update(e).digest(`hex`).slice(0,12);return`${e.replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,120)||`snapshot`}-${t}.png`}async function Zc(e){let{baseManifest:t,headManifest:n,baseRoot:r,headRoot:i,outputDir:a,threshold:o,coverage:s,stability:l}=e;Rc(t.environment,n.environment),await ae(c(a,`images`),{recursive:!0,force:!0}),await y(c(a,`images`),{recursive:!0});let u=s?new Set(s.selectedStoryIds):void 0,d=[...new Set([...Object.keys(t.snapshots),...Object.keys(n.snapshots)])].filter(e=>{if(!u)return!0;let r=n.snapshots[e]??t.snapshots[e];return r?u.has(r.storyId):!1}).sort(),f={};for(let e of d){let s=t.snapshots[e],c=n.snapshots[e];f[e]=await Qc({id:e,base:s,head:c,baseRoot:r,headRoot:i,outputDir:a,threshold:o,stability:l&&s&&c?{base:l.baseManifest.snapshots[e],head:l.headManifest.snapshots[e],baseRoot:l.baseRoot,headRoot:l.headRoot}:void 0})}let p=Object.values(f),m={version:3,baseRevision:t.revision,headRevision:n.revision,environment:t.environment,createdAt:new Date().toISOString(),threshold:o,summary:{total:p.length,unchanged:p.filter(e=>e.status===`unchanged`).length,changed:p.filter(e=>e.status===`changed`).length,unstable:p.filter(e=>e.status===`unstable`).length,added:p.filter(e=>e.status===`added`).length,removed:p.filter(e=>e.status===`removed`).length,errors:p.filter(e=>e.status===`error`).length},...s?{coverage:s}:{},entries:f},h=[];for(let e of Hc(m))h.push({path:e,sha256:await Yc(c(a,e))});return m.contentDigest=Wc(m,h),await se(c(a,`report.json`),`${JSON.stringify(m,null,2)}\n`),m}async function Qc(e){let{id:t,base:n,head:r,baseRoot:a,headRoot:o,outputDir:s,threshold:l,stability:u}=e,d=r??n;if(!d)throw Error(`Snapshot ${t} has no base or head record`);let f={id:t,storyId:d.storyId,title:d.title,name:d.name,viewport:d.viewport},p={...l,...r?.threshold??n?.threshold};if(n?.error||r?.error)return{...f,status:`error`,threshold:p,error:[n?.error,r?.error].filter(Boolean).join(` | `)};if(!n&&r)return{...f,status:`added`,threshold:p,headImage:await el(`head`,r,o,s)};if(n&&!r)return{...f,status:`removed`,threshold:p,baseImage:await el(`base`,n,a,s)};if(!n||!r)throw Error(`Invalid manifest pair for ${t}`);if(n.viewport.width!==r.viewport.width||n.viewport.height!==r.viewport.height)return{...f,status:`error`,threshold:p,error:`Viewport contract differs: base=${n.viewport.width}x${n.viewport.height}, head=${r.viewport.width}x${r.viewport.height}`};if(n.sha256===r.sha256)return{...f,status:`unchanged`,threshold:p};let m=`images/diff/${i(n.imageFile)}`;try{let e=await jc(c(a,n.imageFile),c(o,r.imageFile),c(s,m),p.pixelColorThreshold,{base:n.ignoredRegions??[],head:r.ignoredRegions??[]});if(e.diffRatio<=p.maxChangedPixelRatio)return await ae(c(s,m),{force:!0}),{...f,status:`unchanged`,threshold:p,changedPixels:e.changedPixels,diffRatio:e.diffRatio};let[i,l]=await Promise.all([el(`base`,n,a,s),el(`head`,r,o,s)]),d=u?await $c({id:t,base:n,head:r,baseRepeat:u.base,headRepeat:u.head,baseRoot:a,headRoot:o,baseRepeatRoot:u.baseRoot,headRepeatRoot:u.headRoot,outputDir:s,threshold:p}):void 0;return{...f,status:d?`unstable`:`changed`,threshold:p,baseImage:i,headImage:l,diffImage:m,changedPixels:e.changedPixels,diffRatio:e.diffRatio,ignoredRegions:e.ignoredRegions,...d?{instability:d}:{}}}catch(e){return{...f,status:`error`,threshold:p,error:e instanceof Error?e.message:String(e)}}}async function $c(e){let t={};for(let n of[`base`,`head`]){let r=e[n],a=n===`base`?e.baseRepeat:e.headRepeat;if(!a)throw Error(`Kapture ${n} stability recapture is missing for ${e.id}`);if(a.error)throw Error(`Kapture ${n} stability recapture failed: ${a.error}`);if(r.sha256===a.sha256)continue;let o=n===`base`?e.baseRepeatRoot:e.headRepeatRoot,s=n===`base`?e.baseRoot:e.headRoot,l=`images/${n}-instability-diff/${i(r.imageFile)}`,u=await jc(c(s,r.imageFile),c(o,a.imageFile),c(e.outputDir,l),e.threshold.pixelColorThreshold,{base:r.ignoredRegions??[],head:a.ignoredRegions??[]});if(u.diffRatio<=e.threshold.maxChangedPixelRatio){await ae(c(e.outputDir,l),{force:!0});continue}t[n]={repeatImage:await el(`${n}-repeat`,a,o,e.outputDir),diffImage:l,changedPixels:u.changedPixels,diffRatio:u.diffRatio}}return t.base||t.head?t:void 0}async function el(e,t,n,r){let a=`images/${e}/${i(t.imageFile)}`;return await y(c(r,`images`,e),{recursive:!0}),await _(c(n,t.imageFile),c(r,a)),a}async function tl(e){let t=await re(f(e)),n=fe(async(e,n)=>{try{let r=decodeURIComponent(new URL(e.url??`/`,`http://localhost`).pathname),i=f(t,`.${r}`);if(!nl(t,i)){n.writeHead(403).end(`Forbidden`);return}let a=await re(i);if(!nl(t,a)){n.writeHead(403).end(`Forbidden`);return}if((await oe(a)).isDirectory()&&(a=await re(f(a,`index.html`)),!nl(t,a))){n.writeHead(403).end(`Forbidden`);return}let s=await x(a);n.writeHead(200,{"cache-control":`no-store`,"content-type":Ju[o(a)]??`application/octet-stream`}),n.end(s)}catch{n.writeHead(404).end(`Not found`)}});await rl(n);let r=n.address();if(!r||typeof r==`string`)throw Error(`Static server has no TCP address`);return{url:`http://127.0.0.1:${r.port}/`,close:()=>il(n)}}function nl(e,t){return t===e||t.startsWith(`${e}${p}`)}function rl(e){return new Promise((t,n)=>{e.once(`error`,n),e.listen(0,`127.0.0.1`,()=>{e.off(`error`,n),t()})})}function il(e){return new Promise((t,n)=>{e.close(e=>e?n(e):t())})}async function al(e,t){await y(a(e),{recursive:!0}),await se(e,`${JSON.stringify(t,null,2)}\n`)}async function ol(e){return Qu.parse(JSON.parse(await x(e,`utf8`)))}function sl(e){return ud.parse(e)}async function cl(e){let t=c(e,$u),n;try{n=await x(t)}catch(e){return _l(e)?{evidence:{state:`missing`}}:{evidence:{state:`invalid`}}}try{let t=await ll(e,sl(JSON.parse(n.toString(`utf8`))));return{manifest:t,evidence:{state:`valid`,digest:fl(t)}}}catch{return{evidence:{state:`invalid`,digest:hl(n)}}}}async function ll(e,t){let n=!0;for(let[r,i]of Object.entries(t.outputInventory))try{let t=c(e,r),a=await v(t);if(!a.isFile()||a.isSymbolicLink()){n=!1;break}let o=await x(t);if(o.byteLength!==i.size||hl(o)!==i.sha256){n=!1;break}}catch{n=!1;break}if(n)for(let r of t.outputInventoryPrefixes){let i=await ul(e,r),a=Object.keys(t.outputInventory).filter(e=>e.startsWith(r)).sort();if(!i||!dl(i,a)){n=!1;break}}return n?t:ud.parse({...t,complete:!1,diagnostics:[...new Set([...t.diagnostics,`output-inventory-mismatch`])].sort()})}async function ul(e,t){let n=[],r=[t===``?``:t.slice(0,-1)];try{for(;r.length>0;){let t=r.pop(),i=await ne(c(e,t),{withFileTypes:!0});for(let e of i){let i=t?`${t}/${e.name}`:e.name;if(e.isSymbolicLink())return null;if(e.isDirectory())r.push(i);else if(e.isFile())i!==`kapture-dependencies.json`&&n.push(i);else return null;if(n.length+r.length>1e5)return null}}}catch{return null}return n.sort()}function dl(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function fl(e){return hl(JSON.stringify(gl(e)))}function pl(e,t){return{base:e?{state:`valid`,digest:fl(e)}:{state:`missing`},head:t?{state:`valid`,digest:fl(t)}:{state:`missing`}}}function ml(e){return e!==``&&!e.includes(`\\`)&&!e.includes(`\0`)&&!e.startsWith(`/`)&&!/^[A-Za-z]:\//.test(e)&&e!==`.`&&e!==`..`&&!e.startsWith(`./`)&&!e.startsWith(`../`)&&!e.split(`/`).some(e=>e===`.`||e===`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function hl(e){return m(`sha256`).update(e).digest(`hex`)}function gl(e){return Array.isArray(e)?e.map(gl):!e||typeof e!=`object`?e:Object.fromEntries(Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,gl(t)]))}function _l(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}async function vl({baseDir:e,headDir:t,changedFiles:n,changedFilesComplete:r=!0,changedFilesEvidence:i}){let[a,o,s,c]=await Promise.all([bl(e),bl(t),Nl(e,`base`),Nl(t,`head`)]);return yl({baseIndex:a,headIndex:o,baseManifest:s.manifest,headManifest:c.manifest,changedFiles:n,changedFilesComplete:r,changedFilesEvidence:i,dependencyManifests:{base:s.evidence,head:c.evidence},initialFallbackReasons:[...s.reason?[s.reason]:[],...c.reason?[c.reason]:[]]})}function yl(e){let t=jl(e.changedFiles.map(wl)),n=xl(e.baseIndex),r=xl(e.headIndex),i=jl([...n.keys(),...r.keys()]),a=[...r.keys()].filter(e=>!n.has(e)).sort(),o=[...n.keys()].filter(e=>!r.has(e)).sort(),s=[...e.initialFallbackReasons??[],...e.changedFilesComplete===!1?[{code:`changed-files-incomplete`}]:[]],{baseManifest:c,headManifest:l}=e,u=e.dependencyManifests??pl(c,l),d=new Set,f=new Set;!c&&!s.some(e=>e.code.startsWith(`base-manifest`))&&s.push({code:`base-manifest-missing`,side:`base`}),!l&&!s.some(e=>e.code.startsWith(`head-manifest`))&&s.push({code:`head-manifest-missing`,side:`head`}),c&&!c.complete&&s.push({code:`manifest-incomplete`,side:`base`}),l&&!l.complete&&s.push({code:`manifest-incomplete`,side:`head`});let p=new Map;if(c&&l){c.globalRuntimeFingerprint!==l.globalRuntimeFingerprint&&s.push({code:`global-runtime`});for(let e of new Set([...Object.keys(c.globalOutputFingerprints),...Object.keys(l.globalOutputFingerprints)]))(c.globalOutputFingerprints[e]!==l.globalOutputFingerprints[e]||!Al(new Set(c.globalOutputStories[e]??[]),new Set(l.globalOutputStories[e]??[])))&&f.add(e);for(let e of new Set([...Object.keys(c.renderedOutputFingerprints),...Object.keys(l.renderedOutputFingerprints)]))c.renderedOutputFingerprints[e]!==l.renderedOutputFingerprints[e]&&d.add(e);if(c.moduleFingerprints&&l.moduleFingerprints)for(let e of new Set([...Object.keys(c.moduleFingerprints),...Object.keys(l.moduleFingerprints)]))c.moduleFingerprints[e]!==l.moduleFingerprints[e]&&d.add(e);for(let e of i){let t=n.get(e),i=r.get(e),a=t?Sl(t,c,`base`,s):void 0,o=i?Sl(i,l,`head`,s):void 0;p.set(e,{base:a,head:o})}let e=new Set,a=new Set;for(let t of[c,l])for(let[n,r]of Object.entries(t.modules)){e.add(n);for(let t of r)e.add(t)}for(let e of p.values()){if(e.base)for(let t of Dl(c,e.base))a.add(t);if(e.head)for(let t of Dl(l,e.head))a.add(t)}for(let e of f){let t=Ol(c,l,e);if(!t||[...t].some(e=>!a.has(e))){s.push({code:`global-output`,path:e});continue}for(let e of t)d.add(e)}for(let e of d)(Tl(e,c.globalInputs)||Tl(e,l.globalInputs))&&s.push({code:`global-input`,path:e});for(let n of t){if(Tl(n,c.globalInputs)||Tl(n,l.globalInputs)){s.push({code:`global-input`,path:n});continue}let t=Tl(n,c.ignoredInputs)&&Tl(n,l.ignoredInputs),r=El(c)&&El(l)&&Tl(n,c.fingerprintedInputs??[])&&Tl(n,l.fingerprintedInputs??[]);!t&&!r&&(!e.has(n)||!a.has(n))&&s.push({code:`unknown-input`,path:n})}}let m=Ml(s);if(m.length>0||!c||!l)return{version:1,selectionMode:`full-fallback`,changedFiles:t,...e.changedFilesEvidence?{changedFilesEvidence:{...e.changedFilesEvidence}}:{},dependencyManifests:Il(u),totalStoryIds:i,selectedStoryIds:i,skippedStoryIds:[],addedStoryIds:a,removedStoryIds:o,fallbackReasons:m};let h=new Set([...a,...o]);for(let e of i){let n=p.get(e);if(!n)continue;if(n.base!==n.head){h.add(e);continue}let r=n.base?Dl(c,n.base):new Set,i=n.head?Dl(l,n.head):new Set;if(!Al(r,i)){h.add(e);continue}let a=new Set([...r,...i]);(t.some(e=>a.has(e))||[...a].some(e=>d.has(e)))&&h.add(e)}let g=[...h].sort();return{version:1,selectionMode:`affected`,changedFiles:t,...e.changedFilesEvidence?{changedFilesEvidence:{...e.changedFilesEvidence}}:{},dependencyManifests:Il(u),totalStoryIds:i,selectedStoryIds:g,skippedStoryIds:i.filter(e=>!h.has(e)),addedStoryIds:a,removedStoryIds:o,fallbackReasons:[]}}async function bl(e){return pd.parse(JSON.parse(await x(c(e,`index.json`),`utf8`)))}function xl(e){return new Map(Object.values(e.entries).filter(e=>e.type===`story`).sort((e,t)=>e.id.localeCompare(t.id)).map(e=>[e.id,e]))}function Sl(e,t,n,r){if(!e.importPath){r.push({code:`story-import-missing`,storyId:e.id,side:n});return}let i;try{i=Cl(t.storybookRoot,e.importPath)}catch{r.push({code:`story-import-missing`,storyId:e.id,side:n});return}if(!t.modules[i]){r.push({code:`story-module-missing`,storyId:e.id,side:n});return}if(t.renderedModules&&!t.renderedModules[i]?.includes(i)){r.push({code:`story-module-missing`,storyId:e.id,side:n});return}return i}function Cl(e,t){let n=t.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(s(n)||/^[A-Za-z]:\//.test(n))throw Error(`Story importPath must be relative`);let r=u.normalize(u.join(e,n));if(r===`..`||r.startsWith(`../`)||r===`.`)throw Error(`Story importPath must stay within project root`);return r}function wl(e){let t=e.replaceAll(`\\`,`/`).replace(/^\.\//,``);if(t.length===0||t.includes(`\0`)||s(t)||/^[A-Za-z]:\//.test(t)||t===`..`||t.startsWith(`../`)||t.split(`/`).some(e=>e===`.`||e===`..`)||t.includes(`//`)||t.endsWith(`/`))throw Error(`Changed file must be a normalized project-relative path: ${e}`);return t}function Tl(e,t){return t.some(t=>e===t||l(e,t))}function El(e){return!e.complete||!e.moduleFingerprints?!1:Object.keys(e.modules).every(t=>e.moduleFingerprints?.[t]!==void 0)}function Dl(e,t){let n=kl(e,t),r=e.renderedModules?.[t];return r?new Set(r):n}function Ol(e,t,n){let r=e.globalOutputFingerprints[n]!==void 0,i=t.globalOutputFingerprints[n]!==void 0;if(r&&i&&e.globalOutputFingerprints[n]!==t.globalOutputFingerprints[n])return null;let a=new Set(e.globalOutputStories[n]??[]),o=new Set(t.globalOutputStories[n]??[]);if(r&&a.size===0||i&&o.size===0)return null;let s=new Set([...a,...o]);return s.size>0?s:null}function kl(e,t){let n=new Set,r=[t];for(;r.length>0;){let t=r.pop();if(!(!t||n.has(t))){n.add(t);for(let i of e.modules[t]??[])n.has(i)||r.push(i)}}return n}function Al(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function jl(e){return[...new Set(e)].sort()}function Ml(e){let t=new Map;for(let n of e)t.set(Fl(n),n);let n=[...t.values()].sort(Pl);return n.length<=1e3?n:[...n.filter(e=>e.code!==`fallback-reasons-truncated`).slice(0,999),{code:`fallback-reasons-truncated`}].sort(Pl)}async function Nl(e,t){let n=await cl(e);if(n.manifest)return n;let r=`${t}-manifest-${n.evidence.state}`;return{evidence:n.evidence,reason:{code:r,side:t}}}function Pl(e,t){return Fl(e).localeCompare(Fl(t))}function Fl(e){return`${e.code}:${e.side??``}:${e.path??``}:${e.storyId??``}`}function Il(e){return{base:{...e.base},head:{...e.head}}}async function Ll(e){let t=await fetch(new URL(`index.json`,Bl(e)));if(!t.ok)throw Error(`Failed to read Storybook index (${t.status}) from ${e}`);return hd.parse(await t.json())}function Rl(e){return Object.values(e.entries).filter(e=>e.type===`story`).sort((e,t)=>e.id.localeCompare(t.id))}function zl(e,t){let n=new URL(`iframe.html`,Bl(e));return n.searchParams.set(`id`,t),n.searchParams.set(`viewMode`,`story`),n.toString()}function Bl(e){return e.endsWith(`/`)?e:`${e}/`}function Vl(e){let t=Zl(e,`bridge`);if(t.protocolVersion!==4)throw Error(`Unsupported Kapture Storybook protocol ${String(t.protocolVersion)}; expected 4`);let n=$l(t.adapterVersion,`adapterVersion`),r=t.state;if(r===`booting`)return{protocolVersion:4,adapterVersion:n,state:r};if(![`rendering`,`ready`,`error`].includes(r))throw Error(`Invalid Kapture Storybook bridge state: ${String(r)}`);let i=$l(t.storyId,`storyId`),a=ou(t.generation,`generation`),o=nu(t.renderId,`renderId`);if(r===`rendering`)return{protocolVersion:4,adapterVersion:n,state:r,storyId:i,generation:a,renderId:o,parameters:t.parameters===void 0?void 0:Hl(t.parameters)};if(r===`ready`){if(o===void 0)throw Error(`Kapture ready bridge requires renderId`);return{protocolVersion:4,adapterVersion:n,state:r,storyId:i,generation:a,renderId:o,parameters:Hl(t.parameters)}}let s=Zl(t.error,`error`);if(s.kind!==`configuration`&&s.kind!==`storybook`)throw Error(`Invalid Kapture bridge error kind: ${String(s.kind)}`);return{protocolVersion:4,adapterVersion:n,state:`error`,storyId:i,generation:a,renderId:o,error:{kind:s.kind,message:$l(s.message,`error.message`)}}}function Hl(e){let t=Zl(e,`parameters`);return lu({captureEnabled:tu(t.captureEnabled,`captureEnabled`),captureViewports:Ul(t.captureViewports),captureArea:Wl(t.captureArea),captureDelayMs:iu(t.captureDelayMs,`captureDelayMs`),waitForElement:Kl(t.waitForElement),animationState:ql(t.animationState),maskSelectors:Xl(t.maskSelectors,`maskSelectors`),diffIgnoreSelectors:Xl(t.diffIgnoreSelectors,`diffIgnoreSelectors`),waitForFonts:tu(t.waitForFonts,`waitForFonts`),fontAssertions:t.fontAssertions===void 0?void 0:Ql(t.fontAssertions,`fontAssertions`).map((e,t)=>Jl(e,`fontAssertions[${t}]`)),diff:Yl(t.diff)})}function Ul(e){if(e===void 0)return;let t=Ql(e,`captureViewports`);if(t.length===0)throw Error(`Kapture captureViewports must contain at least one viewport; use captureEnabled: false to skip`);return t.map((e,t)=>Gl(e,`captureViewports[${t}]`))}function Wl(e){if(e===void 0||e===`full-page`||e===`viewport`)return e;throw Error(`Invalid Kapture captureArea: ${String(e)}`)}function Gl(e,t){let n=Zl(e,t);return{name:$l(n.name,`${t}.name`),width:au(n.width,`${t}.width`),height:au(n.height,`${t}.height`)}}function Kl(e){if(e===void 0)return;let t=Zl(e,`waitForElement`),n=t.state;if(n!==void 0&&n!==`attached`&&n!==`visible`&&n!==`hidden`&&n!==`detached`)throw Error(`Invalid Kapture waitForElement state: ${String(n)}`);return lu({selector:$l(t.selector,`waitForElement.selector`),state:n,timeoutMs:iu(t.timeoutMs,`waitForElement.timeoutMs`)})}function ql(e){if(e!==void 0)return e===`disabled`||e===`start`||e===`end`?e:{atMs:ru(Zl(e,`animationState`).atMs,`animationState.atMs`)}}function Jl(e,t){let n=Zl(e,t),r=n.weight;if(r!==void 0&&typeof r!=`string`&&typeof r!=`number`)throw Error(`${t}.weight must be a string or number`);return lu({family:$l(n.family,`${t}.family`),glyphs:$l(n.glyphs,`${t}.glyphs`),style:eu(n.style,`${t}.style`),weight:r})}function Yl(e){if(e===void 0)return;let t=Zl(e,`diff`);if(`maxChangedPixelRatio`in t)throw Error(`Kapture diff.maxChangedPixelRatio is not supported; use diff.maxChangedPixelPercentage with a value between 0 and 100`);return lu({pixelColorThreshold:su(t.pixelColorThreshold,`diff.pixelColorThreshold`),maxChangedPixelPercentage:cu(t.maxChangedPixelPercentage,`diff.maxChangedPixelPercentage`)})}function Xl(e,t){if(e!==void 0)return Ql(e,t).map((e,n)=>$l(e,`${t}[${n}]`))}function Zl(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw Error(`Kapture ${t} must be an object`);return e}function Ql(e,t){if(!Array.isArray(e))throw Error(`Kapture ${t} must be an array`);return e}function $l(e,t){if(typeof e!=`string`||!e.trim())throw Error(`Kapture ${t} must be a non-empty string`);return e}function eu(e,t){return e===void 0?void 0:$l(e,t)}function tu(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Kapture ${t} must be a boolean`);return e}}function nu(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isFinite(e))throw Error(`Kapture ${t} must be a finite number`);return e}}function ru(e,t){let n=nu(e,t);if(n===void 0||n<0)throw Error(`Kapture ${t} must be a non-negative number`);return n}function iu(e,t){return e===void 0?void 0:ru(e,t)}function au(e,t){let n=nu(e,t);if(n===void 0||n<=0)throw Error(`Kapture ${t} must be positive`);return n}function ou(e,t){let n=ru(e,t);if(!Number.isInteger(n))throw Error(`Kapture ${t} must be an integer`);return n}function su(e,t){if(e===void 0)return;let n=ru(e,t);if(n>1)throw Error(`Kapture ${t} must be between 0 and 1`);return n}function cu(e,t){if(e===void 0)return;let n=ru(e,t);if(n>100)throw Error(`Kapture ${t} must be between 0 and 100`);return n}function lu(e){return Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0))}async function uu(e,t,n){let r=JSON.stringify(t),i=await e.evaluate(`(async () => {
326
326
  const expectedStoryId = ${r};
327
327
  const deadline = performance.now() + 10000;
328
328
  let sawAdapter = false;
@@ -420,4 +420,4 @@ ${r}`)}formatType(e,t,n){let r=ih[e.type]||ah[e.level]||`gray`;if(t)return ph(r)
420
420
  `+r.join(`
421
421
  `):``),e.type===`trace`){let t=Error(`Trace: `+e.message);l+=this.formatStack(t.stack||``,t.message)}return o?`
422
422
  `+l+`
423
- `:l}};function dh(e){return e.replace(/`([^`]+)`/gm,(e,t)=>K.cyan(t)).replace(/\s+_([^_]+)_\s+/gm,(e,t)=>` ${K.underline(t)} `)}function fh(e=`white`){return K[e]||K.white}function ph(e=`bgWhite`){return K[`bg${e[0].toUpperCase()}${e.slice(1)}`]||K.bgWhite}function mh(e={}){let t=hh();return process.env.CONSOLA_LEVEL&&(t=Number.parseInt(process.env.CONSOLA_LEVEL)??t),yf({level:t,defaults:{level:t},stdout:process.stdout,stderr:process.stderr,prompt:(...e)=>Promise.resolve().then(()=>(vm(),Gf)).then(t=>t.prompt(...e)),reporters:e.reporters||[e.fancy??!(Om||jm)?new uh:new Cf],...e})}function hh(){return Am?U.debug:jm?U.warn:U.info}const X=mh();function gh(e){let t=Rh.safeParse(_h(e));if(!t.success){let e=t.error.issues[0],n=e?.path.length?` at ${e.path.join(`.`)}`:``;throw Error(`Invalid Kapture report${n}: ${e?.message??`unknown error`}`)}return t.data}function _h(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;return t.version!==2||!t.summary||typeof t.summary!=`object`?e:{...t,version:3,summary:{...t.summary,unstable:0}}}async function vh(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r;try{r=JSON.parse(await x(t,`utf8`))}catch{throw Error(`Kapture report does not contain valid JSON`)}return gh(r)}function yh(e){try{let t=new URL(e);return t.protocol===`https:`&&!t.username&&!t.password}catch{return!1}}var bh,xh,Z,Q,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh=S((()=>{_d(),Tc(),bh=10485760,xh=2e4,Z=F().max(4096),Q=F().min(1).max(512),Sh=Q.refine(e=>Array.from(e).every(e=>{let t=e.codePointAt(0)??0;return t>31&&t!==127}),`must not contain control characters`),Ch=I().int().min(0).max(2**53-1),wh=I().int().positive().max(2**53-1),Th=I().min(0).max(1),Eh=L({name:Q,width:I().int().positive().max(16384),height:I().int().positive().max(16384)}),Dh=L({pixelColorThreshold:Th,maxChangedPixelRatio:Th}),Oh=L({id:Q,browser:Q,browserVersion:Q,orchestratorRuntime:Q,operatingSystem:Q,architecture:Q,deviceScaleFactor:I().positive().max(8),locale:Q,timezone:Q,colorScheme:z([`light`,`dark`]),reducedMotion:z([`reduce`,`no-preference`]),frozenTime:Q,randomSeed:I().int().min(0).max(2**53-1),fontsFingerprint:Q,stateIsolation:B(`fresh-browser-process-per-story-side-v1`).optional(),network:L({mode:B(`allowlist`),allowedDomains:ms(Q).max(100),webRtc:B(`disabled`)})}),kh=L({id:Q,storyId:Q,title:Z,name:Z,viewport:Eh,status:z([`unchanged`,`changed`,`unstable`,`added`,`removed`,`error`]),baseImage:Z.optional(),headImage:Z.optional(),diffImage:Z.optional(),changedPixels:Ch.optional(),diffRatio:Th.optional(),threshold:Dh.optional(),instability:L({base:L({repeatImage:Z,diffImage:Z,changedPixels:Ch,diffRatio:Th}).optional(),head:L({repeatImage:Z,diffImage:Z,changedPixels:Ch,diffRatio:Th}).optional()}).optional(),error:Z.optional()}).superRefine((e,t)=>{e.status===`unstable`&&!e.instability?.base&&!e.instability?.head&&t.addIssue({code:`custom`,path:[`instability`],message:`unstable snapshots require base or head instability evidence`}),e.status!==`unstable`&&e.instability&&t.addIssue({code:`custom`,path:[`instability`],message:`only unstable snapshots can contain instability evidence`})}),Ah=ms(Q).max(xh).refine(e=>new Set(e).size===e.length,`must not contain duplicates`).refine(e=>e.every((t,n)=>n===0||e[n-1]<t),`must be sorted`),jh=L({code:z([`base-manifest-missing`,`base-manifest-invalid`,`head-manifest-missing`,`head-manifest-invalid`,`changed-files-incomplete`,`manifest-incomplete`,`global-input`,`global-output`,`global-runtime`,`unknown-input`,`story-import-missing`,`story-module-missing`,`fallback-reasons-truncated`]),path:Z.optional(),storyId:Q.optional(),side:z([`base`,`head`]).optional()}),Mh=L({provider:B(`github-pull-request-files`),manifestDigest:F().regex(/^[0-9a-f]{64}$/),pullRequestNumber:wh,baseSha:F().regex(/^[0-9a-f]{40}$/),headSha:F().regex(/^[0-9a-f]{40}$/)}),Nh=F().regex(/^[0-9a-f]{64}$/),Ph=_s(`state`,[L({state:B(`valid`),digest:Nh,revision:Q}),L({state:B(`invalid`),digest:Nh.optional(),revision:Q}),L({state:B(`missing`),revision:Q})]),Fh=L({base:Ph,head:Ph}),Ih=L({repository:Q.regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),number:wh,url:Z.refine(yh,`must be an HTTPS URL without credentials`),baseBranch:Sh,headBranch:Sh,workflowRunUrl:Z.refine(yh,`must be an HTTPS URL without credentials`)}),Lh=L({plannerVersion:B(1),mode:z([`full`,`affected`,`full-fallback`]),changedFilesEvidence:Mh.optional(),dependencyManifests:Fh.optional(),storyIds:Ah,selectedStoryIds:Ah,skippedStoryIds:Ah,addedStoryIds:Ah.optional(),removedStoryIds:Ah.optional(),fallbackReasons:ms(jh).max(dd),baseline:L({mode:B(`reused`),revision:Q,manifestDigest:Nh}).optional()}).superRefine((e,t)=>{let n=new Set(e.storyIds),r=new Set(e.selectedStoryIds),i=new Set(e.skippedStoryIds);if((r.size+i.size!==n.size||[...r].some(e=>!n.has(e)||i.has(e))||[...i].some(e=>!n.has(e)))&&t.addIssue({code:`custom`,message:`selected and skipped stories must exactly partition the story catalog`}),e.mode!==`affected`&&i.size>0&&t.addIssue({code:`custom`,path:[`skippedStoryIds`],message:`full coverage modes cannot skip stories`}),e.mode===`full-fallback`&&e.fallbackReasons.length===0&&t.addIssue({code:`custom`,path:[`fallbackReasons`],message:`full-fallback coverage requires at least one reason`}),e.mode!==`full-fallback`&&e.fallbackReasons.length>0&&t.addIssue({code:`custom`,path:[`fallbackReasons`],message:`only full-fallback coverage can contain fallback reasons`}),e.addedStoryIds===void 0!=(e.removedStoryIds===void 0)&&t.addIssue({code:`custom`,message:`added and removed story catalogs must be provided together`}),e.addedStoryIds&&e.removedStoryIds){let i=new Set(e.addedStoryIds),a=new Set(e.removedStoryIds);([...i].some(e=>!n.has(e)||!r.has(e)||a.has(e))||[...a].some(e=>!n.has(e)||!r.has(e)))&&t.addIssue({code:`custom`,message:`added and removed stories must be disjoint selected catalog members`})}}),Rh=L({version:B(3),contentDigest:F().regex(/^[0-9a-f]{64}$/).optional(),baseRevision:Q,headRevision:Q,headBranch:Sh.optional(),pullRequest:Ih.optional(),storybookUrl:Z.refine(e=>e===`./storybook/`||yh(e),`must be an HTTPS URL or ./storybook/ without credentials`).optional(),environment:Oh,createdAt:Q,threshold:Dh,summary:L({total:Ch,unchanged:Ch,changed:Ch,unstable:Ch,added:Ch,removed:Ch,errors:Ch}),coverage:Lh.optional(),entries:R(F(),kh)}).superRefine((e,t)=>{let n=Object.entries(e.entries);if(n.length>2e4){t.addIssue({code:`custom`,message:`Report contains more than ${xh} entries`,path:[`entries`]});return}for(let[e,r]of n)e!==r.id&&t.addIssue({code:`custom`,message:`Entry key must match entry.id`,path:[`entries`,e,`id`]});let r={unchanged:0,changed:0,unstable:0,added:0,removed:0,error:0};for(let t of Object.values(e.entries))r[t.status]+=1;if((e.summary.total!==n.length||e.summary.unchanged!==r.unchanged||e.summary.changed!==r.changed||e.summary.unstable!==r.unstable||e.summary.added!==r.added||e.summary.removed!==r.removed||e.summary.errors!==r.error)&&t.addIssue({code:`custom`,message:`Report summary does not match its entries`,path:[`summary`]}),e.coverage){let r=e.coverage.changedFilesEvidence;r&&(r.baseSha!==e.baseRevision||r.headSha!==e.headRevision)&&t.addIssue({code:`custom`,message:`Changed-files evidence must match the report base and head revisions`,path:[`coverage`,`changedFilesEvidence`]});let i=e.coverage.dependencyManifests;i&&(i.base.revision!==e.baseRevision||i.head.revision!==e.headRevision)&&t.addIssue({code:`custom`,message:`Dependency manifest evidence must match the report base and head revisions`,path:[`coverage`,`dependencyManifests`]});let a=new Set(e.coverage.selectedStoryIds),o=new Set(e.coverage.addedStoryIds??[]),s=new Set(e.coverage.removedStoryIds??[]);for(let[e,r]of n)a.has(r.storyId)||t.addIssue({code:`custom`,message:`Report entries must belong to selected stories`,path:[`entries`,e,`storyId`]}),o.has(r.storyId)&&r.status!==`added`&&r.status!==`error`&&t.addIssue({code:`custom`,message:`Entries for an added story must be added or error snapshots`,path:[`entries`,e,`status`]}),s.has(r.storyId)&&r.status!==`removed`&&r.status!==`error`&&t.addIssue({code:`custom`,message:`Entries for a removed story must be removed or error snapshots`,path:[`entries`,e,`status`]})}})}));_d(),E();var Bh=Nt();zh();const Vh=26214400,Hh=Buffer.from([137,80,78,71,13,10,26,10]),Uh=new Set([`acTL`,`fcTL`,`fdAT`]),Wh=[`baseImage`,`headImage`,`diffImage`,`baseRepeatImage`,`baseInstabilityDiffImage`,`headRepeatImage`,`headInstabilityDiffImage`],Gh=T({meta:{name:`build`,description:`Rebuild a trusted static report from an untrusted Kapture artifact`},args:{input:{type:`string`,required:!0,description:`Untrusted artifact report directory containing report.json and images`},output:{type:`string`,required:!0,description:`New directory for the trusted static report`},"storybook-url":{type:`string`,description:`Trusted HTTPS Storybook URL or the fixed same-origin ./storybook/ directory`}},async run({args:e}){let t=await Kh({inputDir:e.input,outputDir:e.output,storybookUrl:e[`storybook-url`]});X.success(`Trusted report: ${t.report.summary.total} snapshots, ${t.imageCount} verified PNGs (${t.imageBytes} bytes)`),X.info(`Output: ${t.outputDir}`)}});async function Kh(e){let t=f(e.inputDir),n=f(e.outputDir),r=qh(e.trustedHeadBranch);if(await ag(t),cg(t,n))throw Error(`Trusted report output must be outside the untrusted input directory`);await og(n);let i=e.dashboardDir?f(e.dashboardDir):f(a(me(import.meta.url)),`dashboard`),o=a(n);await y(o,{recursive:!0});let s=await te(`${o}${p}.kapture-report-`),c;try{c=await Yh(t,async(e,t)=>{let n=f(s,e.relativePath);await y(a(n),{recursive:!0}),await se(n,t,{flag:`wx`})});let{report:o,imageDigests:l,calculatedContentDigest:u}=c;if(o.contentDigest&&o.contentDigest!==u)throw Error(`Report content digest does not match its referenced PNGs: expected ${o.contentDigest}, calculated ${u}`);r?o.headBranch=r:delete o.headBranch,e.trustedPullRequest?o.pullRequest={...e.trustedPullRequest}:delete o.pullRequest;let d=jd(e.storybookUrl);d?o.storybookUrl=d:delete o.storybookUrl,o.contentDigest=Wc(o,l),await se(f(s,`report.json`),`${JSON.stringify(o)}\n`,{flag:`wx`}),await Iu(i,s),await ie(s,n)}catch(e){throw await ae(s,{recursive:!0,force:!0}),e}if(!c)throw Error(`Trusted report validation did not complete`);return{report:c.report,outputDir:n,imageCount:c.references.length,imageBytes:c.imageBytes}}function qh(e){if(e!==void 0){if(e.length<1||e.length>512||Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127}))throw Error(`Trusted head branch must contain between 1 and 512 non-control characters`);return e}}async function Jh(e,t){if(!/^[0-9a-f]{64}$/.test(t))throw Error(`Expected trusted report content digest must be a lowercase SHA-256 digest`);let n=f(e);if(n!==f(a(n),`report.json`))throw Error(`Trusted report path must end in report.json`);let r=a(n);await ag(r);let i=await Yh(r);if(i.report.contentDigest!==t||i.calculatedContentDigest!==t)throw Error(`Trusted report content digest does not match its actual structure and referenced PNGs`);return i.report}async function Yh(e,t){let n=Xh(await sg(e,`report.json`,bh)),r=Zh(n);if(r.length>6e4)throw Error(`Report references more than 60000 PNG images`);let i=new Map,a=[],o=0;for(let n of r){let r=await sg(e,n.relativePath,Vh);if(o+=r.byteLength,o>536870912)throw Error(`Referenced PNGs exceed 536870912 total bytes`);i.set(n.relativePath,ng(r,n.relativePath)),a.push({path:n.relativePath,sha256:m(`sha256`).update(r).digest(`hex`)}),await t?.(n,r)}return ig(n,i),{report:n,references:r,imageDigests:a,imageBytes:o,calculatedContentDigest:Wc(n,a)}}function Xh(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch{throw Error(`Input report.json does not contain valid JSON`)}return gh(t)}function Zh(e){let t=new Map;for(let n of Object.values(e.entries)){let e=Qh(n);for(let r of Wh){let i=eg(n,r);if(e.has(r)&&!i)throw Error(`Report entry ${n.id} is missing ${r} for status ${n.status}`);if(!e.has(r)&&i)throw Error(`Report entry ${n.id} cannot contain ${r} for status ${n.status}`);if(!i)continue;let a=tg(i,$h(r),n.id),o=t.get(a);if(o&&o.entryId!==n.id)throw Error(`Report entries ${o.entryId} and ${n.id} reference the same PNG: ${a}`);t.set(a,{relativePath:a,entryId:n.id})}}return[...t.values()]}function Qh(e){if(e.status===`changed`)return new Set([`baseImage`,`headImage`,`diffImage`]);if(e.status===`unstable`){if(!e.instability?.base&&!e.instability?.head)throw Error(`Report entry ${e.id} is unstable without instability evidence`);let t=[`baseImage`,`headImage`,`diffImage`];return e.instability.base&&t.push(`baseRepeatImage`,`baseInstabilityDiffImage`),e.instability.head&&t.push(`headRepeatImage`,`headInstabilityDiffImage`),new Set(t)}return e.status===`added`?new Set([`headImage`]):e.status===`removed`?new Set([`baseImage`]):new Set}function $h(e){return e===`baseImage`?`base`:e===`headImage`?`head`:e===`diffImage`?`diff`:e===`baseRepeatImage`?`base-repeat`:e===`baseInstabilityDiffImage`?`base-instability-diff`:e===`headRepeatImage`?`head-repeat`:`head-instability-diff`}function eg(e,t){return t===`baseImage`||t===`headImage`||t===`diffImage`?e[t]:t===`baseRepeatImage`?e.instability?.base?.repeatImage:t===`baseInstabilityDiffImage`?e.instability?.base?.diffImage:t===`headRepeatImage`?e.instability?.head?.repeatImage:e.instability?.head?.diffImage}function tg(e,t,n){let r=`images/${t}/`,i=e.slice(r.length);if(!e.startsWith(r)||!i||i.includes(`/`)||i.includes(`\\`)||i.length>255||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*\.png$/.test(i))throw Error(`Report entry ${n} has an invalid ${t} PNG path: ${e}`);return e}function ng(e,t){if(e.byteLength<33||!e.subarray(0,8).equals(Hh))throw Error(`Referenced image is not a PNG: ${t}`);let n=e.readUInt32BE(8),r=e.toString(`ascii`,12,16);if(n!==13||r!==`IHDR`)throw Error(`Referenced PNG has an invalid IHDR chunk: ${t}`);let i=e.readUInt32BE(16),a=e.readUInt32BE(20);if(i<1||a<1||i>16384||a>32768||i*a>33554432)throw Error(`Referenced PNG dimensions are outside the supported limits: ${t} (${i}x${a})`);rg(e,t);try{let t=Bh.PNG.sync.read(e,{checkCRC:!0,skipRescale:!0});if(t.width!==i||t.height!==a)throw Error(`decoded dimensions differ from IHDR`)}catch{throw Error(`Referenced PNG cannot be decoded safely: ${t}`)}return{width:i,height:a}}function rg(e,t){let n=Hh.byteLength,r=!1;for(;n+12<=e.byteLength;){let i=e.readUInt32BE(n),a=e.toString(`ascii`,n+4,n+8),o=n+12+i;if(o>e.byteLength)throw Error(`Referenced PNG has an invalid chunk boundary: ${t}`);if(Uh.has(a))throw Error(`Animated PNG is not supported in a static report: ${t}`);if(n=o,a===`IEND`){r=!0;break}}if(!r||n!==e.byteLength)throw Error(`Referenced PNG has an invalid chunk structure: ${t}`)}function ig(e,t){for(let n of Object.values(e.entries)){if(n.status!==`changed`&&n.status!==`unstable`||!n.baseImage||!n.headImage||!n.diffImage)continue;let e=t.get(n.baseImage),r=t.get(n.headImage),i=t.get(n.diffImage);if(!e||!r||!i)throw Error(`Report entry ${n.id} is missing validated PNG dimensions`);let a=Math.max(e.width,r.width),o=Math.max(e.height,r.height);if(i.width!==a||i.height!==o)throw Error(`Report entry ${n.id} diff PNG must match the padded comparison canvas ${a}x${o}`);if(n.changedPixels!==void 0&&n.changedPixels>a*o)throw Error(`Report entry ${n.id} changedPixels exceeds its diff PNG pixel count`);for(let i of[n.instability?.base,n.instability?.head]){if(!i)continue;let a=t.get(i.repeatImage),o=t.get(i.diffImage);if(!a||!o)throw Error(`Report entry ${n.id} is missing instability PNG dimensions`);let s=i===n.instability?.base?e:r,c=Math.max(s.width,a.width),l=Math.max(s.height,a.height);if(o.width!==c||o.height!==l)throw Error(`Report entry ${n.id} instability diff PNG must match ${c}x${l}`);if(i.changedPixels>c*l)throw Error(`Report entry ${n.id} instability changedPixels exceeds its diff PNG pixel count`)}}}async function ag(e){let t;try{t=await v(e)}catch(t){throw lg(t)?Error(`Input report directory does not exist: ${e}`):t}if(t.isSymbolicLink()||!t.isDirectory())throw Error(`Input report path must be a real directory, not a symbolic link`)}async function og(e){try{await v(e)}catch(e){if(lg(e))return;throw e}throw Error(`Trusted report output already exists: ${e}`)}async function sg(e,t,n){if(s(t)||t.includes(`\\`))throw Error(`Input file must be a normalized relative path: ${t}`);let r=t.split(`/`),i=e;for(let[e,n]of r.entries()){if(!n||n===`.`||n===`..`)throw Error(`Input file must be a normalized relative path: ${t}`);i=f(i,n);let a;try{a=await v(i)}catch(e){throw lg(e)?Error(`Referenced input file does not exist: ${t}`):e}if(a.isSymbolicLink())throw Error(`Referenced input path cannot contain a symbolic link: ${t}`);let o=e===r.length-1;if(!o&&!a.isDirectory()||o&&!a.isFile())throw Error(`Referenced input path is not a regular file: ${t}`)}let a=pe.O_RDONLY|(pe.O_NOFOLLOW??0),o=await b(i,a);try{let e=await o.stat();if(!e.isFile()||e.size>n)throw Error(`Input file exceeds ${n} bytes: ${t}`);let r=Buffer.alloc(e.size),i=0;for(;i<r.byteLength;){let{bytesRead:e}=await o.read(r,i,r.byteLength-i,i);if(e===0)throw Error(`Input file changed while being read: ${t}`);i+=e}let a=Buffer.alloc(1),{bytesRead:s}=await o.read(a,0,1,r.byteLength);if(s>0)throw Error(`Input file changed while being read: ${t}`);return r}finally{await o.close()}}function cg(e,t){let n=d(e,t);return n===``||!n.startsWith(`..${p}`)&&n!==`..`&&!s(n)}function lg(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function ug(e,t){return fg(e,t).map(({path:e,compressedBytes:t,uncompressedBytes:n})=>({path:e,compressedBytes:t,uncompressedBytes:n}))}async function dg(e,t,n){let r=fg(e,n),i=f(t);await y(i,{recursive:!0});for(let t of r){let n=e.subarray(t.dataOffset,t.dataOffset+t.compressedBytes),r=t.compression===0?Buffer.from(n):Se(n,{maxOutputLength:t.uncompressedBytes+1});if(r.byteLength!==t.uncompressedBytes)throw Error(`ZIP entry size mismatch: ${t.path}`);if(xe(r)!==t.crc)throw Error(`ZIP entry checksum mismatch: ${t.path}`);let o=f(i,t.path);if(!o.startsWith(`${i}${p}`))throw Error(`ZIP entry escapes the output directory: ${t.path}`);await y(a(o),{recursive:!0}),await se(o,r,{flag:`wx`})}return r}function fg(e,t){_g(t);let n=pg(e),r=e.readUInt16LE(n+4),i=e.readUInt16LE(n+6),a=e.readUInt16LE(n+8),o=e.readUInt16LE(n+10),s=e.readUInt32LE(n+12),c=e.readUInt32LE(n+16),l=e.readUInt16LE(n+20);if(n+22+l!==e.byteLength)throw Error(`ZIP end record does not match the archive size`);if(r!==0||i!==0||a!==o)throw Error(`Multi-disk ZIP archives are not supported`);if(o===65535||s===4294967295||c===4294967295)throw Error(`ZIP64 archives are not supported`);if(o>t.maxEntries)throw Error(`ZIP archive contains more than ${t.maxEntries} entries`);if(c+s!==n)throw Error(`ZIP central directory is malformed`);let u=[],d=new Set,f=c,p=0;for(let r=0;r<o;r+=1){if(f+46>n||e.readUInt32LE(f)!==33639248)throw Error(`ZIP central directory entry is malformed`);let r=e.readUInt16LE(f+4),i=e.readUInt16LE(f+8),a=e.readUInt16LE(f+10),o=e.readUInt32LE(f+16),s=e.readUInt32LE(f+20),l=e.readUInt32LE(f+24),m=e.readUInt16LE(f+28),h=e.readUInt16LE(f+30),g=e.readUInt16LE(f+32),_=e.readUInt16LE(f+34),ee=e.readUInt32LE(f+38),v=e.readUInt32LE(f+42),y=f+46+m+h+g;if(y>n)throw Error(`ZIP central directory entry exceeds its bounds`);if(i&1)throw Error(`Encrypted ZIP entries are not supported`);if(a!==0&&a!==8)throw Error(`ZIP compression method ${a} is not supported`);if(_!==0)throw Error(`Multi-disk ZIP entries are not supported`);if(s===4294967295||l===4294967295||v===4294967295)throw Error(`ZIP64 entries are not supported`);let te=e.subarray(f+46,f+46+m),b=hg(te);f=y;let x=b.endsWith(`/`);if(gg(r,ee,b,x),d.has(b))throw Error(`ZIP archive contains duplicate path: ${b}`);if(d.add(b),x){if(!t.allowDirectoryPath(b))throw Error(`ZIP archive contains unexpected directory: ${b}`);if(i&8||a!==0||o!==0||s!==0||l!==0)throw Error(`ZIP directory entry must be empty and stored: ${b}`);mg(e,v,te,i,a,o,s,l,c);continue}if(!t.allowPath(b))throw Error(`ZIP archive contains unexpected path: ${b}`);if(l>t.maxFileBytes)throw Error(`ZIP entry exceeds ${t.maxFileBytes} bytes: ${b}`);if(p+=l,p>t.maxTotalBytes)throw Error(`ZIP archive exceeds ${t.maxTotalBytes} uncompressed bytes`);let ne=mg(e,v,te,i,a,o,s,l,c);u.push({path:b,compression:a,crc:o,compressedBytes:s,uncompressedBytes:l,dataOffset:ne})}if(f!==n)throw Error(`ZIP central directory size is inconsistent`);return u}function pg(e){let t=Math.max(0,e.byteLength-65557);for(let n=e.byteLength-22;n>=t;--n)if(e.readUInt32LE(n)===101010256)return n;throw Error(`ZIP end-of-central-directory record is missing`)}function mg(e,t,n,r,i,a,o,s,c){if(t+30>c||e.readUInt32LE(t)!==67324752)throw Error(`ZIP local entry header is malformed`);let l=e.readUInt16LE(t+6),u=e.readUInt16LE(t+8),d=e.readUInt32LE(t+14),f=e.readUInt32LE(t+18),p=e.readUInt32LE(t+22),m=e.readUInt16LE(t+26),h=e.readUInt16LE(t+28),g=t+30+m+h;if(g>c)throw Error(`ZIP local entry header exceeds its bounds`);let _=e.subarray(t+30,t+30+m);if(l!==r||u!==i||!_.equals(n))throw Error(`ZIP local and central directory entries do not match`);if(!(l&8)&&(d!==a||f!==o||p!==s))throw Error(`ZIP local and central directory sizes or checksum do not match`);if(g+o>c)throw Error(`ZIP entry data exceeds the archive bounds`);return g}function hg(e){let t=e.toString(`utf8`);if(!Buffer.from(t,`utf8`).equals(e))throw Error(`ZIP path is not valid UTF-8`);let n=t.endsWith(`/`),r=t.split(`/`),i=n?r.slice(0,-1):r;if(t.length<1||t.startsWith(`/`)||t.includes(`\\`)||t.includes(`\0`)||i.some(e=>!e||e===`.`||e===`..`)||Array.from(t).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127}))throw Error(`ZIP path is unsafe: ${JSON.stringify(t)}`);return t}function gg(e,t,n,r){if(e>>>8!=3)return;let i=t>>>16&61440;if(i!==0&&i!==(r?16384:32768))throw Error(r?`ZIP entry is not a directory: ${n}`:`ZIP entry is not a regular file: ${n}`)}function _g(e){for(let[t,n]of Object.entries({maxEntries:e.maxEntries,maxFileBytes:e.maxFileBytes,maxTotalBytes:e.maxTotalBytes}))if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be positive`)}function vg(e,t){let n=Eg(e,`GitHub pull_request event`),r=Eg(n.pull_request,`pull_request`),i=xg(Eg(n.repository,`repository`)),a=Eg(r.base,`pull_request.base`),o=Eg(r.head,`pull_request.head`),s=xg(Eg(a.repo,`pull_request.base.repo`)),c=Eg(o.repo,`pull_request.head.repo`),l=Cg(a.ref,`pull_request.base.ref`),u=Cg(o.ref,`pull_request.head.ref`),d=wg(r.number,`pull request number`);if(s!==i)throw Error(`Pull request base repository must match the workflow repository`);if(t!==void 0&&l!==Cg(t,`base branch`))throw Error(`Pull request targets ${l}, expected ${t}`);return{schemaVersion:1,runId:wg(n.run_id??process.env.GITHUB_RUN_ID,`workflow run ID`),prNumber:d,base:{repository:s,ref:l,sha:Sg(a.sha,`pull_request.base.sha`)},head:{repository:xg(c),repositoryId:wg(c.id,`head repository ID`),ref:u,sha:Sg(o.sha,`pull_request.head.sha`)},preview:{branch:u,alias:bg(d,u)}}}function yg(e){return`pr-${e.prNumber}-base-${e.base.sha}-head-${e.head.sha}`}function bg(e,t){let n=`pr-${wg(e,`pull request number`)}-`,r=Cg(t,`head branch`),i=r.normalize(`NFKD`).toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``),a=`-${m(`sha256`).update(r).digest(`hex`).slice(0,10)}`,o=Math.max(1,63-n.length-a.length);return`${n}${(i||`branch`).slice(0,o).replace(/-$/g,``)||`b`}${a}`}function xg(e){let t=Tg(e.full_name,`repository full name`);if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error(`GitHub event contains an invalid repository full name`);return t}function Sg(e,t){let n=Tg(e,t).toLowerCase();if(!/^[0-9a-f]{40}$/.test(n))throw Error(`${t} must be a full SHA`);return n}function Cg(e,t){let n=Tg(e,t);if(n.length<1||n.length>512)throw Error(`${t} is invalid`);for(let e of n){let n=e.codePointAt(0)??0;if(n<=31||n===127)throw Error(`${t} is invalid`)}return n}function wg(e,t){let n=typeof e==`string`&&/^[1-9][0-9]*$/.test(e)?Number(e):e;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function Tg(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string`);return e}function Eg(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}const Dg=3e3;async function Og(e,t){let n=await e.getPullRequestForCapture(t.prNumber);jg(n,t);let r=Hg(n.changed_files,`pull request changed_files`),i=[],a=[],o=0;if(r>3e3)i.push({code:`github-file-limit`});else for(let n=1;n<=Math.ceil(r/100);n+=1){let s=await e.listPullRequestFilesPage(t.prNumber,n,100);if(o=n,!Array.isArray(s)){i.push({code:`pagination-incomplete`,page:n});break}let c=s.slice(0,100);s.length>100&&i.push({code:`pagination-incomplete`,page:n});for(let[e,t]of c.entries())a.push({value:t,page:n,index:e});if(c.length<100){a.length<r&&i.push({code:`pagination-incomplete`,page:n});break}}a.length!==r&&i.push({code:`file-count-mismatch`});let s=new Set,c=new Set;for(let e of a)Mg(e,s,c,i);let l=await e.getPullRequestForCapture(t.prNumber);if(jg(l,t),l.changed_files!==r)throw Error(`Pull request changed while Kapture discovered changed files`);let u=Fg(i);return{kind:`kapture-changed-files`,version:1,complete:u.length===0,pullRequest:{number:t.prNumber,baseSha:t.base.sha,headSha:t.head.sha},files:[...s].sort(),source:{provider:`github-pull-request-files`,expectedFileCount:r,fetchedFileCount:a.length,pageCount:o,perPage:100,maxFiles:Dg},diagnostics:u}}function kg(e){let t=Ug(e,`changed-files manifest`);if(zg(t,[`kind`,`version`,`complete`,`pullRequest`,`files`,`source`,`diagnostics`],`changed-files manifest`),t.kind!==`kapture-changed-files`||t.version!==1)throw Error(`changed-files manifest must use kapture-changed-files version 1`);if(typeof t.complete!=`boolean`)throw Error(`changed-files manifest complete must be a boolean`);if(!Array.isArray(t.files)||t.files.length>6e3)throw Error(`changed-files manifest files must be a bounded array`);let n=t.files.map(e=>Ag(e,`changed file path`));if(!Ig(n))throw Error(`changed-files manifest files must be unique and sorted`);let r=Ug(t.pullRequest,`changed-files manifest pullRequest`);zg(r,[`number`,`baseSha`,`headSha`],`changed-files manifest pullRequest`);let i=Ug(t.source,`changed-files manifest source`);if(zg(i,[`provider`,`expectedFileCount`,`fetchedFileCount`,`pageCount`,`perPage`,`maxFiles`],`changed-files manifest source`),i.provider!==`github-pull-request-files`)throw Error(`changed-files manifest source provider is invalid`);if(i.perPage!==100||i.maxFiles!==3e3)throw Error(`changed-files manifest source limits are invalid`);if(!Array.isArray(t.diagnostics)||t.diagnostics.length>6e3)throw Error(`changed-files manifest diagnostics must be a bounded array`);let a=t.diagnostics.map(Pg);if(!Ig(a.map(Lg)))throw Error(`changed-files manifest diagnostics must be unique and sorted`);if(t.complete!==(a.length===0))throw Error(`changed-files manifest completeness disagrees with diagnostics`);let o=Hg(i.expectedFileCount,`changed-files expected file count`),s=Hg(i.fetchedFileCount,`changed-files fetched file count`),c=Hg(i.pageCount,`changed-files page count`);if(s>3e3||c>30||s>c*100||n.length>s*2)throw Error(`changed-files manifest source counts are inconsistent`);if(t.complete&&(o!==s||o>3e3||c!==Math.ceil(s/100)||n.length<s))throw Error(`complete changed-files manifest source counts are inconsistent`);return{kind:`kapture-changed-files`,version:1,complete:t.complete,pullRequest:{number:Vg(r.number,`changed-files pull request number`),baseSha:Bg(r.baseSha,`changed-files base SHA`),headSha:Bg(r.headSha,`changed-files head SHA`)},files:n,source:{provider:`github-pull-request-files`,expectedFileCount:o,fetchedFileCount:s,pageCount:c,perPage:100,maxFiles:Dg},diagnostics:a}}function Ag(e,t=`GitHub file path`){if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=Array.from(e);if(e.length===0||e.length>4096||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`./`)||e===`.`||e===`..`||e.startsWith(`../`)||e.endsWith(`/`)||e.includes(`//`)||e.includes(`\\`)||e.split(`/`).some(e=>e===`.`||e===`..`)||n.some(e=>{let t=e.codePointAt(0)??0;return t<=31||t>=127&&t<=159}))throw Error(`${t} must be a normalized project-relative path`);return e}function jg(e,t){let n=e.head.repo;if(e.number!==t.prNumber||e.state!==`open`||e.base.ref!==t.base.ref||e.base.sha.toLowerCase()!==t.base.sha||e.base.repo.full_name!==t.base.repository||e.head.ref!==t.head.ref||e.head.sha.toLowerCase()!==t.head.sha||n?.id!==t.head.repositoryId||n.full_name!==t.head.repository)throw Error(`Live pull request does not match the exact Kapture capture context`)}function Mg(e,t,n,r){if(!e.value||typeof e.value!=`object`||Array.isArray(e.value)){r.push({code:`invalid-file-record`,page:e.page,index:e.index});return}let i=e.value;if(typeof i.status!=`string`||typeof i.filename!=`string`){r.push({code:`invalid-file-record`,page:e.page,index:e.index});return}let a=JSON.stringify([i.status,i.filename,i.previous_filename]);if(n.has(a)&&r.push({code:`duplicate-file-entry`,page:e.page,index:e.index}),n.add(a),Ng(i.filename,e,t,r),i.status===`renamed`||i.previous_filename!==void 0){if(typeof i.previous_filename!=`string`){r.push({code:`rename-source-missing`,page:e.page,index:e.index});return}Ng(i.previous_filename,e,t,r)}}function Ng(e,t,n,r){try{n.add(Ag(e))}catch{r.push({code:`invalid-file-path`,page:t.page,index:t.index})}}function Pg(e){let t=Ug(e,`changed-files diagnostic`);if(zg(t,[`code`,`page`,`index`],`changed-files diagnostic`,!0),typeof t.code!=`string`||![`github-file-limit`,`pagination-incomplete`,`file-count-mismatch`,`invalid-file-record`,`invalid-file-path`,`rename-source-missing`,`duplicate-file-entry`].includes(t.code))throw Error(`changed-files diagnostic code is invalid`);let n=t.page===void 0?void 0:Vg(t.page,`page`),r=t.index===void 0?void 0:Hg(t.index,`diagnostic index`),i={code:t.code,...n===void 0?{}:{page:n},...r===void 0?{}:{index:r}};if(i.code===`github-file-limit`||i.code===`file-count-mismatch`?n!==void 0||r!==void 0:i.code===`pagination-incomplete`?n===void 0||n>30||r!==void 0:n===void 0||n>30||r===void 0||r>=100)throw Error(`changed-files diagnostic location is invalid`);return i}function Fg(e){return[...new Map(e.map(e=>[JSON.stringify(e),e])).values()].sort((e,t)=>Rg(Lg(e),Lg(t)))}function Ig(e){return e.every((t,n)=>n===0||(e[n-1]??``)<t)}function Lg(e){return`${e.code}:${String(e.page??0).padStart(2,`0`)}:${String(e.index??0).padStart(3,`0`)}`}function Rg(e,t){return e<t?-1:+(e>t)}function zg(e,t,n,r=!1){let i=Object.keys(e).sort(),a=r?i.filter(e=>t.includes(e)).sort():[...t].sort();if(i.some(e=>!t.includes(e))||!r&&(i.length!==a.length||i.some((e,t)=>e!==a[t])))throw Error(`${n} contains unexpected or missing fields`)}function Bg(e,t){if(typeof e!=`string`||!/^[0-9a-f]{40}$/.test(e))throw Error(`${t} must be a full lowercase SHA`);return e}function Vg(e,t){let n=Hg(e,t);if(n===0)throw Error(`${t} must be a positive integer`);return n}function Hg(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function Ug(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}Tc(),zh();const Wg=/^[0-9a-f]{40}$/,Gg=/^sha256:[0-9a-f]{64}$/,Kg=/^[0-9a-f]{64}$/,qg=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,Jg=/^\.github\/workflows\/[A-Za-z0-9_./-]+\.ya?ml$/,Yg=/^images\/(?:base|head|diff)\/[A-Za-z0-9][A-Za-z0-9._-]*\.png$/,Xg=F().min(1).max(512).refine(e=>!ov(e),`must not contain control characters`),Zg=F().regex(Wg),Qg=I().int().positive().max(2**53-1),$g=F().regex(qg),e_=F().regex(Gg),t_=L({schemaVersion:B(1),runId:Qg,prNumber:Qg,base:L({repository:$g,ref:Xg,sha:Zg}),head:L({repository:$g,repositoryId:Qg,ref:Xg,sha:Zg}),preview:L({branch:Xg,alias:Xg})}),n_=L({id:Qg,name:Xg,sizeInBytes:Qg,digest:e_}),r_=L({id:Qg,name:Xg,digest:e_}),i_=L({schemaVersion:B(1),artifacts:L({context:r_,baseStorybook:r_,headStorybook:r_})}),a_=L({schemaVersion:B(2),repository:L({id:Qg,fullName:$g}),context:t_,captureRun:L({id:Qg,runNumber:Qg,attempt:Qg,workflowId:Qg,workflowPath:Xg,headSha:Zg,headBranch:Xg,headRepositoryId:Qg,headRepository:$g}),artifacts:L({context:n_,baseStorybook:n_,headStorybook:n_,report:n_}),report:L({contentDigest:F().regex(Kg)}),trustedArtifactName:Xg});async function o_(e,t){let n=Q_(t.captureWorkflowPath),r=nv(t.baseBranch,`base branch`),i=f(t.outputDir),a=f(t.receiptPath);if(lv(i,a))throw Error(`Trusted receipt must be outside the publicly deployed report directory`);await Z_(a,`Trusted receipt`);let o=u_(t.event,n),s=await e.getWorkflowRun(o.run.id);P_(s,o),await f_(e,s);let c=p_(await e.listRunArtifacts(s.id),o),l=await Y_(t.temporaryRoot),u=!1;try{let d=await g_(e,c.context,33685504),p=f(l,`context`);x_(d),await dg(d,p,__);let m=await E_(f(p,`context.json`)),h=await D_(f(p,`changed-files.json`),m);k_(m,c.context),A_(m,o,s,r),M_(await e.getPullRequest(m.prNumber),m,o,r),await N_(e,m,n);let g=await g_(e,c.report,629145600),_=f(l,`untrusted-report`);S_(g),await dg(g,_,y_),T_(await w_(f(_,`capture-boundary.json`)),c);let ee=await vh(f(_,`report.json`));O_(ee,h),await nf(e,q_(o,m),ee);let v=await Kh({inputDir:_,outputDir:i,trustedHeadBranch:m.head.ref,trustedPullRequest:{repository:m.base.repository,number:m.prNumber,url:`https://github.com/${m.base.repository}/pull/${m.prNumber}`,baseBranch:m.base.ref,headBranch:m.head.ref,workflowRunUrl:`https://github.com/${m.base.repository}/actions/runs/${o.run.id}`},...t.storybookUrl?{storybookUrl:t.storybookUrl}:{},...t.dashboardDir?{dashboardDir:f(t.dashboardDir)}:{}});if(u=!0,!v.report.contentDigest)throw Error(`Trusted report build did not produce an image-bound content digest`);await K_(e,o,s,m,r,n);let y=F_(o,s,m,c,v.report);return await X_(a,y),{receipt:y,report:v.report,reportDirectory:i,reportPath:f(i,`report.json`),receiptPath:a,changedFiles:h}}catch(e){throw u&&await ae(i,{recursive:!0,force:!0}),e}finally{await ae(l,{recursive:!0,force:!0})}}async function s_(e,t,n){let r=await d_(n.receiptPath),i=u_(n.event,r.captureRun.workflowPath);R_(r,i);let a=await e.getWorkflowRun(r.captureRun.id);z_(a,r),await f_(e,a),await B_(e,r,i),M_(await e.getPullRequest(r.context.prNumber),r.context,i,r.context.base.ref),await N_(e,r.context,r.captureRun.workflowPath);let o=await Jh(n.reportPath,r.report.contentDigest);if(o.headBranch!==r.context.head.ref)throw Error(`Trusted report branch does not match its verified pull request context`);let s=q_(i,r.context);return await nf(e,s,o),rf(t,s,o,n.statusContext,n.reportUrl,n.commentLanguage)}async function c_(e,t){let n=Q_(t.captureWorkflowPath),r=nv(t.baseBranch,`base branch`),i=f(t.outputDir),o=f(t.receiptPath);await Z_(i,`Trusted Storybook output`);let s=await d_(o),c=u_(t.event,n);R_(s,c);let l=await e.getWorkflowRun(s.captureRun.id);z_(l,s),await f_(e,l),await B_(e,s,c),M_(await e.getPullRequest(s.context.prNumber),s.context,c,r),await N_(e,s.context,n);let u=f(t.temporaryRoot??a(i));if(lv(i,u))throw Error(`Trusted Storybook temporary root must be outside its output directory`);let d=await Y_(u),p=f(d,`storybook`);try{let t=await g_(e,s.artifacts.headStorybook,536870912);return C_(t),await dg(t,p,b_),await K_(e,c,l,s.context,r,n),await B_(e,s,c),await Z_(i,`Trusted Storybook output`),await y(a(i),{recursive:!0}),await ie(p,i),{receipt:s,receiptPath:o,context:s.context,artifact:s.artifacts.headStorybook,storybookDirectory:i}}finally{await ae(d,{recursive:!0,force:!0})}}async function l_(e,t){let n=await d_(t.receiptPath),r=u_(t.event,n.captureRun.workflowPath);R_(n,r),z_(await e.getWorkflowRun(n.captureRun.id),n);let i=t.trustedArtifactId,a=t.trustedArtifactDigest?W_(t.trustedArtifactDigest):void 0,o=[i,a];if(o.some(e=>e!==void 0)&&o.some(e=>e===void 0))throw Error(`trusted-artifact-id and trusted-artifact-digest must be provided together`);if(i!==void 0&&!av(i))throw Error(`trusted-artifact-id must be a positive integer`);let s=i!==void 0&&a!==void 0?G_():void 0,c=[];for(let t of V_(n)){let n=await e.getArtifact(t.id);n&&(H_(n,t,r),c.push({artifact:n,expected:t}))}if(i!==void 0&&a!==void 0&&s!==void 0){if(V_(n).some(e=>e.id===i))throw Error(`trusted-artifact-id must not duplicate a source artifact ID`);let t=await e.getArtifact(i);t&&(U_(t,a,s,n),c.push({artifact:t,expected:{id:t.id,name:t.name,sizeInBytes:t.sizeInBytes,digest:t.digest}}))}let l=[...new Set(c.map(({artifact:e})=>e.id))];for(let t of l)await e.deleteArtifact(t);return l}function u_(e,t){let n=sv(e,`GitHub workflow_run event`);if(n.action!==`completed`)throw Error(`Kapture trusted run requires a completed workflow_run event`);let r=sv(n.repository,`event repository`),i=$_(r.full_name,`event repository`),a=ev(i),o=iv(r.id,`event repository ID`),s=sv(n.workflow_run,`workflow_run`),c=Q_(rv(s.path,`workflow path`));if(c!==Q_(t))throw Error(`workflow_run path ${c} does not match ${t}`);if(s.status!==`completed`||s.conclusion!==`success`||s.event!==`pull_request`)throw Error(`Kapture trusted run requires one successful pull_request capture run`);let l=sv(s.head_repository,`workflow_run head repository`),u=cv(s.pull_requests,`workflow_run pull_requests`);if(u.length>1)throw Error(`workflow_run must contain at most one pull request`);let d=u[0]?J_(u[0]):void 0;return{repository:{id:o,fullName:i,ref:a},run:{id:iv(s.id,`workflow run ID`),runNumber:iv(s.run_number,`workflow run number`),attempt:iv(s.run_attempt,`workflow run attempt`),workflowId:iv(s.workflow_id,`workflow ID`),workflowPath:c,status:`completed`,conclusion:`success`,event:`pull_request`,headSha:tv(s.head_sha,`workflow run head SHA`),headBranch:nv(s.head_branch,`workflow run head branch`),headRepository:{id:iv(l.id,`workflow run head repository ID`),fullName:$_(l.full_name,`workflow run head repository`)}},...d?{pullRequest:d}:{}}}async function d_(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size<1||n.size>65536)throw Error(`Trusted receipt must be a file no larger than 65536 bytes`);let r;try{r=JSON.parse(await x(t,`utf8`))}catch{throw Error(`Trusted receipt does not contain valid JSON`)}let i=a_.safeParse(r);if(!i.success){let e=i.error.issues[0];throw Error(`Invalid trusted receipt${e?.path.length?` at ${e.path.join(`.`)}`:``}: ${e?.message??`unknown error`}`)}return L_(i.data),i.data}async function f_(e,t){let n=(await e.listWorkflowRuns(t.workflowId,t.headBranch)).filter(e=>e.headRepositoryId===t.headRepository.id).reduce((e,t)=>e?t.runNumber===e.runNumber?t.id>e.id?t:e:t.runNumber>e.runNumber?t:e:t,void 0);if(!n||n.id!==t.id)throw Error(`A newer Kapture capture run owns this repository and branch`)}function p_(e,t){let n=/^kapture-context-pr-([1-9][0-9]*)-base-([0-9a-f]{40})-head-([0-9a-f]{40})$/,r=e.filter(e=>n.test(e.name)?h_(e,t):!1);if(r.length!==1||!r[0])throw Error(`Triggering run must contain exactly one immutable Kapture context artifact`);let i=r[0];if(i.sizeInBytes>33685504)throw Error(`Kapture context artifact exceeds its compressed size limit`);let a=i.name.match(n);if(!a?.[1]||!a[2]||!a[3])throw Error(`Kapture context artifact name is invalid`);let o=`kapture-visual-report-pr-${a[1]}-base-${a[2]}-head-${a[3]}`,s=e.filter(e=>e.name===o&&h_(e,t));if(s.length!==1||!s[0])throw Error(`Triggering run must contain exactly one matching Kapture report artifact`);if(s[0].sizeInBytes>629145600)throw Error(`Kapture report artifact exceeds its compressed size limit`);let c=`pr-${a[1]}-base-${a[2]}-head-${a[3]}`,l=m_(e,`kapture-storybook-base-${c}`,t),u=m_(e,`kapture-storybook-head-${c}`,t),d=[i,l,u,s[0]];if(new Set(d.map(e=>e.id)).size!==d.length||new Set(d.map(e=>e.name)).size!==d.length)throw Error(`Kapture artifact IDs and names must be distinct`);return{context:i,baseStorybook:l,headStorybook:u,report:s[0]}}function m_(e,t,n){let r=e.filter(e=>e.name===t&&h_(e,n));if(r.length!==1||!r[0])throw Error(`Triggering run must contain exactly one non-expired ${t} artifact`);if(r[0].sizeInBytes>536870912)throw Error(`${t} exceeds its compressed size limit`);return r[0]}function h_(e,t){return!e.expired&&e.workflowRun.id===t.run.id&&e.workflowRun.repositoryId===t.repository.id&&e.workflowRun.headRepositoryId===t.run.headRepository.id&&e.workflowRun.headBranch===t.run.headBranch&&e.workflowRun.headSha===t.run.headSha&&Gg.test(e.digest)&&av(e.id)&&av(e.sizeInBytes)}async function g_(e,t,n){let r=await e.downloadArtifactArchive(t.id,n);if(r.byteLength!==t.sizeInBytes)throw Error(`Artifact ${t.id} download size does not match GitHub metadata`);if(`sha256:${m(`sha256`).update(r).digest(`hex`)}`!==t.digest)throw Error(`Artifact ${t.id} download digest does not match GitHub metadata`);return r}const __={maxEntries:2,maxFileBytes:33554432,maxTotalBytes:33619968,allowPath:e=>e===`context.json`||e===`changed-files.json`,allowDirectoryPath:()=>!1},v_=new Set([`images/`,`images/base/`,`images/head/`,`images/diff/`]),y_={maxEntries:60006,maxFileBytes:Vh,maxTotalBytes:629145600,allowPath:e=>e===`report.json`||e===`capture-boundary.json`||Yg.test(e),allowDirectoryPath:e=>v_.has(e)},b_={maxEntries:2e4,maxFileBytes:26214400,maxTotalBytes:1073741824,allowPath:()=>!0,allowDirectoryPath:()=>!0};function x_(e){let t=ug(e,__);if(t.length!==2)throw Error(`Context archive must contain exactly context.json and changed-files.json`);let n=t.find(e=>e.path===`context.json`),r=t.find(e=>e.path===`changed-files.json`);if(!n||n.uncompressedBytes<1||n.uncompressedBytes>65536||!r||r.uncompressedBytes<1||r.uncompressedBytes>33554432)throw Error(`Context archive entries are outside their fixed size contract`)}function S_(e){let t=ug(e,y_),n=new Set,r=0,i=0;for(let e of t){let t=e.path.toLocaleLowerCase(`en-US`);if(n.has(t))throw Error(`Report archive contains a case-insensitive duplicate: ${e.path}`);if(n.add(t),e.uncompressedBytes<1)throw Error(`Report archive contains an empty file: ${e.path}`);if(e.path===`report.json`&&(r+=1,e.uncompressedBytes>10485760))throw Error(`report.json exceeds its uncompressed size limit`);if(e.path===`capture-boundary.json`&&(i+=1,e.uncompressedBytes>65536))throw Error(`capture-boundary.json exceeds its uncompressed size limit`)}if(r!==1)throw Error(`Report archive must contain one root report.json file`);if(i!==1)throw Error(`Report archive must contain one root capture-boundary.json file`)}function C_(e){let t=ug(e,b_),n=new Set,r=0;for(let e of t){let t=e.path.toLocaleLowerCase(`en-US`);if(n.has(t))throw Error(`Storybook archive contains a case-insensitive duplicate: ${e.path}`);n.add(t),e.path===`index.html`&&e.uncompressedBytes>0&&(r+=1)}if(r!==1)throw Error(`Storybook archive must contain one non-empty root index.html file`)}async function w_(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch(e){throw Error(`capture-boundary.json must contain valid JSON`,{cause:e})}return i_.parse(t)}function T_(e,t){for(let n of[`context`,`baseStorybook`,`headStorybook`]){let r=e.artifacts[n],i=t[n];if(i.id!==r.id||i.name!==r.name||i.digest!==r.digest)throw Error(`Capture ${n} artifact does not match its exact downloaded identity`)}}async function E_(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch{throw Error(`Kapture context artifact does not contain valid JSON`)}let n=t_.safeParse(t);if(!n.success){let e=n.error.issues[0];throw Error(`Invalid Kapture capture context${e?.path.length?` at ${e.path.join(`.`)}`:``}: ${e?.message??`unknown error`}`)}if(n.data.preview.branch!==n.data.head.ref||n.data.preview.alias!==bg(n.data.prNumber,n.data.head.ref))throw Error(`Kapture context preview identity is not derived from its pull request branch`);return n.data}async function D_(e,t){let n=await oe(e);if(!n.isFile()||n.size<1||n.size>33554432)throw Error(`changed-files.json is outside its fixed size contract`);let r;try{r=JSON.parse(await x(e,`utf8`))}catch{throw Error(`changed-files.json does not contain valid JSON`)}let i=kg(r);if(i.pullRequest.number!==t.prNumber||i.pullRequest.baseSha!==t.base.sha||i.pullRequest.headSha!==t.head.sha)throw Error(`changed-files.json does not belong to the exact capture context`);return i}function O_(e,t){let n=e.coverage;if(!n)throw Error(`Trusted workflow reports must include audited story coverage`);let r=n.changedFilesEvidence;if(!r)throw Error(`Trusted workflow report coverage must include changed-files evidence`);let i=m(`sha256`).update(JSON.stringify(t)).digest(`hex`);if(r.provider!==t.source.provider||r.manifestDigest!==i||r.pullRequestNumber!==t.pullRequest.number||r.baseSha!==t.pullRequest.baseSha||r.headSha!==t.pullRequest.headSha)throw Error(`Trusted workflow report changed-files evidence does not match its verified context manifest`)}function k_(e,t){let n=`kapture-context-${yg(e)}`;if(t.name!==n)throw Error(`Kapture context contents do not match the immutable artifact name`)}function A_(e,t,n,r){if(e.runId!==n.id||e.base.repository!==t.repository.fullName||e.base.ref!==r||e.head.repository!==n.headRepository.fullName||e.head.repositoryId!==n.headRepository.id||e.head.ref!==n.headBranch)throw Error(`Kapture capture context does not belong to the triggering workflow run`);j_(t,e)}function j_(e,t){let n=e.pullRequest;if(n&&(n.number!==t.prNumber||n.base.repositoryId!==e.repository.id||n.base.ref!==t.base.ref||n.base.sha!==t.base.sha||n.head.repositoryId!==t.head.repositoryId||n.head.ref!==t.head.ref||n.head.sha!==t.head.sha))throw Error(`workflow_run pull request metadata conflicts with the capture context`)}function M_(e,t,n,r){if(e.number!==t.prNumber||e.state!==`open`||e.base.repository.id!==n.repository.id||e.base.repository.fullName!==t.base.repository||e.base.ref!==r||e.base.sha!==t.base.sha||e.head.repository.id!==t.head.repositoryId||e.head.repository.fullName!==t.head.repository||e.head.ref!==t.head.ref||e.head.sha!==t.head.sha)throw Error(`Kapture artifacts are stale or do not belong to the current open pull request`);j_(n,t)}async function N_(e,t,n){let[r,i]=await Promise.all([e.getContentSha(t.base.repository,n,t.base.sha),e.getContentSha(t.head.repository,n,t.head.sha)]);if(!Wg.test(r)||i!==r)throw Error(`Pull requests that modify the capture workflow require separate review before publishing`)}function P_(e,t){if(e.id!==t.run.id||e.runNumber!==t.run.runNumber||e.runAttempt!==t.run.attempt||e.workflowId!==t.run.workflowId||e.path!==t.run.workflowPath||e.status!==`completed`||e.conclusion!==`success`||e.event!==`pull_request`||e.headSha!==t.run.headSha||e.headBranch!==t.run.headBranch||e.headRepository.id!==t.run.headRepository.id||e.headRepository.fullName!==t.run.headRepository.fullName||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Triggering capture run metadata changed or no longer matches the event`)}function F_(e,t,n,r,i){if(!i.contentDigest)throw Error(`Trusted report is missing contentDigest`);if(i.headBranch!==n.head.ref)throw Error(`Trusted report branch does not match its verified pull request context`);let a=yg(n);return{schemaVersion:2,repository:{id:e.repository.id,fullName:e.repository.fullName},context:n,captureRun:{id:t.id,runNumber:t.runNumber,attempt:t.runAttempt,workflowId:t.workflowId,workflowPath:t.path,headSha:t.headSha,headBranch:t.headBranch,headRepositoryId:t.headRepository.id,headRepository:t.headRepository.fullName},artifacts:{context:I_(r.context),baseStorybook:I_(r.baseStorybook),headStorybook:I_(r.headStorybook),report:I_(r.report)},report:{contentDigest:i.contentDigest},trustedArtifactName:`kapture-trusted-report-${a}`}}function I_(e){return{id:e.id,name:e.name,sizeInBytes:e.sizeInBytes,digest:e.digest}}function L_(e){let t=yg(e.context);if(e.context.runId!==e.captureRun.id||e.context.base.repository!==e.repository.fullName||e.context.head.repository!==e.captureRun.headRepository||e.context.head.repositoryId!==e.captureRun.headRepositoryId||e.context.head.ref!==e.captureRun.headBranch||e.context.preview.branch!==e.context.head.ref||e.context.preview.alias!==bg(e.context.prNumber,e.context.head.ref)||e.artifacts.context.name!==`kapture-context-${t}`||e.artifacts.baseStorybook.name!==`kapture-storybook-base-${t}`||e.artifacts.headStorybook.name!==`kapture-storybook-head-${t}`||e.artifacts.report.name!==`kapture-visual-report-${t}`||e.trustedArtifactName!==`kapture-trusted-report-${t}`||new Set(V_(e).map(e=>e.id)).size!==4||new Set(V_(e).map(e=>e.name)).size!==4||e.artifacts.context.sizeInBytes>33685504||e.artifacts.baseStorybook.sizeInBytes>536870912||e.artifacts.headStorybook.sizeInBytes>536870912||e.artifacts.report.sizeInBytes>629145600||!Jg.test(e.captureRun.workflowPath))throw Error(`Trusted receipt fields are not internally consistent`)}function R_(e,t){if(L_(e),e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName||e.captureRun.id!==t.run.id||e.captureRun.runNumber!==t.run.runNumber||e.captureRun.attempt!==t.run.attempt||e.captureRun.workflowId!==t.run.workflowId||e.captureRun.workflowPath!==t.run.workflowPath||e.captureRun.headSha!==t.run.headSha||e.captureRun.headBranch!==t.run.headBranch||e.captureRun.headRepositoryId!==t.run.headRepository.id||e.captureRun.headRepository!==t.run.headRepository.fullName)throw Error(`Trusted receipt does not belong to the triggering workflow_run event`);j_(t,e.context)}function z_(e,t){if(e.id!==t.captureRun.id||e.runNumber!==t.captureRun.runNumber||e.runAttempt!==t.captureRun.attempt||e.workflowId!==t.captureRun.workflowId||e.path!==t.captureRun.workflowPath||e.status!==`completed`||e.conclusion!==`success`||e.event!==`pull_request`||e.headSha!==t.captureRun.headSha||e.headBranch!==t.captureRun.headBranch||e.headRepository.id!==t.captureRun.headRepositoryId||e.headRepository.fullName!==t.captureRun.headRepository||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Capture run changed after prepare-run verification`)}async function B_(e,t,n){let r=await e.listRunArtifacts(t.captureRun.id);for(let e of V_(t)){let t=r.filter(t=>t.id===e.id);if(t.length!==1||!t[0])throw Error(`Receipt-bound artifact ${e.id} is no longer available`);H_(t[0],e,n)}}function V_(e){return[e.artifacts.context,e.artifacts.baseStorybook,e.artifacts.headStorybook,e.artifacts.report]}function H_(e,t,n){if(e.id!==t.id||e.name!==t.name||e.sizeInBytes!==t.sizeInBytes||e.digest!==t.digest||!h_(e,n))throw Error(`Artifact ${t.id} no longer matches its trusted receipt binding`)}function U_(e,t,n,r){if(e.expired||e.name!==r.trustedArtifactName||e.digest!==t||e.workflowRun.id!==n||e.workflowRun.repositoryId!==r.repository.id||e.workflowRun.headRepositoryId!==r.repository.id||e.sizeInBytes>629145600)throw Error(`Trusted report artifact does not match the exact cleanup binding`)}function W_(e){let t=e.startsWith(`sha256:`)?e:`sha256:${e}`;if(!Gg.test(t))throw Error(`trusted-artifact-digest must be a 64-character SHA-256 digest`);return t}function G_(){let e=process.env.GITHUB_RUN_ID;if(!e||!/^[1-9][0-9]*$/.test(e))throw Error(`GITHUB_RUN_ID must identify the current trusted reporter workflow run`);let t=Number(e);if(!Number.isSafeInteger(t))throw Error(`GITHUB_RUN_ID must be a safe positive integer`);return t}async function K_(e,t,n,r,i,a){let o=await e.getWorkflowRun(n.id);P_(o,t),await f_(e,o),M_(await e.getPullRequest(r.prNumber),r,t,i),await N_(e,r,a)}function q_(e,t){return{repository:e.repository.ref,issueNumber:t.prNumber,headSha:t.head.sha,captureRunId:e.run.id,captureRunAttempt:e.run.attempt,captureWorkflowId:e.run.workflowId,captureRunHeadBranch:e.run.headBranch,captureRunHeadRepositoryId:e.run.headRepository.id}}function J_(e){let t=sv(e,`workflow_run pull request`),n=sv(t.base,`workflow_run pull request base`),r=sv(t.head,`workflow_run pull request head`);return{number:iv(t.number,`workflow_run pull request number`),base:{repositoryId:iv(sv(n.repo,`workflow_run pull request base repository`).id,`workflow_run pull request base repository ID`),ref:nv(n.ref,`workflow_run pull request base ref`),sha:tv(n.sha,`workflow_run pull request base SHA`)},head:{repositoryId:iv(sv(r.repo,`workflow_run pull request head repository`).id,`workflow_run pull request head repository ID`),ref:nv(r.ref,`workflow_run pull request head ref`),sha:tv(r.sha,`workflow_run pull request head SHA`)}}}async function Y_(e){let t=f(e??process.env.RUNNER_TEMP??de());return await y(t,{recursive:!0}),te(`${t}${p}kapture-prepare-`)}async function X_(e,t){let n=f(e),r=f(n,`..`);await y(r,{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`})}async function Z_(e,t){try{await oe(e)}catch(e){if(e.code===`ENOENT`)return;throw e}throw Error(`${t} already exists: ${e}`)}function Q_(e){if(!Jg.test(e)||e.includes(`//`)||e.includes(`..`))throw Error(`capture-workflow-path must be a safe .github/workflows YAML path`);return e}function $_(e,t){let n=rv(e,`${t} full name`);if(!qg.test(n))throw Error(`${t} full name is invalid`);return n}function ev(e){let[t,n,...r]=e.split(`/`);if(!t||!n||r.length>0)throw Error(`Repository full name is invalid`);return{owner:t,repo:n}}function tv(e,t){let n=rv(e,t);if(!Wg.test(n))throw Error(`${t} must be a lowercase full SHA`);return n}function nv(e,t){let n=rv(e,t);if(ov(n))throw Error(`${t} contains control characters`);return n}function rv(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);return e}function iv(e,t){if(!av(e))throw Error(`${t} must be a positive integer`);return e}function av(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function ov(e){return Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function sv(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function cv(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}function lv(e,t){let n=d(e,t);return n===``||!s(n)&&n!==`..`&&!n.startsWith(`..${p}`)}var uv=class{#e;#t;#n;constructor(e,t,n=fetch){if(!e)throw Error(`GITHUB_TOKEN is required`);this.#e=e,this.#t=t,this.#n=n}async getWorkflowRun(e){return fv(await this.#i(`GET`,`${this.#r()}/actions/runs/${e}`))}async listWorkflowRuns(e,t){let n=[];for(let r=1;r<=10;r+=1){let i=new URLSearchParams({event:`pull_request`,branch:t,per_page:`100`,page:String(r)}),a=yv(vv(await this.#i(`GET`,`${this.#r()}/actions/workflows/${e}/runs?${i}`),`workflow runs response`).workflow_runs,`workflow_runs`).map(pv);if(n.push(...a),a.length<100)return n}throw Error(`GitHub returned more than 1000 workflow runs`)}async listRunArtifacts(e){let t=[];for(let n=1;n<=10;n+=1){let r=new URLSearchParams({per_page:`100`,page:String(n)}),i=yv(vv(await this.#i(`GET`,`${this.#r()}/actions/runs/${e}/artifacts?${r}`),`artifacts response`).artifacts,`artifacts`).map(mv);if(t.push(...i),i.length<100)return t}throw Error(`GitHub returned more than 1000 workflow artifacts`)}async getArtifact(e){let t=await this.#o(`GET`,`${this.#r()}/actions/artifacts/${e}`);return t.status===404?null:(await dv(t,`GET`,`/actions/artifacts/${e}`),mv(await t.json()))}async downloadArtifactArchive(e,t){if(!Number.isSafeInteger(t)||t<=0)throw Error(`Artifact download byte limit must be positive`);let n=await this.#o(`GET`,`${this.#r()}/actions/artifacts/${e}/zip`,`manual`),r=await this.#a(n,e);await dv(r,`GET`,`/actions/artifacts/${e}/zip`);let i=r.headers.get(`content-length`);if(i!==null){let n=Number(i);if(!Number.isSafeInteger(n)||n<0||n>t)throw Error(`Artifact ${e} exceeds the ${t} byte download limit`)}if(!r.body)throw Error(`Artifact ${e} download returned no body`);let a=r.body.getReader(),o=[],s=0;try{for(;;){let{done:n,value:r}=await a.read();if(n)break;if(s+=r.byteLength,s>t)throw await a.cancel(),Error(`Artifact ${e} exceeds the ${t} byte download limit`);o.push(Buffer.from(r))}}finally{a.releaseLock()}if(s<1)throw Error(`Artifact ${e} download is empty`);return Buffer.concat(o,s)}async deleteArtifact(e){let t=await this.#o(`DELETE`,`${this.#r()}/actions/artifacts/${e}`);t.status!==404&&await dv(t,`DELETE`,`/actions/artifacts/${e}`)}async getPullRequest(e){return hv(await this.#i(`GET`,`${this.#r()}/pulls/${e}`))}async listOpenPullRequestsForHead(e,t,n){let r=_v(e),i=[];for(let e=1;e<=10;e+=1){let a=new URLSearchParams({state:`open`,base:n,head:`${r.owner}:${t}`,per_page:`100`,page:String(e)}),o=yv(await this.#i(`GET`,`${this.#r()}/pulls?${a}`),`pull requests response`).map(hv);if(i.push(...o),o.length<100)return i}throw Error(`GitHub returned more than 1000 matching pull requests`)}async getContentSha(e,t,n){let r=_v(e),i=t.split(`/`).map(encodeURIComponent).join(`/`),a=new URLSearchParams({ref:n});return Cv(vv(await this.#i(`GET`,`/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/contents/${i}?${a}`),`contents response`).sha,`contents SHA`)}#r(){let{owner:e,repo:t}=this.#t;return`/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}async#i(e,t){let n=await this.#o(e,t);return await dv(n,e,t),n.json()}async#a(e,t){if(e.status<300||e.status>399)return e;let n=e.headers.get(`location`);if(!n)throw Error(`Artifact ${t} redirect is missing its location`);let r;try{r=new URL(n)}catch{throw Error(`Artifact ${t} redirect location is invalid`)}if(r.protocol!==`https:`||r.username||r.password)throw Error(`Artifact ${t} redirect must be a credential-free HTTPS URL`);return this.#n(r,{method:`GET`,headers:{Accept:`application/octet-stream`,"User-Agent":`kapture-cli`},redirect:`follow`})}#o(e,t,n=`follow`){return this.#n(`https://api.github.com${t}`,{method:e,headers:{Accept:`application/vnd.github+json`,Authorization:`Bearer ${this.#e}`,"X-GitHub-Api-Version":`2022-11-28`,"User-Agent":`kapture-cli`},redirect:n})}};async function dv(e,t,n){if(!e.ok)throw Error(`GitHub API ${t} ${n} failed with status ${e.status}`)}function fv(e){let t=vv(e,`workflow run`);return{id:$(t.id,`workflow run ID`),runNumber:$(t.run_number,`workflow run number`),runAttempt:$(t.run_attempt,`workflow run attempt`),workflowId:$(t.workflow_id,`workflow ID`),path:bv(t.path,`workflow path`),status:bv(t.status,`workflow run status`),conclusion:xv(t.conclusion,`workflow run conclusion`),event:bv(t.event,`workflow run event`),headSha:Cv(t.head_sha,`workflow run head SHA`),headBranch:bv(t.head_branch,`workflow run head branch`),headRepository:gv(t.head_repository,`workflow run head repository`),repository:gv(t.repository,`workflow run repository`)}}function pv(e){let t=vv(e,`workflow run candidate`);return{id:$(t.id,`workflow run ID`),runNumber:$(t.run_number,`workflow run number`),headRepositoryId:$(vv(t.head_repository,`workflow run head repository`).id,`workflow run head repository ID`)}}function mv(e){let t=vv(e,`workflow artifact`),n=vv(t.workflow_run,`artifact workflow run`);return{id:$(t.id,`artifact ID`),name:bv(t.name,`artifact name`),sizeInBytes:$(t.size_in_bytes,`artifact size`),digest:wv(t.digest,`artifact digest`),expired:Sv(t.expired,`artifact expired`),workflowRun:{id:$(n.id,`artifact workflow run ID`),repositoryId:$(n.repository_id,`artifact workflow repository ID`),headRepositoryId:$(n.head_repository_id,`artifact workflow head repository ID`),headBranch:bv(n.head_branch,`artifact workflow head branch`),headSha:Cv(n.head_sha,`artifact workflow head SHA`)}}}function hv(e){let t=vv(e,`pull request`),n=vv(t.base,`pull request base`),r=vv(t.head,`pull request head`),i=bv(t.state,`pull request state`);if(i!==`open`&&i!==`closed`)throw Error(`Pull request state is invalid`);return{number:$(t.number,`pull request number`),state:i,base:{ref:bv(n.ref,`pull request base ref`),sha:Cv(n.sha,`pull request base SHA`),repository:gv(n.repo,`pull request base repository`)},head:{ref:bv(r.ref,`pull request head ref`),sha:Cv(r.sha,`pull request head SHA`),repository:gv(r.repo,`pull request head repository`)}}}function gv(e,t){let n=vv(e,t),r=bv(n.full_name,`${t} full name`);return _v(r),{id:$(n.id,`${t} ID`),fullName:r}}function _v(e){let t=e.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!t?.[1]||!t[2])throw Error(`Repository full name is invalid`);return{owner:t[1],repo:t[2]}}function vv(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function yv(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}function $(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}function bv(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);for(let n of e){let e=n.codePointAt(0)??0;if(e<=31||e===127)throw Error(`${t} contains control characters`)}return e}function xv(e,t){return e===null?null:bv(e,t)}function Sv(e,t){if(typeof e!=`boolean`)throw Error(`${t} must be a boolean`);return e}function Cv(e,t){if(typeof e!=`string`||!/^[0-9a-f]{40}$/.test(e))throw Error(`${t} must be a lowercase full SHA`);return e}function wv(e,t){if(typeof e!=`string`||!/^sha256:[0-9a-f]{64}$/.test(e))throw Error(`${t} must be a SHA-256 digest`);return e}E();const Tv=T({meta:{name:`cleanup`,description:`Delete only exact receipt-bound Kapture artifact IDs`},args:{receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},"trusted-artifact-id":{type:`string`,description:`Exact current trusted report artifact ID`},"trusted-artifact-digest":{type:`string`,description:`upload-artifact SHA-256 digest for the current trusted report artifact`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=Dv(n),i=e[`trusted-artifact-id`]?Ev(e[`trusted-artifact-id`],`trusted-artifact-id`):void 0,a=await l_(new uv(t,r),{event:n,receiptPath:f(e.receipt),...i===void 0?{}:{trustedArtifactId:i},...e[`trusted-artifact-digest`]?{trustedArtifactDigest:e[`trusted-artifact-digest`]}:{}});await sf({"deleted-artifact-count":a.length,"deleted-artifact-ids":a.join(`,`)})}});function Ev(e,t){if(!/^[1-9][0-9]*$/.test(e))throw Error(`${t} must be a positive integer`);let n=Number(e);if(!Number.isSafeInteger(n))throw Error(`${t} must be a safe integer`);return n}function Dv(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const Ov=T({meta:{name:`context`,description:`Validate a pull request event and write immutable Kapture capture context`},args:{output:{type:`string`,required:!0,description:`Path for the normalized context JSON`},"changed-files-output":{type:`string`,required:!0,description:`Path for the versioned changed-files manifest`},"base-branch":{type:`string`,description:`Expected pull request base branch`}},async run({args:e}){let t=vg(await Kd(),e[`base-branch`]),n=process.env.GITHUB_TOKEN;if(!n)throw Error(`GITHUB_TOKEN is required`);let[r,i]=t.base.repository.split(`/`);if(!r||!i)throw Error(`Capture context repository is invalid`);let o=await Og(new Ud(n,{owner:r,repo:i}),t),s=f(e.output),c=f(e[`changed-files-output`]);if(s===c)throw Error(`output and changed-files-output must be different paths`);await Promise.all([y(a(s),{recursive:!0}),y(a(c),{recursive:!0})]),await Promise.all([se(s,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`}),se(c,`${JSON.stringify(o,null,2)}\n`,{flag:`wx`})]),await sf({"artifact-suffix":yg(t),"base-repository":t.base.repository,"base-ref":t.base.ref,"base-sha":t.base.sha,"changed-files-complete":String(o.complete),"changed-files-count":o.files.length,"changed-files-path":c,"context-path":s,"head-repository":t.head.repository,"head-repository-id":t.head.repositoryId,"head-ref":t.head.ref,"head-sha":t.head.sha,"pr-number":t.prNumber,"preview-branch":t.preview.branch,"preview-alias":t.preview.alias})}}),kv=/^[0-9a-f]{40}$/,Av=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,jv=/^\.github\/workflows\/[A-Za-z0-9_./-]+\.ya?ml$/,Mv=`Base branch changed; rerun visual capture`,Nv=new Set([`action_required`,`cancelled`,`failure`,`neutral`,`skipped`,`stale`,`startup_failure`,`success`,`timed_out`]);async function Pv(e,t,n){let r=ey(n.captureWorkflowPath),i=iy(n.baseBranch,`base branch`),a=Md(n.statusContext),o=Lv(n.event,r),s=await Rv(e,o,i);if(!s.ok)return Zv(s.reason);if(await Uv(t,o,s.target))return Zv(`final-report-exists`,s.target);let c=await Rv(e,o,i);if(!c.ok)return Zv(c.reason,s.target);if(!Xv(s.target,c.target))return Zv(`pull-request-changed`,c.target);if(await Uv(t,o,c.target))return Zv(`final-report-exists`,c.target);let l=Jv(o,c.target);return await t.setReviewStatus(c.target.headSha,l.state,l.description,a),{status:l.state,reason:`status-written`,prNumber:c.target.prNumber,headSha:c.target.headSha}}async function Fv(e,t,n){let r=ey(n.captureWorkflowPath),i=iy(n.baseBranch,`base branch`),a=Md(n.statusContext),o=Iv(n.event,r),s=await Rv(e,o,i);if(!s.ok)return Qv(s.reason);let c=Gv(o,await Wv(t,o,s.target,a),s.target);if(c)return Qv(c,s.target);let l=await Rv(e,o,i);if(!l.ok)return Qv(l.reason,s.target);if(!Xv(s.target,l.target))return Qv(`pull-request-changed`,l.target);let u=Gv(o,await Wv(t,o,l.target,a),l.target);if(u)return Qv(u,l.target);let d=l.target.baseDrift?Mv:o.run.conclusion===`success`?`Visual report publication did not complete`:`Visual capture did not succeed (${o.run.conclusion})`;return await t.setReviewStatus(l.target.headSha,`error`,d,a),{status:`error`,reason:`status-written`,prNumber:l.target.prNumber,headSha:l.target.headSha}}function Iv(e,t){let n=Lv(e,t);if(n.run.status!==`completed`)throw Error(`Kapture finalize-run requires a completed workflow_run event`);return{...n,run:{...n.run,status:`completed`}}}function Lv(e,t){let n=ly(e,`GitHub workflow_run event`),r=oy(n.action,`workflow_run action`);if(r!==`in_progress`&&r!==`completed`)throw Error(`Kapture reconcile-run requires an in_progress or completed workflow_run event`);let i=ly(n.repository,`event repository`),a=ty(i.full_name,`event repository`),o=sy(i.id,`event repository ID`),s=ly(n.workflow_run,`workflow_run`),c=ey(oy(s.path,`workflow path`));if(c!==ey(t))throw Error(`workflow_run path ${c} does not match ${t}`);if(s.event!==`pull_request`)throw Error(`Kapture reconcile-run requires a pull_request capture run`);let l=oy(s.status,`workflow run status`),u=ay(s.conclusion,`workflow run conclusion`);if(r===`in_progress`&&(l!==`in_progress`||u!==null))throw Error(`An in_progress workflow_run event must describe an unfinished run`);if(r===`completed`&&(l!==`completed`||u===null||!Nv.has(u)))throw Error(`A completed workflow_run event must have a supported conclusion`);let d=ly(s.head_repository,`workflow_run head repository`),f={id:sy(d.id,`workflow run head repository ID`),fullName:ty(d.full_name,`workflow run head repository`)},p=iy(s.head_branch,`workflow run head branch`),m=uy(s.pull_requests,`workflow_run pull requests`);if(m.length>1)throw Error(`workflow_run must contain at most one pull request`);let h=m[0]?$v(m[0]):void 0;if(h&&(h.base.repositoryId!==o||h.head.repositoryId!==f.id||h.head.ref!==p))throw Error(`workflow_run pull request metadata conflicts with run provenance`);return{repository:{id:o,fullName:a,ref:ny(a)},run:{id:sy(s.id,`workflow run ID`),runNumber:sy(s.run_number,`workflow run number`),attempt:sy(s.run_attempt,`workflow run attempt`),workflowId:sy(s.workflow_id,`workflow ID`),workflowPath:c,status:l,conclusion:u,event:`pull_request`,headSha:ry(s.head_sha,`workflow run head SHA`),headBranch:p,headRepository:f},...h?{pullRequest:h}:{}}}async function Rv(e,t,n){let r=await e.getWorkflowRun(t.run.id);return zv(r,t),r.runAttempt===t.run.attempt?r.status!==t.run.status||r.conclusion!==t.run.conclusion?{ok:!1,reason:`stale-run-state`}:await Bv(e,r)?Vv(e,t,n):{ok:!1,reason:`superseded-run`}:{ok:!1,reason:`stale-run-attempt`}}function zv(e,t){if(e.id!==t.run.id||e.runNumber!==t.run.runNumber||e.workflowId!==t.run.workflowId||ey(e.path)!==t.run.workflowPath||e.event!==`pull_request`||e.headSha!==t.run.headSha||e.headBranch!==t.run.headBranch||e.headRepository.id!==t.run.headRepository.id||e.headRepository.fullName!==t.run.headRepository.fullName||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Triggering capture run identity no longer matches the workflow_run event`)}async function Bv(e,t){let n=(await e.listWorkflowRuns(t.workflowId,t.headBranch)).filter(e=>e.headRepositoryId===t.headRepository.id);if(n.filter(e=>e.id===t.id).some(e=>e.runNumber!==t.runNumber))throw Error(`Latest workflow run metadata conflicts with the triggering run`);return n.reduce((e,t)=>e?t.runNumber===e.runNumber?t.id>e.id?t:e:t.runNumber>e.runNumber?t:e:t,void 0)?.id===t.id}async function Vv(e,t,n){if(t.pullRequest){if(t.pullRequest.base.ref!==n)return{ok:!1,reason:`base-branch-mismatch`};let r=await e.getPullRequest(t.pullRequest.number);return Hv(r,t,n)?{ok:!0,target:Yv(r,r.base.sha!==t.pullRequest.base.sha)}:{ok:!1,reason:`pull-request-not-current`}}let r=(await e.listOpenPullRequestsForHead(t.run.headRepository.fullName,t.run.headBranch,n)).filter(e=>e.state===`open`&&e.base.repository.id===t.repository.id&&e.base.repository.fullName===t.repository.fullName&&e.base.ref===n&&e.head.repository.id===t.run.headRepository.id&&e.head.repository.fullName===t.run.headRepository.fullName&&e.head.ref===t.run.headBranch);return r.length===0?{ok:!1,reason:`pull-request-not-found`}:r.length===1?{ok:!0,target:Yv(r[0])}:{ok:!1,reason:`pull-request-ambiguous`}}function Hv(e,t,n){let r=t.pullRequest;return!!(r&&e.number===r.number&&e.state===`open`&&e.base.repository.id===t.repository.id&&e.base.repository.fullName===t.repository.fullName&&e.base.ref===n&&e.head.repository.id===t.run.headRepository.id&&e.head.repository.fullName===t.run.headRepository.fullName&&e.head.ref===t.run.headBranch&&e.head.sha===r.head.sha)}async function Uv(e,t,n){return qv(await e.findCurrentReportMarker(n.prNumber,n.baseSha,n.headSha),t)}async function Wv(e,t,n,r){let i=await e.findCurrentReportMarker(n.prNumber,n.baseSha,n.headSha),a=await e.getLatestReviewStatus(n.headSha,r);return{marker:qv(i,t)?i:null,status:a}}function Gv(e,t,n){return n.baseDrift&&t.status?.state===`error`&&t.status.description===Mv?`base-drift-already-recorded`:e.run.conclusion===`success`?Kv(t)?`final-report-exists`:t.status?.state===`error`&&t.status.description===`Visual report publication did not complete`?`publication-failure-already-recorded`:void 0:t.status?.state===`error`?`capture-failure-already-recorded`:void 0}function Kv(e){let{marker:t,status:n}=e;return!t?.reportUrl||!n||t.reportUrl!==n.targetUrl?!1:t.status===`clean`?n.state===`success`&&n.description===`No visual changes`:t.status===`changed`?n.state===`pending`&&n.description===`Visual changes require approval`:n.state===`failure`}function qv(e,t){return!!(e&&e.captureRunId===t.run.id&&e.captureRunAttempt===t.run.attempt&&e.captureWorkflowId===t.run.workflowId&&e.captureRunHeadBranch===t.run.headBranch&&e.captureRunHeadRepositoryId===t.run.headRepository.id)}function Jv(e,t){return t.baseDrift?{state:`error`,description:Mv}:e.run.status===`in_progress`?{state:`pending`,description:`Visual capture is in progress`}:e.run.conclusion===`success`?{state:`pending`,description:`Visual report is awaiting publication`}:{state:`error`,description:`Visual capture did not succeed (${e.run.conclusion})`}}function Yv(e,t=!1){return{prNumber:e.number,baseSha:e.base.sha,headSha:e.head.sha,baseDrift:t}}function Xv(e,t){return e.prNumber===t.prNumber&&e.baseSha===t.baseSha&&e.headSha===t.headSha&&e.baseDrift===t.baseDrift}function Zv(e,t){return{status:`noop`,reason:e,...t?{prNumber:t.prNumber,headSha:t.headSha}:{}}}function Qv(e,t){return{status:`noop`,reason:e,...t?{prNumber:t.prNumber,headSha:t.headSha}:{}}}function $v(e){let t=ly(e,`workflow_run pull request`),n=ly(t.base,`workflow_run pull request base`),r=ly(t.head,`workflow_run pull request head`);return{number:sy(t.number,`workflow_run pull request number`),base:{repositoryId:sy(ly(n.repo,`workflow_run pull request base repository`).id,`workflow_run pull request base repository ID`),ref:iy(n.ref,`workflow_run pull request base ref`),sha:ry(n.sha,`workflow_run pull request base SHA`)},head:{repositoryId:sy(ly(r.repo,`workflow_run pull request head repository`).id,`workflow_run pull request head repository ID`),ref:iy(r.ref,`workflow_run pull request head ref`),sha:ry(r.sha,`workflow_run pull request head SHA`)}}}function ey(e){if(!jv.test(e)||e.includes(`//`)||e.includes(`..`))throw Error(`capture-workflow-path must be a safe .github/workflows YAML path`);return e}function ty(e,t){let n=oy(e,`${t} full name`);if(!Av.test(n))throw Error(`${t} full name is invalid`);return n}function ny(e){let[t,n,...r]=e.split(`/`);if(!t||!n||r.length>0)throw Error(`Repository full name is invalid`);return{owner:t,repo:n}}function ry(e,t){let n=oy(e,t);if(!kv.test(n))throw Error(`${t} must be a lowercase full SHA`);return n}function iy(e,t){let n=oy(e,t);if(cy(n))throw Error(`${t} contains control characters`);return n}function ay(e,t){return e===null?null:oy(e,t)}function oy(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);if(cy(e))throw Error(`${t} contains control characters`);return e}function sy(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}function cy(e){return Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function ly(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function uy(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}E();const dy=T({meta:{name:`finalize-run`,description:`Close an unfinished status for the exact completed trusted workflow run`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=fy(n),i=await Fv(new uv(t,r),new Ud(t,r),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],statusContext:Md(e[`status-context`])});await sf({status:i.status,"finalize-reason":i.reason,...i.prNumber===void 0?{}:{"pr-number":i.prNumber},...i.headSha?{"head-sha":i.headSha}:{}})}});function fy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const py=T({meta:{name:`prepare-run`,description:`Download, verify, and rebuild a completed workflow_run report`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},output:{type:`string`,default:`.kapture/trusted-report`,description:`New directory for the trusted static report`},receipt:{type:`string`,default:`.kapture/trusted-run-receipt.json`,description:`Path for the strict trusted-run receipt`},"storybook-url":{type:`string`,description:`Trusted HTTPS Storybook URL or the fixed same-origin ./storybook/ directory`},"temporary-root":{type:`string`,description:`Trusted temporary directory root (defaults to RUNNER_TEMP)`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=await o_(new uv(t,my(n)),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],outputDir:f(e.output),receiptPath:f(e.receipt),...e[`storybook-url`]?{storybookUrl:e[`storybook-url`]}:{},...e[`temporary-root`]?{temporaryRoot:f(e[`temporary-root`])}:{}});await sf({"base-sha":r.receipt.context.base.sha,"context-artifact-id":r.receipt.artifacts.context.id,"head-repository":r.receipt.context.head.repository,"head-sha":r.receipt.context.head.sha,"pr-number":r.receipt.context.prNumber,"preview-branch":r.receipt.context.preview.branch,"preview-alias":r.receipt.context.preview.alias,"raw-report-artifact-id":r.receipt.artifacts.report.id,"report-digest":r.receipt.report.contentDigest,"report-directory":r.reportDirectory,"report-path":r.reportPath,receipt:r.receiptPath,"run-attempt":r.receipt.captureRun.attempt,"run-head-branch":r.receipt.captureRun.headBranch,"run-head-repository-id":r.receipt.captureRun.headRepositoryId,"run-head-sha":r.receipt.captureRun.headSha,"run-id":r.receipt.captureRun.id,"changed-files-complete":String(r.changedFiles.complete),"changed-files-count":r.changedFiles.files.length,"trusted-artifact-name":r.receipt.trustedArtifactName,"workflow-id":r.receipt.captureRun.workflowId})}});function my(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const hy=T({meta:{name:`prepare-storybook-run`,description:`Verify and extract the exact receipt-bound head Storybook artifact`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},output:{type:`string`,required:!0,description:`New directory for the verified head Storybook`},receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},"temporary-root":{type:`string`,description:`Trusted temporary directory root (defaults beside output)`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=await c_(new uv(t,gy(n)),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],outputDir:f(e.output),receiptPath:f(e.receipt),...e[`temporary-root`]?{temporaryRoot:f(e[`temporary-root`])}:{}});await sf({"head-ref":r.context.head.ref,"head-repository":r.context.head.repository,"head-sha":r.context.head.sha,"head-storybook-artifact-id":r.artifact.id,"pr-number":r.context.prNumber,"preview-branch":r.context.preview.branch,"preview-alias":r.context.preview.alias,receipt:r.receiptPath,"storybook-directory":r.storybookDirectory})}});function gy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const _y=T({meta:{name:`publish-run`,description:`Revalidate a prepare-run receipt and publish its deployed visual report`},args:{receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},report:{type:`string`,required:!0,description:`Path to the trusted image-bound report.json`},"report-url":{type:`string`,required:!0,description:`Immutable HTTPS URL of the deployed dashboard`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`},"comment-language":{type:`string`,default:`en`,description:`PR comment language (en or ko)`}},async run({args:e}){try{let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=vy(n),i=Ad(e[`report-url`]);if(!i)throw Error(`report-url is required`);let a=await s_(new uv(t,r),new Ud(t,r),{event:n,receiptPath:f(e.receipt),reportPath:f(e.report),reportUrl:i,statusContext:Md(e[`status-context`]),commentLanguage:bd(e[`comment-language`])});if(await sf({status:a.status,"changed-count":a.changedCount,"comment-id":a.commentId,"report-digest":a.reportDigest}),a.status===`error`)throw Error(`Visual capture errors were published to the trusted report`)}catch(e){throw await sf({status:`error`}),e}}});function vy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const yy=T({meta:{name:`reconcile-run`,description:`Reconcile a trusted workflow_run event with the current PR status`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=by(n),i=await Pv(new uv(t,r),new Ud(t,r),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],statusContext:Md(e[`status-context`])});await sf({status:i.status,"reconcile-reason":i.reason,...i.prNumber===void 0?{}:{"pr-number":i.prNumber},...i.headSha?{"head-sha":i.headSha}:{}})}});function by(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E(),zh();const xy=T({meta:{name:`report`,description:`Publish a trusted Kapture PR report and commit status`},args:{report:{type:`string`,required:!0,description:`Path to image-bound trusted report.json`},"report-url":{type:`string`,description:`HTTPS URL for the full report or workflow run`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`},"comment-language":{type:`string`,default:`en`,description:`PR comment language (en or ko)`}},async run({args:e}){try{let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await vh(e.report),r=qd(await Kd()),i=Md(e[`status-context`]),a=Ad(e[`report-url`]),o=await rf(new Ud(t,r.repository),r,n,i,a,bd(e[`comment-language`]));if(await sf({status:o.status,"changed-count":o.changedCount,"comment-id":o.commentId,"report-digest":o.reportDigest}),o.status===`error`)throw Error(`${n.summary.errors} visual capture error(s)`)}catch(e){throw await sf({status:`error`}),e}}});E(),zh();const Sy=T({meta:{name:`verify`,description:`Verify that a Kapture report matches the current pull request`},args:{report:{type:`string`,required:!0,description:`Path to untrusted report.json`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await vh(e.report),r=qd(await Kd());await nf(new Ud(t,r.repository),r,n)}});E();const Cy=T({meta:{name:`github`,description:`Verify, publish, and approve GitHub visual reviews`},subCommands:{context:Ov,verify:Sy,report:xy,approve:cf,"prepare-run":py,"prepare-storybook-run":hy,"publish-run":_y,"reconcile-run":yy,"finalize-run":dy,cleanup:Tv}});async function wy(e,t){let{report:n,resolveImage:r}=await Ty(e),i=n.entries[t];if(!i)throw Error(`Kapture report does not contain snapshot ${t}`);let a=[],o=(e,t)=>{t&&(Ay(e,t),a.push({role:e,mediaType:`image/png`,source:r(t)}))};return o(`base`,i.baseImage),o(`head`,i.headImage),o(`diff`,i.diffImage),o(`base-repeat`,i.instability?.base?.repeatImage),o(`base-instability-diff`,i.instability?.base?.diffImage),o(`head-repeat`,i.instability?.head?.repeatImage),o(`head-instability-diff`,i.instability?.head?.diffImage),{version:1,report:{baseRevision:n.baseRevision,headRevision:n.headRevision,...n.contentDigest?{contentDigest:n.contentDigest}:{}},snapshot:{id:i.id,storyId:i.storyId,title:i.title,name:i.name,viewport:i.viewport,status:i.status,...i.changedPixels===void 0?{}:{changedPixels:i.changedPixels},...i.diffRatio===void 0?{}:{diffRatio:i.diffRatio},...i.threshold?{threshold:i.threshold}:{},...i.error?{error:i.error}:{}},images:a}}async function Ty(e){let t=ky(e);return t?Dy(t):Ey(e)}async function Ey(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r=Oy(await x(t,`utf8`)),i=a(t);return{report:r,resolveImage:e=>{let t=f(i,e);if(d(i,t).startsWith(`..`))throw Error(`Kapture report contains an unsafe image path: ${e}`);return{type:`path`,value:t}}}}async function Dy(e){let t=await fetch(e,{redirect:`error`});if(!t.ok)throw Error(`Kapture report request failed with HTTP ${t.status}`);let n=Number(t.headers.get(`content-length`));if(Number.isFinite(n)&&n>10485760)throw Error(`Kapture report must be no larger than ${bh} bytes`);let r=await t.text();if(Buffer.byteLength(r)>10485760)throw Error(`Kapture report must be no larger than ${bh} bytes`);return{report:Oy(r),resolveImage:t=>{let n=new URL(t,e);if(n.origin!==e.origin||n.protocol!==`https:`)throw Error(`Kapture report contains an unsafe image URL: ${t}`);return{type:`url`,value:n.toString()}}}}function Oy(e){try{return gh(JSON.parse(e))}catch(e){throw e instanceof SyntaxError?Error(`Kapture report does not contain valid JSON`):e}}function ky(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`https:`||t.username||t.password)throw Error(`Remote Kapture report must be an HTTPS URL without credentials`);return t}function Ay(e,t){let n=`images/${e}/`,r=t.slice(n.length);if(!t.startsWith(n)||!r||r.includes(`/`)||r.includes(`\\`)||!r.endsWith(`.png`))throw Error(`Kapture report contains an invalid ${e} image path: ${t}`)}var jy,My=S((()=>{E(),zh(),jy=T({meta:{name:`inspect`,description:`Print machine-readable snapshot evidence for agents and review tools`},args:{report:{type:`string`,required:!0,description:`Local report.json path or public HTTPS report.json URL`},snapshot:{type:`string`,required:!0,description:`Exact snapshot ID`}},async run({args:e}){let t=await wy(e.report,e.snapshot);process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}})})),Ny=S((()=>{wc()})),Py=S((()=>{Ny()})),Fy=we({createKaptureMcpServer:()=>Ly,getSnapshotEvidenceResult:()=>Ry,startKaptureMcpServer:()=>Iy});async function Iy(e){let{serveStdio:t}=await import(`@modelcontextprotocol/server/stdio`);t(()=>Ly(e),{onerror:e=>console.error(e.message)})}async function Ly(e){let{McpServer:t}=await import(`@modelcontextprotocol/server`),n=new t({name:`kapture`,version:et},{instructions:`Use list_snapshots to find visual changes, then get_snapshot_evidence to inspect the exact PNG evidence. Unstable snapshots are nondeterministic and do not represent an approvable baseline change.`});return n.registerTool(`list_snapshots`,{title:`List Kapture snapshots`,description:`List snapshot IDs, statuses, stories, viewports, and diff metrics from a report.`,inputSchema:hs({status:z([`unchanged`,`changed`,`unstable`,`added`,`removed`,`error`]).optional().describe(`Optional exact status filter`)}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({status:t})=>{let{report:n}=await Ty(e),r=Object.values(n.entries).filter(e=>!t||e.status===t).map(e=>({id:e.id,storyId:e.storyId,title:e.title,name:e.name,viewport:e.viewport,status:e.status,changedPixels:e.changedPixels,changedPixelPercentage:e.diffRatio===void 0?void 0:e.diffRatio*100})),i={baseRevision:n.baseRevision,headRevision:n.headRevision,summary:n.summary,snapshots:r};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}],structuredContent:i}}),n.registerTool(`get_snapshot_evidence`,{title:`Get Kapture snapshot evidence`,description:`Return machine-readable metadata and the actual base, head, diff, and instability PNGs for one snapshot.`,inputSchema:hs({snapshotId:F().min(1).max(512).describe(`Exact ID returned by list_snapshots`)}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({snapshotId:t})=>Ry(e,t)),n}async function Ry(e,t){let n=await wy(e,t),r=await Promise.all(n.images.map(zy));return{content:[{type:`text`,text:JSON.stringify(Uy(n),null,2)},...r],structuredContent:Uy(n)}}async function zy(e){return{type:`image`,data:(e.source.type===`path`?await By(e.source.value):await Vy(e.source.value)).toString(`base64`),mimeType:`image/png`,_meta:{"kapture/role":e.role}}}async function By(e){let t=await v(e);if(t.isSymbolicLink()||!t.isFile()||t.size>Wy)throw Error(`Kapture evidence image must be no larger than ${Wy} bytes`);return Hy(await x(e),e)}async function Vy(e){let t=await fetch(e,{redirect:`error`});if(!t.ok)throw Error(`Kapture evidence request failed with HTTP ${t.status}`);let n=Number(t.headers.get(`content-length`));if(Number.isFinite(n)&&n>Wy)throw Error(`Kapture evidence image must be no larger than ${Wy} bytes`);return Hy(Buffer.from(await t.arrayBuffer()),e)}function Hy(e,t){if(e.byteLength>Wy||!e.subarray(0,8).equals(Gy))throw Error(`Kapture evidence is not a supported PNG: ${t}`);return e}function Uy(e){return{...e,images:e.images.map(t=>({role:t.role,mediaType:t.mediaType,source:t.source,contentBlockIndex:e.images.indexOf(t)+1}))}}var Wy,Gy,Ky=S((()=>{Py(),My(),Wy=26214400,Gy=Buffer.from([137,80,78,71,13,10,26,10])}));E();const qy=T({meta:{name:`mcp`,description:`Serve Kapture snapshot evidence to agents over MCP stdio`},args:{report:{type:`string`,required:!0,description:`Local report.json path or public HTTPS report.json URL`}},async run({args:e}){let{startKaptureMcpServer:t}=await Promise.resolve().then(()=>(Ky(),Fy));await t(e.report)}});_d(),E();const Jy=T({meta:{name:`plan`,description:`Select affected Storybook stories from base/head dependency manifests`},args:{"base-dir":{type:`string`,required:!0,description:`Built base Storybook directory`},"head-dir":{type:`string`,required:!0,description:`Built head Storybook directory`},"changed-files":{type:`string`,required:!0,description:`Path to a versioned changed-files manifest or legacy JSON path array`},output:{type:`string`,default:`.kapture/plan.json`,description:`Affected-story plan output path`}},async run({args:e}){let t=await Yy(f(e[`changed-files`])),n=await vl({baseDir:f(e[`base-dir`]),headDir:f(e[`head-dir`]),changedFiles:t.files,changedFilesComplete:t.complete,...t.evidence?{changedFilesEvidence:t.evidence}:{}}),r=f(e.output);await y(a(r),{recursive:!0}),await se(r,`${JSON.stringify(n,null,2)}\n`,`utf8`),n.selectionMode===`affected`?X.success(`Selected ${n.selectedStoryIds.length} of ${n.totalStoryIds.length} affected stories`):X.warn(`Selected all ${n.totalStoryIds.length} stories (${n.fallbackReasons.map(e=>e.code).join(`, `)})`),X.info(`Plan: ${r}`)}});async function Yy(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch(t){throw Error(`Failed to read changed files JSON from ${e}`,{cause:t})}if(!Array.isArray(t)){let e=kg(t);return{files:e.files,complete:e.complete,evidence:{provider:e.source.provider,manifestDigest:m(`sha256`).update(JSON.stringify(e)).digest(`hex`),pullRequestNumber:e.pullRequest.number,baseSha:e.pullRequest.baseSha,headSha:e.pullRequest.headSha}}}if(t.length>1e5)throw Error(`changed-files contains too many paths`);return{files:t.map(e=>Ag(e,`changed file path`)),complete:!0}}E();const Xy=T({meta:{name:`report`,description:`Build trusted static Kapture reports`},subCommands:{build:Gh}});_d(),E();const Zy=T({meta:{name:`test`,description:`Capture and compare base/head Storybooks in one hermetic browser environment`},args:{"base-dir":{type:`string`,required:!0,description:`Built base Storybook directory`},"head-dir":{type:`string`,required:!0,description:`Built head Storybook directory`},"base-capture-dir":{type:`string`,description:`Verified capture directory for the exact base revision; captures head only`},"base-revision":{type:`string`,required:!0,description:`Base Git revision`},"head-revision":{type:`string`,required:!0,description:`Head Git revision`},"changed-files":{type:`string`,description:`Versioned changed-files manifest used to capture only provably affected stories`},"install-browser":{type:`boolean`,default:!1,description:`Install the pinned Chrome runtime only when at least one story is selected`},"browser-with-deps":{type:`boolean`,default:!1,description:`Install Linux browser dependencies together with Chrome`},output:{type:`string`,default:`.kapture`,description:`Output directory`},workers:{type:`string`,default:`4`,description:`Concurrent isolated story lanes`},"pixel-color-threshold":{type:`string`,default:`0.2`,description:`Per-pixel perceptual color threshold`},"max-changed-pixel-percentage":{type:`string`,default:`0`,description:`Maximum percentage of changed pixels allowed without review (0 to 100)`},"frozen-time":{type:`string`,default:`2026-01-01T00:00:00.000Z`,description:`ISO time exposed to stories`},"random-seed":{type:`string`,default:`20260101`,description:`Math.random seed`},locale:{type:`string`,default:`en-US`,description:`BCP 47 browser locale`},timezone:{type:`string`,default:`UTC`,description:`IANA browser time zone`},"dashboard-dir":{type:`string`,description:`Dashboard build directory (defaults to the CLI embedded dashboard)`}},async run({args:e}){let t=nb(e.workers),n=rb(e[`pixel-color-threshold`],`pixel-color-threshold`),r=ib(e[`max-changed-pixel-percentage`],`max-changed-pixel-percentage`),i=tb(e[`random-seed`],`random-seed`),o=f(e[`base-dir`]),s=f(e[`head-dir`]),c=e[`changed-files`]?await Qy(o,s,f(e[`changed-files`]),e[`base-revision`],e[`head-revision`]):void 0;eb(c),e[`install-browser`]&&$y(c)&&(X.start(`Installing the Kapture browser runtime…`),await nt(e[`browser-with-deps`])),X.start(e[`base-capture-dir`]?`Reusing the verified base capture and capturing affected head stories…`:`Capturing base and head Storybooks in one hermetic environment…`);let l=await fu({baseDir:o,headDir:s,...e[`base-capture-dir`]?{baseCaptureDir:f(e[`base-capture-dir`])}:{},baseRevision:e[`base-revision`],headRevision:e[`head-revision`],outputDir:f(e.output),workers:t,threshold:{pixelColorThreshold:n,maxChangedPixelRatio:r/100},frozenTime:e[`frozen-time`],randomSeed:i,locale:e.locale,timezone:e.timezone,adapterVersion:et,selectionPlan:c});await Iu(e[`dashboard-dir`]?f(e[`dashboard-dir`]):f(a(me(import.meta.url)),`dashboard`),f(e.output,`report`));let{summary:u}=l.report;X.success(`${u.total} snapshots: ${u.changed} changed, ${u.unstable} unstable, ${u.added} added, ${u.removed} removed, ${u.unchanged} unchanged, ${u.errors} errors`),X.info(`Environment: ${l.report.environment.id}`),X.info(`Report: ${f(e.output,`report`,`report.json`)}`),u.errors>0&&(process.exitCode=2)}});async function Qy(e,t,n,r,i){let a=await Yy(n);if(a.evidence&&(a.evidence.baseSha!==r||a.evidence.headSha!==i))throw Error(`changed-files manifest base/head SHAs must match --base-revision and --head-revision`);return vl({baseDir:e,headDir:t,changedFiles:a.files,changedFilesComplete:a.complete,...a.evidence?{changedFilesEvidence:a.evidence}:{}})}function $y(e){return!e||e.selectedStoryIds.length>0}function eb(e){if(!e){X.info(`Story coverage: full capture (no changed-files manifest)`);return}if(e.selectionMode===`affected`){X.info(`Story coverage: ${e.selectedStoryIds.length} affected, ${e.skippedStoryIds.length} proven unaffected`);return}X.warn(`Story coverage: full fallback (${e.fallbackReasons.map(e=>e.code).join(`, `)})`)}function tb(e,t){let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function nb(e){let t=tb(e,`workers`);if(t>8)throw Error(`workers must be between 1 and 8`);return t}function rb(e,t){let n=Number.parseFloat(e);if(!Number.isFinite(n)||n<0||n>1)throw Error(`${t} must be between 0 and 1`);return n}function ib(e,t){let n=Number(e);if(!Number.isFinite(n)||n<0||n>100)throw Error(`${t} must be between 0 and 100`);return n}E(),zh();const ab=T({meta:{name:`validate`,description:`Validate a Kapture report as a CI gate`},args:{report:{type:`string`,required:!0,description:`Path to report.json`},"fail-on-diff":{type:`boolean`,default:!1,description:`Exit 1 when visual changes require review`}},async run({args:e}){let t=f(e.report),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r=gh(JSON.parse(await x(t,`utf8`)));if(r.summary.errors>0){X.error(`${r.summary.errors} capture or comparison error(s)`),process.exitCode=2;return}let i=r.summary.changed+r.summary.added+r.summary.removed;if(r.summary.unstable>0&&X.warn(`${r.summary.unstable} unstable snapshot(s) are non-blocking`),i>0&&e[`fail-on-diff`]){X.warn(`${i} visual change(s) require human approval`),process.exitCode=1;return}X.success(i>0?`${i} visual change(s) detected`:`No visual changes`)}});E(),My(),Ge(T({meta:{name:`kapture`,version:et,description:`Hermetic Storybook visual review`},subCommands:{test:Zy,validate:ab,browser:rt,plan:Jy,report:Xy,github:Cy,inspect:jy,mcp:qy}}));export{};
423
+ `:l}};function dh(e){return e.replace(/`([^`]+)`/gm,(e,t)=>K.cyan(t)).replace(/\s+_([^_]+)_\s+/gm,(e,t)=>` ${K.underline(t)} `)}function fh(e=`white`){return K[e]||K.white}function ph(e=`bgWhite`){return K[`bg${e[0].toUpperCase()}${e.slice(1)}`]||K.bgWhite}function mh(e={}){let t=hh();return process.env.CONSOLA_LEVEL&&(t=Number.parseInt(process.env.CONSOLA_LEVEL)??t),yf({level:t,defaults:{level:t},stdout:process.stdout,stderr:process.stderr,prompt:(...e)=>Promise.resolve().then(()=>(vm(),Gf)).then(t=>t.prompt(...e)),reporters:e.reporters||[e.fancy??!(Om||jm)?new uh:new Cf],...e})}function hh(){return Am?U.debug:jm?U.warn:U.info}const X=mh();function gh(e){let t=Rh.safeParse(_h(e));if(!t.success){let e=t.error.issues[0],n=e?.path.length?` at ${e.path.join(`.`)}`:``;throw Error(`Invalid Kapture report${n}: ${e?.message??`unknown error`}`)}return t.data}function _h(e){if(!e||typeof e!=`object`||Array.isArray(e))return e;let t=e;return t.version!==2||!t.summary||typeof t.summary!=`object`?e:{...t,version:3,summary:{...t.summary,unstable:0}}}async function vh(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r;try{r=JSON.parse(await x(t,`utf8`))}catch{throw Error(`Kapture report does not contain valid JSON`)}return gh(r)}function yh(e){try{let t=new URL(e);return t.protocol===`https:`&&!t.username&&!t.password}catch{return!1}}var bh,xh,Z,Q,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh=S((()=>{_d(),Tc(),bh=10485760,xh=2e4,Z=F().max(4096),Q=F().min(1).max(512),Sh=Q.refine(e=>Array.from(e).every(e=>{let t=e.codePointAt(0)??0;return t>31&&t!==127}),`must not contain control characters`),Ch=I().int().min(0).max(2**53-1),wh=I().int().positive().max(2**53-1),Th=I().min(0).max(1),Eh=L({name:Q,width:I().int().positive().max(16384),height:I().int().positive().max(16384)}),Dh=L({pixelColorThreshold:Th,maxChangedPixelRatio:Th}),Oh=L({id:Q,browser:Q,browserVersion:Q,orchestratorRuntime:Q,operatingSystem:Q,architecture:Q,deviceScaleFactor:I().positive().max(8),locale:Q,timezone:Q,colorScheme:z([`light`,`dark`]),reducedMotion:z([`reduce`,`no-preference`]),frozenTime:Q,randomSeed:I().int().min(0).max(2**53-1),fontsFingerprint:Q,stateIsolation:B(`fresh-browser-process-per-story-side-v1`).optional(),network:L({mode:B(`allowlist`),allowedDomains:ms(Q).max(100),webRtc:B(`disabled`)})}),kh=L({id:Q,storyId:Q,title:Z,name:Z,viewport:Eh,status:z([`unchanged`,`changed`,`unstable`,`added`,`removed`,`error`]),baseImage:Z.optional(),headImage:Z.optional(),diffImage:Z.optional(),ignoredRegions:ms(L({x:I().int().min(0).max(16384),y:I().int().min(0).max(32768),width:I().int().positive().max(16384),height:I().int().positive().max(32768)})).max(1e4).optional(),changedPixels:Ch.optional(),diffRatio:Th.optional(),threshold:Dh.optional(),instability:L({base:L({repeatImage:Z,diffImage:Z,changedPixels:Ch,diffRatio:Th}).optional(),head:L({repeatImage:Z,diffImage:Z,changedPixels:Ch,diffRatio:Th}).optional()}).optional(),error:Z.optional()}).superRefine((e,t)=>{e.status===`unstable`&&!e.instability?.base&&!e.instability?.head&&t.addIssue({code:`custom`,path:[`instability`],message:`unstable snapshots require base or head instability evidence`}),e.status!==`unstable`&&e.instability&&t.addIssue({code:`custom`,path:[`instability`],message:`only unstable snapshots can contain instability evidence`})}),Ah=ms(Q).max(xh).refine(e=>new Set(e).size===e.length,`must not contain duplicates`).refine(e=>e.every((t,n)=>n===0||e[n-1]<t),`must be sorted`),jh=L({code:z([`base-manifest-missing`,`base-manifest-invalid`,`head-manifest-missing`,`head-manifest-invalid`,`changed-files-incomplete`,`manifest-incomplete`,`global-input`,`global-output`,`global-runtime`,`unknown-input`,`story-import-missing`,`story-module-missing`,`fallback-reasons-truncated`]),path:Z.optional(),storyId:Q.optional(),side:z([`base`,`head`]).optional()}),Mh=L({provider:B(`github-pull-request-files`),manifestDigest:F().regex(/^[0-9a-f]{64}$/),pullRequestNumber:wh,baseSha:F().regex(/^[0-9a-f]{40}$/),headSha:F().regex(/^[0-9a-f]{40}$/)}),Nh=F().regex(/^[0-9a-f]{64}$/),Ph=_s(`state`,[L({state:B(`valid`),digest:Nh,revision:Q}),L({state:B(`invalid`),digest:Nh.optional(),revision:Q}),L({state:B(`missing`),revision:Q})]),Fh=L({base:Ph,head:Ph}),Ih=L({repository:Q.regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/),number:wh,url:Z.refine(yh,`must be an HTTPS URL without credentials`),baseBranch:Sh,headBranch:Sh,workflowRunUrl:Z.refine(yh,`must be an HTTPS URL without credentials`)}),Lh=L({plannerVersion:B(1),mode:z([`full`,`affected`,`full-fallback`]),changedFilesEvidence:Mh.optional(),dependencyManifests:Fh.optional(),storyIds:Ah,selectedStoryIds:Ah,skippedStoryIds:Ah,addedStoryIds:Ah.optional(),removedStoryIds:Ah.optional(),fallbackReasons:ms(jh).max(dd),baseline:L({mode:B(`reused`),revision:Q,manifestDigest:Nh}).optional()}).superRefine((e,t)=>{let n=new Set(e.storyIds),r=new Set(e.selectedStoryIds),i=new Set(e.skippedStoryIds);if((r.size+i.size!==n.size||[...r].some(e=>!n.has(e)||i.has(e))||[...i].some(e=>!n.has(e)))&&t.addIssue({code:`custom`,message:`selected and skipped stories must exactly partition the story catalog`}),e.mode!==`affected`&&i.size>0&&t.addIssue({code:`custom`,path:[`skippedStoryIds`],message:`full coverage modes cannot skip stories`}),e.mode===`full-fallback`&&e.fallbackReasons.length===0&&t.addIssue({code:`custom`,path:[`fallbackReasons`],message:`full-fallback coverage requires at least one reason`}),e.mode!==`full-fallback`&&e.fallbackReasons.length>0&&t.addIssue({code:`custom`,path:[`fallbackReasons`],message:`only full-fallback coverage can contain fallback reasons`}),e.addedStoryIds===void 0!=(e.removedStoryIds===void 0)&&t.addIssue({code:`custom`,message:`added and removed story catalogs must be provided together`}),e.addedStoryIds&&e.removedStoryIds){let i=new Set(e.addedStoryIds),a=new Set(e.removedStoryIds);([...i].some(e=>!n.has(e)||!r.has(e)||a.has(e))||[...a].some(e=>!n.has(e)||!r.has(e)))&&t.addIssue({code:`custom`,message:`added and removed stories must be disjoint selected catalog members`})}}),Rh=L({version:B(3),contentDigest:F().regex(/^[0-9a-f]{64}$/).optional(),baseRevision:Q,headRevision:Q,headBranch:Sh.optional(),baseBranch:Sh.optional(),pullRequest:Ih.optional(),storybookUrl:Z.refine(e=>e===`./storybook/`||yh(e),`must be an HTTPS URL or ./storybook/ without credentials`).optional(),environment:Oh,createdAt:Q,threshold:Dh,summary:L({total:Ch,unchanged:Ch,changed:Ch,unstable:Ch,added:Ch,removed:Ch,errors:Ch}),coverage:Lh.optional(),entries:R(F(),kh)}).superRefine((e,t)=>{let n=Object.entries(e.entries);if(n.length>2e4){t.addIssue({code:`custom`,message:`Report contains more than ${xh} entries`,path:[`entries`]});return}for(let[e,r]of n)e!==r.id&&t.addIssue({code:`custom`,message:`Entry key must match entry.id`,path:[`entries`,e,`id`]});let r={unchanged:0,changed:0,unstable:0,added:0,removed:0,error:0};for(let t of Object.values(e.entries))r[t.status]+=1;if((e.summary.total!==n.length||e.summary.unchanged!==r.unchanged||e.summary.changed!==r.changed||e.summary.unstable!==r.unstable||e.summary.added!==r.added||e.summary.removed!==r.removed||e.summary.errors!==r.error)&&t.addIssue({code:`custom`,message:`Report summary does not match its entries`,path:[`summary`]}),e.coverage){let r=e.coverage.changedFilesEvidence;r&&(r.baseSha!==e.baseRevision||r.headSha!==e.headRevision)&&t.addIssue({code:`custom`,message:`Changed-files evidence must match the report base and head revisions`,path:[`coverage`,`changedFilesEvidence`]});let i=e.coverage.dependencyManifests;i&&(i.base.revision!==e.baseRevision||i.head.revision!==e.headRevision)&&t.addIssue({code:`custom`,message:`Dependency manifest evidence must match the report base and head revisions`,path:[`coverage`,`dependencyManifests`]});let a=new Set(e.coverage.selectedStoryIds),o=new Set(e.coverage.addedStoryIds??[]),s=new Set(e.coverage.removedStoryIds??[]);for(let[e,r]of n)a.has(r.storyId)||t.addIssue({code:`custom`,message:`Report entries must belong to selected stories`,path:[`entries`,e,`storyId`]}),o.has(r.storyId)&&r.status!==`added`&&r.status!==`error`&&t.addIssue({code:`custom`,message:`Entries for an added story must be added or error snapshots`,path:[`entries`,e,`status`]}),s.has(r.storyId)&&r.status!==`removed`&&r.status!==`error`&&t.addIssue({code:`custom`,message:`Entries for a removed story must be removed or error snapshots`,path:[`entries`,e,`status`]})}})}));_d(),E();var Bh=Nt();zh();const Vh=26214400,Hh=Buffer.from([137,80,78,71,13,10,26,10]),Uh=new Set([`acTL`,`fcTL`,`fdAT`]),Wh=[`baseImage`,`headImage`,`diffImage`,`baseRepeatImage`,`baseInstabilityDiffImage`,`headRepeatImage`,`headInstabilityDiffImage`],Gh=T({meta:{name:`build`,description:`Rebuild a trusted static report from an untrusted Kapture artifact`},args:{input:{type:`string`,required:!0,description:`Untrusted artifact report directory containing report.json and images`},output:{type:`string`,required:!0,description:`New directory for the trusted static report`},"storybook-url":{type:`string`,description:`Trusted HTTPS Storybook URL or the fixed same-origin ./storybook/ directory`},"base-branch":{type:`string`,description:`Trusted base branch display label (not a comparison revision)`},"head-branch":{type:`string`,description:`Trusted head branch display label (not a comparison revision)`}},async run({args:e}){let t=await Kh({inputDir:e.input,outputDir:e.output,storybookUrl:e[`storybook-url`],trustedBaseBranch:e[`base-branch`],trustedHeadBranch:e[`head-branch`]});X.success(`Trusted report: ${t.report.summary.total} snapshots, ${t.imageCount} verified PNGs (${t.imageBytes} bytes)`),X.info(`Output: ${t.outputDir}`)}});async function Kh(e){let t=f(e.inputDir),n=f(e.outputDir),r=qh(e.trustedHeadBranch),i=qh(e.trustedBaseBranch);if(await ag(t),cg(t,n))throw Error(`Trusted report output must be outside the untrusted input directory`);await og(n);let o=e.dashboardDir?f(e.dashboardDir):f(a(me(import.meta.url)),`dashboard`),s=a(n);await y(s,{recursive:!0});let c=await te(`${s}${p}.kapture-report-`),l;try{l=await Yh(t,async(e,t)=>{let n=f(c,e.relativePath);await y(a(n),{recursive:!0}),await se(n,t,{flag:`wx`})});let{report:s,imageDigests:u,calculatedContentDigest:d}=l;if(s.contentDigest&&s.contentDigest!==d)throw Error(`Report content digest does not match its referenced PNGs: expected ${s.contentDigest}, calculated ${d}`);r?s.headBranch=r:delete s.headBranch,i?s.baseBranch=i:delete s.baseBranch,e.trustedPullRequest?s.pullRequest={...e.trustedPullRequest}:delete s.pullRequest;let p=jd(e.storybookUrl);p?s.storybookUrl=p:delete s.storybookUrl,s.contentDigest=Wc(s,u),await se(f(c,`report.json`),`${JSON.stringify(s)}\n`,{flag:`wx`}),await Iu(o,c),await ie(c,n)}catch(e){throw await ae(c,{recursive:!0,force:!0}),e}if(!l)throw Error(`Trusted report validation did not complete`);return{report:l.report,outputDir:n,imageCount:l.references.length,imageBytes:l.imageBytes}}function qh(e){if(e!==void 0){if(e.length<1||e.length>512||Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127}))throw Error(`Trusted head branch must contain between 1 and 512 non-control characters`);return e}}async function Jh(e,t){if(!/^[0-9a-f]{64}$/.test(t))throw Error(`Expected trusted report content digest must be a lowercase SHA-256 digest`);let n=f(e);if(n!==f(a(n),`report.json`))throw Error(`Trusted report path must end in report.json`);let r=a(n);await ag(r);let i=await Yh(r);if(i.report.contentDigest!==t||i.calculatedContentDigest!==t)throw Error(`Trusted report content digest does not match its actual structure and referenced PNGs`);return i.report}async function Yh(e,t){let n=Xh(await sg(e,`report.json`,bh)),r=Zh(n);if(r.length>6e4)throw Error(`Report references more than 60000 PNG images`);let i=new Map,a=[],o=0;for(let n of r){let r=await sg(e,n.relativePath,Vh);if(o+=r.byteLength,o>536870912)throw Error(`Referenced PNGs exceed 536870912 total bytes`);i.set(n.relativePath,ng(r,n.relativePath)),a.push({path:n.relativePath,sha256:m(`sha256`).update(r).digest(`hex`)}),await t?.(n,r)}return ig(n,i),{report:n,references:r,imageDigests:a,imageBytes:o,calculatedContentDigest:Wc(n,a)}}function Xh(e){let t;try{t=JSON.parse(e.toString(`utf8`))}catch{throw Error(`Input report.json does not contain valid JSON`)}return gh(t)}function Zh(e){let t=new Map;for(let n of Object.values(e.entries)){let e=Qh(n);for(let r of Wh){let i=eg(n,r);if(e.has(r)&&!i)throw Error(`Report entry ${n.id} is missing ${r} for status ${n.status}`);if(!e.has(r)&&i)throw Error(`Report entry ${n.id} cannot contain ${r} for status ${n.status}`);if(!i)continue;let a=tg(i,$h(r),n.id),o=t.get(a);if(o&&o.entryId!==n.id)throw Error(`Report entries ${o.entryId} and ${n.id} reference the same PNG: ${a}`);t.set(a,{relativePath:a,entryId:n.id})}}return[...t.values()]}function Qh(e){if(e.status===`changed`)return new Set([`baseImage`,`headImage`,`diffImage`]);if(e.status===`unstable`){if(!e.instability?.base&&!e.instability?.head)throw Error(`Report entry ${e.id} is unstable without instability evidence`);let t=[`baseImage`,`headImage`,`diffImage`];return e.instability.base&&t.push(`baseRepeatImage`,`baseInstabilityDiffImage`),e.instability.head&&t.push(`headRepeatImage`,`headInstabilityDiffImage`),new Set(t)}return e.status===`added`?new Set([`headImage`]):e.status===`removed`?new Set([`baseImage`]):new Set}function $h(e){return e===`baseImage`?`base`:e===`headImage`?`head`:e===`diffImage`?`diff`:e===`baseRepeatImage`?`base-repeat`:e===`baseInstabilityDiffImage`?`base-instability-diff`:e===`headRepeatImage`?`head-repeat`:`head-instability-diff`}function eg(e,t){return t===`baseImage`||t===`headImage`||t===`diffImage`?e[t]:t===`baseRepeatImage`?e.instability?.base?.repeatImage:t===`baseInstabilityDiffImage`?e.instability?.base?.diffImage:t===`headRepeatImage`?e.instability?.head?.repeatImage:e.instability?.head?.diffImage}function tg(e,t,n){let r=`images/${t}/`,i=e.slice(r.length);if(!e.startsWith(r)||!i||i.includes(`/`)||i.includes(`\\`)||i.length>255||!/^[a-zA-Z0-9][a-zA-Z0-9._-]*\.png$/.test(i))throw Error(`Report entry ${n} has an invalid ${t} PNG path: ${e}`);return e}function ng(e,t){if(e.byteLength<33||!e.subarray(0,8).equals(Hh))throw Error(`Referenced image is not a PNG: ${t}`);let n=e.readUInt32BE(8),r=e.toString(`ascii`,12,16);if(n!==13||r!==`IHDR`)throw Error(`Referenced PNG has an invalid IHDR chunk: ${t}`);let i=e.readUInt32BE(16),a=e.readUInt32BE(20);if(i<1||a<1||i>16384||a>32768||i*a>33554432)throw Error(`Referenced PNG dimensions are outside the supported limits: ${t} (${i}x${a})`);rg(e,t);try{let t=Bh.PNG.sync.read(e,{checkCRC:!0,skipRescale:!0});if(t.width!==i||t.height!==a)throw Error(`decoded dimensions differ from IHDR`)}catch{throw Error(`Referenced PNG cannot be decoded safely: ${t}`)}return{width:i,height:a}}function rg(e,t){let n=Hh.byteLength,r=!1;for(;n+12<=e.byteLength;){let i=e.readUInt32BE(n),a=e.toString(`ascii`,n+4,n+8),o=n+12+i;if(o>e.byteLength)throw Error(`Referenced PNG has an invalid chunk boundary: ${t}`);if(Uh.has(a))throw Error(`Animated PNG is not supported in a static report: ${t}`);if(n=o,a===`IEND`){r=!0;break}}if(!r||n!==e.byteLength)throw Error(`Referenced PNG has an invalid chunk structure: ${t}`)}function ig(e,t){for(let n of Object.values(e.entries)){if(n.status!==`changed`&&n.status!==`unstable`||!n.baseImage||!n.headImage||!n.diffImage)continue;let e=t.get(n.baseImage),r=t.get(n.headImage),i=t.get(n.diffImage);if(!e||!r||!i)throw Error(`Report entry ${n.id} is missing validated PNG dimensions`);let a=Math.max(e.width,r.width),o=Math.max(e.height,r.height);for(let e of n.ignoredRegions??[])if(e.x+e.width>a||e.y+e.height>o)throw Error(`Report entry ${n.id} ignored region exceeds its comparison canvas`);if(i.width!==a||i.height!==o)throw Error(`Report entry ${n.id} diff PNG must match the padded comparison canvas ${a}x${o}`);if(n.changedPixels!==void 0&&n.changedPixels>a*o)throw Error(`Report entry ${n.id} changedPixels exceeds its diff PNG pixel count`);for(let i of[n.instability?.base,n.instability?.head]){if(!i)continue;let a=t.get(i.repeatImage),o=t.get(i.diffImage);if(!a||!o)throw Error(`Report entry ${n.id} is missing instability PNG dimensions`);let s=i===n.instability?.base?e:r,c=Math.max(s.width,a.width),l=Math.max(s.height,a.height);if(o.width!==c||o.height!==l)throw Error(`Report entry ${n.id} instability diff PNG must match ${c}x${l}`);if(i.changedPixels>c*l)throw Error(`Report entry ${n.id} instability changedPixels exceeds its diff PNG pixel count`)}}}async function ag(e){let t;try{t=await v(e)}catch(t){throw lg(t)?Error(`Input report directory does not exist: ${e}`):t}if(t.isSymbolicLink()||!t.isDirectory())throw Error(`Input report path must be a real directory, not a symbolic link`)}async function og(e){try{await v(e)}catch(e){if(lg(e))return;throw e}throw Error(`Trusted report output already exists: ${e}`)}async function sg(e,t,n){if(s(t)||t.includes(`\\`))throw Error(`Input file must be a normalized relative path: ${t}`);let r=t.split(`/`),i=e;for(let[e,n]of r.entries()){if(!n||n===`.`||n===`..`)throw Error(`Input file must be a normalized relative path: ${t}`);i=f(i,n);let a;try{a=await v(i)}catch(e){throw lg(e)?Error(`Referenced input file does not exist: ${t}`):e}if(a.isSymbolicLink())throw Error(`Referenced input path cannot contain a symbolic link: ${t}`);let o=e===r.length-1;if(!o&&!a.isDirectory()||o&&!a.isFile())throw Error(`Referenced input path is not a regular file: ${t}`)}let a=pe.O_RDONLY|(pe.O_NOFOLLOW??0),o=await b(i,a);try{let e=await o.stat();if(!e.isFile()||e.size>n)throw Error(`Input file exceeds ${n} bytes: ${t}`);let r=Buffer.alloc(e.size),i=0;for(;i<r.byteLength;){let{bytesRead:e}=await o.read(r,i,r.byteLength-i,i);if(e===0)throw Error(`Input file changed while being read: ${t}`);i+=e}let a=Buffer.alloc(1),{bytesRead:s}=await o.read(a,0,1,r.byteLength);if(s>0)throw Error(`Input file changed while being read: ${t}`);return r}finally{await o.close()}}function cg(e,t){let n=d(e,t);return n===``||!n.startsWith(`..${p}`)&&n!==`..`&&!s(n)}function lg(e){return typeof e==`object`&&!!e&&`code`in e&&e.code===`ENOENT`}function ug(e,t){return fg(e,t).map(({path:e,compressedBytes:t,uncompressedBytes:n})=>({path:e,compressedBytes:t,uncompressedBytes:n}))}async function dg(e,t,n){let r=fg(e,n),i=f(t);await y(i,{recursive:!0});for(let t of r){let n=e.subarray(t.dataOffset,t.dataOffset+t.compressedBytes),r=t.compression===0?Buffer.from(n):Se(n,{maxOutputLength:t.uncompressedBytes+1});if(r.byteLength!==t.uncompressedBytes)throw Error(`ZIP entry size mismatch: ${t.path}`);if(xe(r)!==t.crc)throw Error(`ZIP entry checksum mismatch: ${t.path}`);let o=f(i,t.path);if(!o.startsWith(`${i}${p}`))throw Error(`ZIP entry escapes the output directory: ${t.path}`);await y(a(o),{recursive:!0}),await se(o,r,{flag:`wx`})}return r}function fg(e,t){_g(t);let n=pg(e),r=e.readUInt16LE(n+4),i=e.readUInt16LE(n+6),a=e.readUInt16LE(n+8),o=e.readUInt16LE(n+10),s=e.readUInt32LE(n+12),c=e.readUInt32LE(n+16),l=e.readUInt16LE(n+20);if(n+22+l!==e.byteLength)throw Error(`ZIP end record does not match the archive size`);if(r!==0||i!==0||a!==o)throw Error(`Multi-disk ZIP archives are not supported`);if(o===65535||s===4294967295||c===4294967295)throw Error(`ZIP64 archives are not supported`);if(o>t.maxEntries)throw Error(`ZIP archive contains more than ${t.maxEntries} entries`);if(c+s!==n)throw Error(`ZIP central directory is malformed`);let u=[],d=new Set,f=c,p=0;for(let r=0;r<o;r+=1){if(f+46>n||e.readUInt32LE(f)!==33639248)throw Error(`ZIP central directory entry is malformed`);let r=e.readUInt16LE(f+4),i=e.readUInt16LE(f+8),a=e.readUInt16LE(f+10),o=e.readUInt32LE(f+16),s=e.readUInt32LE(f+20),l=e.readUInt32LE(f+24),m=e.readUInt16LE(f+28),h=e.readUInt16LE(f+30),g=e.readUInt16LE(f+32),_=e.readUInt16LE(f+34),ee=e.readUInt32LE(f+38),v=e.readUInt32LE(f+42),y=f+46+m+h+g;if(y>n)throw Error(`ZIP central directory entry exceeds its bounds`);if(i&1)throw Error(`Encrypted ZIP entries are not supported`);if(a!==0&&a!==8)throw Error(`ZIP compression method ${a} is not supported`);if(_!==0)throw Error(`Multi-disk ZIP entries are not supported`);if(s===4294967295||l===4294967295||v===4294967295)throw Error(`ZIP64 entries are not supported`);let te=e.subarray(f+46,f+46+m),b=hg(te);f=y;let x=b.endsWith(`/`);if(gg(r,ee,b,x),d.has(b))throw Error(`ZIP archive contains duplicate path: ${b}`);if(d.add(b),x){if(!t.allowDirectoryPath(b))throw Error(`ZIP archive contains unexpected directory: ${b}`);if(i&8||a!==0||o!==0||s!==0||l!==0)throw Error(`ZIP directory entry must be empty and stored: ${b}`);mg(e,v,te,i,a,o,s,l,c);continue}if(!t.allowPath(b))throw Error(`ZIP archive contains unexpected path: ${b}`);if(l>t.maxFileBytes)throw Error(`ZIP entry exceeds ${t.maxFileBytes} bytes: ${b}`);if(p+=l,p>t.maxTotalBytes)throw Error(`ZIP archive exceeds ${t.maxTotalBytes} uncompressed bytes`);let ne=mg(e,v,te,i,a,o,s,l,c);u.push({path:b,compression:a,crc:o,compressedBytes:s,uncompressedBytes:l,dataOffset:ne})}if(f!==n)throw Error(`ZIP central directory size is inconsistent`);return u}function pg(e){let t=Math.max(0,e.byteLength-65557);for(let n=e.byteLength-22;n>=t;--n)if(e.readUInt32LE(n)===101010256)return n;throw Error(`ZIP end-of-central-directory record is missing`)}function mg(e,t,n,r,i,a,o,s,c){if(t+30>c||e.readUInt32LE(t)!==67324752)throw Error(`ZIP local entry header is malformed`);let l=e.readUInt16LE(t+6),u=e.readUInt16LE(t+8),d=e.readUInt32LE(t+14),f=e.readUInt32LE(t+18),p=e.readUInt32LE(t+22),m=e.readUInt16LE(t+26),h=e.readUInt16LE(t+28),g=t+30+m+h;if(g>c)throw Error(`ZIP local entry header exceeds its bounds`);let _=e.subarray(t+30,t+30+m);if(l!==r||u!==i||!_.equals(n))throw Error(`ZIP local and central directory entries do not match`);if(!(l&8)&&(d!==a||f!==o||p!==s))throw Error(`ZIP local and central directory sizes or checksum do not match`);if(g+o>c)throw Error(`ZIP entry data exceeds the archive bounds`);return g}function hg(e){let t=e.toString(`utf8`);if(!Buffer.from(t,`utf8`).equals(e))throw Error(`ZIP path is not valid UTF-8`);let n=t.endsWith(`/`),r=t.split(`/`),i=n?r.slice(0,-1):r;if(t.length<1||t.startsWith(`/`)||t.includes(`\\`)||t.includes(`\0`)||i.some(e=>!e||e===`.`||e===`..`)||Array.from(t).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127}))throw Error(`ZIP path is unsafe: ${JSON.stringify(t)}`);return t}function gg(e,t,n,r){if(e>>>8!=3)return;let i=t>>>16&61440;if(i!==0&&i!==(r?16384:32768))throw Error(r?`ZIP entry is not a directory: ${n}`:`ZIP entry is not a regular file: ${n}`)}function _g(e){for(let[t,n]of Object.entries({maxEntries:e.maxEntries,maxFileBytes:e.maxFileBytes,maxTotalBytes:e.maxTotalBytes}))if(!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be positive`)}function vg(e,t){let n=Eg(e,`GitHub pull_request event`),r=Eg(n.pull_request,`pull_request`),i=xg(Eg(n.repository,`repository`)),a=Eg(r.base,`pull_request.base`),o=Eg(r.head,`pull_request.head`),s=xg(Eg(a.repo,`pull_request.base.repo`)),c=Eg(o.repo,`pull_request.head.repo`),l=Cg(a.ref,`pull_request.base.ref`),u=Cg(o.ref,`pull_request.head.ref`),d=wg(r.number,`pull request number`);if(s!==i)throw Error(`Pull request base repository must match the workflow repository`);if(t!==void 0&&l!==Cg(t,`base branch`))throw Error(`Pull request targets ${l}, expected ${t}`);return{schemaVersion:1,runId:wg(n.run_id??process.env.GITHUB_RUN_ID,`workflow run ID`),prNumber:d,base:{repository:s,ref:l,sha:Sg(a.sha,`pull_request.base.sha`)},head:{repository:xg(c),repositoryId:wg(c.id,`head repository ID`),ref:u,sha:Sg(o.sha,`pull_request.head.sha`)},preview:{branch:u,alias:bg(d,u)}}}function yg(e){return`pr-${e.prNumber}-base-${e.base.sha}-head-${e.head.sha}`}function bg(e,t){let n=`pr-${wg(e,`pull request number`)}-`,r=Cg(t,`head branch`),i=r.normalize(`NFKD`).toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``),a=`-${m(`sha256`).update(r).digest(`hex`).slice(0,10)}`,o=Math.max(1,63-n.length-a.length);return`${n}${(i||`branch`).slice(0,o).replace(/-$/g,``)||`b`}${a}`}function xg(e){let t=Tg(e.full_name,`repository full name`);if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t))throw Error(`GitHub event contains an invalid repository full name`);return t}function Sg(e,t){let n=Tg(e,t).toLowerCase();if(!/^[0-9a-f]{40}$/.test(n))throw Error(`${t} must be a full SHA`);return n}function Cg(e,t){let n=Tg(e,t);if(n.length<1||n.length>512)throw Error(`${t} is invalid`);for(let e of n){let n=e.codePointAt(0)??0;if(n<=31||n===127)throw Error(`${t} is invalid`)}return n}function wg(e,t){let n=typeof e==`string`&&/^[1-9][0-9]*$/.test(e)?Number(e):e;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function Tg(e,t){if(typeof e!=`string`)throw Error(`${t} must be a string`);return e}function Eg(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}const Dg=3e3;async function Og(e,t){let n=await e.getPullRequestForCapture(t.prNumber);jg(n,t);let r=Hg(n.changed_files,`pull request changed_files`),i=[],a=[],o=0;if(r>3e3)i.push({code:`github-file-limit`});else for(let n=1;n<=Math.ceil(r/100);n+=1){let s=await e.listPullRequestFilesPage(t.prNumber,n,100);if(o=n,!Array.isArray(s)){i.push({code:`pagination-incomplete`,page:n});break}let c=s.slice(0,100);s.length>100&&i.push({code:`pagination-incomplete`,page:n});for(let[e,t]of c.entries())a.push({value:t,page:n,index:e});if(c.length<100){a.length<r&&i.push({code:`pagination-incomplete`,page:n});break}}a.length!==r&&i.push({code:`file-count-mismatch`});let s=new Set,c=new Set;for(let e of a)Mg(e,s,c,i);let l=await e.getPullRequestForCapture(t.prNumber);if(jg(l,t),l.changed_files!==r)throw Error(`Pull request changed while Kapture discovered changed files`);let u=Fg(i);return{kind:`kapture-changed-files`,version:1,complete:u.length===0,pullRequest:{number:t.prNumber,baseSha:t.base.sha,headSha:t.head.sha},files:[...s].sort(),source:{provider:`github-pull-request-files`,expectedFileCount:r,fetchedFileCount:a.length,pageCount:o,perPage:100,maxFiles:Dg},diagnostics:u}}function kg(e){let t=Ug(e,`changed-files manifest`);if(zg(t,[`kind`,`version`,`complete`,`pullRequest`,`files`,`source`,`diagnostics`],`changed-files manifest`),t.kind!==`kapture-changed-files`||t.version!==1)throw Error(`changed-files manifest must use kapture-changed-files version 1`);if(typeof t.complete!=`boolean`)throw Error(`changed-files manifest complete must be a boolean`);if(!Array.isArray(t.files)||t.files.length>6e3)throw Error(`changed-files manifest files must be a bounded array`);let n=t.files.map(e=>Ag(e,`changed file path`));if(!Ig(n))throw Error(`changed-files manifest files must be unique and sorted`);let r=Ug(t.pullRequest,`changed-files manifest pullRequest`);zg(r,[`number`,`baseSha`,`headSha`],`changed-files manifest pullRequest`);let i=Ug(t.source,`changed-files manifest source`);if(zg(i,[`provider`,`expectedFileCount`,`fetchedFileCount`,`pageCount`,`perPage`,`maxFiles`],`changed-files manifest source`),i.provider!==`github-pull-request-files`)throw Error(`changed-files manifest source provider is invalid`);if(i.perPage!==100||i.maxFiles!==3e3)throw Error(`changed-files manifest source limits are invalid`);if(!Array.isArray(t.diagnostics)||t.diagnostics.length>6e3)throw Error(`changed-files manifest diagnostics must be a bounded array`);let a=t.diagnostics.map(Pg);if(!Ig(a.map(Lg)))throw Error(`changed-files manifest diagnostics must be unique and sorted`);if(t.complete!==(a.length===0))throw Error(`changed-files manifest completeness disagrees with diagnostics`);let o=Hg(i.expectedFileCount,`changed-files expected file count`),s=Hg(i.fetchedFileCount,`changed-files fetched file count`),c=Hg(i.pageCount,`changed-files page count`);if(s>3e3||c>30||s>c*100||n.length>s*2)throw Error(`changed-files manifest source counts are inconsistent`);if(t.complete&&(o!==s||o>3e3||c!==Math.ceil(s/100)||n.length<s))throw Error(`complete changed-files manifest source counts are inconsistent`);return{kind:`kapture-changed-files`,version:1,complete:t.complete,pullRequest:{number:Vg(r.number,`changed-files pull request number`),baseSha:Bg(r.baseSha,`changed-files base SHA`),headSha:Bg(r.headSha,`changed-files head SHA`)},files:n,source:{provider:`github-pull-request-files`,expectedFileCount:o,fetchedFileCount:s,pageCount:c,perPage:100,maxFiles:Dg},diagnostics:a}}function Ag(e,t=`GitHub file path`){if(typeof e!=`string`)throw Error(`${t} must be a string`);let n=Array.from(e);if(e.length===0||e.length>4096||e.startsWith(`/`)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith(`./`)||e===`.`||e===`..`||e.startsWith(`../`)||e.endsWith(`/`)||e.includes(`//`)||e.includes(`\\`)||e.split(`/`).some(e=>e===`.`||e===`..`)||n.some(e=>{let t=e.codePointAt(0)??0;return t<=31||t>=127&&t<=159}))throw Error(`${t} must be a normalized project-relative path`);return e}function jg(e,t){let n=e.head.repo;if(e.number!==t.prNumber||e.state!==`open`||e.base.ref!==t.base.ref||e.base.sha.toLowerCase()!==t.base.sha||e.base.repo.full_name!==t.base.repository||e.head.ref!==t.head.ref||e.head.sha.toLowerCase()!==t.head.sha||n?.id!==t.head.repositoryId||n.full_name!==t.head.repository)throw Error(`Live pull request does not match the exact Kapture capture context`)}function Mg(e,t,n,r){if(!e.value||typeof e.value!=`object`||Array.isArray(e.value)){r.push({code:`invalid-file-record`,page:e.page,index:e.index});return}let i=e.value;if(typeof i.status!=`string`||typeof i.filename!=`string`){r.push({code:`invalid-file-record`,page:e.page,index:e.index});return}let a=JSON.stringify([i.status,i.filename,i.previous_filename]);if(n.has(a)&&r.push({code:`duplicate-file-entry`,page:e.page,index:e.index}),n.add(a),Ng(i.filename,e,t,r),i.status===`renamed`||i.previous_filename!==void 0){if(typeof i.previous_filename!=`string`){r.push({code:`rename-source-missing`,page:e.page,index:e.index});return}Ng(i.previous_filename,e,t,r)}}function Ng(e,t,n,r){try{n.add(Ag(e))}catch{r.push({code:`invalid-file-path`,page:t.page,index:t.index})}}function Pg(e){let t=Ug(e,`changed-files diagnostic`);if(zg(t,[`code`,`page`,`index`],`changed-files diagnostic`,!0),typeof t.code!=`string`||![`github-file-limit`,`pagination-incomplete`,`file-count-mismatch`,`invalid-file-record`,`invalid-file-path`,`rename-source-missing`,`duplicate-file-entry`].includes(t.code))throw Error(`changed-files diagnostic code is invalid`);let n=t.page===void 0?void 0:Vg(t.page,`page`),r=t.index===void 0?void 0:Hg(t.index,`diagnostic index`),i={code:t.code,...n===void 0?{}:{page:n},...r===void 0?{}:{index:r}};if(i.code===`github-file-limit`||i.code===`file-count-mismatch`?n!==void 0||r!==void 0:i.code===`pagination-incomplete`?n===void 0||n>30||r!==void 0:n===void 0||n>30||r===void 0||r>=100)throw Error(`changed-files diagnostic location is invalid`);return i}function Fg(e){return[...new Map(e.map(e=>[JSON.stringify(e),e])).values()].sort((e,t)=>Rg(Lg(e),Lg(t)))}function Ig(e){return e.every((t,n)=>n===0||(e[n-1]??``)<t)}function Lg(e){return`${e.code}:${String(e.page??0).padStart(2,`0`)}:${String(e.index??0).padStart(3,`0`)}`}function Rg(e,t){return e<t?-1:+(e>t)}function zg(e,t,n,r=!1){let i=Object.keys(e).sort(),a=r?i.filter(e=>t.includes(e)).sort():[...t].sort();if(i.some(e=>!t.includes(e))||!r&&(i.length!==a.length||i.some((e,t)=>e!==a[t])))throw Error(`${n} contains unexpected or missing fields`)}function Bg(e,t){if(typeof e!=`string`||!/^[0-9a-f]{40}$/.test(e))throw Error(`${t} must be a full lowercase SHA`);return e}function Vg(e,t){let n=Hg(e,t);if(n===0)throw Error(`${t} must be a positive integer`);return n}function Hg(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<0)throw Error(`${t} must be a non-negative integer`);return e}function Ug(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}Tc(),zh();const Wg=/^[0-9a-f]{40}$/,Gg=/^sha256:[0-9a-f]{64}$/,Kg=/^[0-9a-f]{64}$/,qg=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,Jg=/^\.github\/workflows\/[A-Za-z0-9_./-]+\.ya?ml$/,Yg=/^images\/(?:base|head|diff)\/[A-Za-z0-9][A-Za-z0-9._-]*\.png$/,Xg=F().min(1).max(512).refine(e=>!ov(e),`must not contain control characters`),Zg=F().regex(Wg),Qg=I().int().positive().max(2**53-1),$g=F().regex(qg),e_=F().regex(Gg),t_=L({schemaVersion:B(1),runId:Qg,prNumber:Qg,base:L({repository:$g,ref:Xg,sha:Zg}),head:L({repository:$g,repositoryId:Qg,ref:Xg,sha:Zg}),preview:L({branch:Xg,alias:Xg})}),n_=L({id:Qg,name:Xg,sizeInBytes:Qg,digest:e_}),r_=L({id:Qg,name:Xg,digest:e_}),i_=L({schemaVersion:B(1),artifacts:L({context:r_,baseStorybook:r_,headStorybook:r_})}),a_=L({schemaVersion:B(2),repository:L({id:Qg,fullName:$g}),context:t_,captureRun:L({id:Qg,runNumber:Qg,attempt:Qg,workflowId:Qg,workflowPath:Xg,headSha:Zg,headBranch:Xg,headRepositoryId:Qg,headRepository:$g}),artifacts:L({context:n_,baseStorybook:n_,headStorybook:n_,report:n_}),report:L({contentDigest:F().regex(Kg)}),trustedArtifactName:Xg});async function o_(e,t){let n=Q_(t.captureWorkflowPath),r=nv(t.baseBranch,`base branch`),i=f(t.outputDir),a=f(t.receiptPath);if(lv(i,a))throw Error(`Trusted receipt must be outside the publicly deployed report directory`);await Z_(a,`Trusted receipt`);let o=u_(t.event,n),s=await e.getWorkflowRun(o.run.id);P_(s,o),await f_(e,s);let c=p_(await e.listRunArtifacts(s.id),o),l=await Y_(t.temporaryRoot),u=!1;try{let d=await g_(e,c.context,33685504),p=f(l,`context`);x_(d),await dg(d,p,__);let m=await E_(f(p,`context.json`)),h=await D_(f(p,`changed-files.json`),m);k_(m,c.context),A_(m,o,s,r),M_(await e.getPullRequest(m.prNumber),m,o,r),await N_(e,m,n);let g=await g_(e,c.report,629145600),_=f(l,`untrusted-report`);S_(g),await dg(g,_,y_),T_(await w_(f(_,`capture-boundary.json`)),c);let ee=await vh(f(_,`report.json`));O_(ee,h),await nf(e,q_(o,m),ee);let v=await Kh({inputDir:_,outputDir:i,trustedHeadBranch:m.head.ref,trustedPullRequest:{repository:m.base.repository,number:m.prNumber,url:`https://github.com/${m.base.repository}/pull/${m.prNumber}`,baseBranch:m.base.ref,headBranch:m.head.ref,workflowRunUrl:`https://github.com/${m.base.repository}/actions/runs/${o.run.id}`},...t.storybookUrl?{storybookUrl:t.storybookUrl}:{},...t.dashboardDir?{dashboardDir:f(t.dashboardDir)}:{}});if(u=!0,!v.report.contentDigest)throw Error(`Trusted report build did not produce an image-bound content digest`);await K_(e,o,s,m,r,n);let y=F_(o,s,m,c,v.report);return await X_(a,y),{receipt:y,report:v.report,reportDirectory:i,reportPath:f(i,`report.json`),receiptPath:a,changedFiles:h}}catch(e){throw u&&await ae(i,{recursive:!0,force:!0}),e}finally{await ae(l,{recursive:!0,force:!0})}}async function s_(e,t,n){let r=await d_(n.receiptPath),i=u_(n.event,r.captureRun.workflowPath);R_(r,i);let a=await e.getWorkflowRun(r.captureRun.id);z_(a,r),await f_(e,a),await B_(e,r,i),M_(await e.getPullRequest(r.context.prNumber),r.context,i,r.context.base.ref),await N_(e,r.context,r.captureRun.workflowPath);let o=await Jh(n.reportPath,r.report.contentDigest);if(o.headBranch!==r.context.head.ref)throw Error(`Trusted report branch does not match its verified pull request context`);let s=q_(i,r.context);return await nf(e,s,o),rf(t,s,o,n.statusContext,n.reportUrl,n.commentLanguage)}async function c_(e,t){let n=Q_(t.captureWorkflowPath),r=nv(t.baseBranch,`base branch`),i=f(t.outputDir),o=f(t.receiptPath);await Z_(i,`Trusted Storybook output`);let s=await d_(o),c=u_(t.event,n);R_(s,c);let l=await e.getWorkflowRun(s.captureRun.id);z_(l,s),await f_(e,l),await B_(e,s,c),M_(await e.getPullRequest(s.context.prNumber),s.context,c,r),await N_(e,s.context,n);let u=f(t.temporaryRoot??a(i));if(lv(i,u))throw Error(`Trusted Storybook temporary root must be outside its output directory`);let d=await Y_(u),p=f(d,`storybook`);try{let t=await g_(e,s.artifacts.headStorybook,536870912);return C_(t),await dg(t,p,b_),await K_(e,c,l,s.context,r,n),await B_(e,s,c),await Z_(i,`Trusted Storybook output`),await y(a(i),{recursive:!0}),await ie(p,i),{receipt:s,receiptPath:o,context:s.context,artifact:s.artifacts.headStorybook,storybookDirectory:i}}finally{await ae(d,{recursive:!0,force:!0})}}async function l_(e,t){let n=await d_(t.receiptPath),r=u_(t.event,n.captureRun.workflowPath);R_(n,r),z_(await e.getWorkflowRun(n.captureRun.id),n);let i=t.trustedArtifactId,a=t.trustedArtifactDigest?W_(t.trustedArtifactDigest):void 0,o=[i,a];if(o.some(e=>e!==void 0)&&o.some(e=>e===void 0))throw Error(`trusted-artifact-id and trusted-artifact-digest must be provided together`);if(i!==void 0&&!av(i))throw Error(`trusted-artifact-id must be a positive integer`);let s=i!==void 0&&a!==void 0?G_():void 0,c=[];for(let t of V_(n)){let n=await e.getArtifact(t.id);n&&(H_(n,t,r),c.push({artifact:n,expected:t}))}if(i!==void 0&&a!==void 0&&s!==void 0){if(V_(n).some(e=>e.id===i))throw Error(`trusted-artifact-id must not duplicate a source artifact ID`);let t=await e.getArtifact(i);t&&(U_(t,a,s,n),c.push({artifact:t,expected:{id:t.id,name:t.name,sizeInBytes:t.sizeInBytes,digest:t.digest}}))}let l=[...new Set(c.map(({artifact:e})=>e.id))];for(let t of l)await e.deleteArtifact(t);return l}function u_(e,t){let n=sv(e,`GitHub workflow_run event`);if(n.action!==`completed`)throw Error(`Kapture trusted run requires a completed workflow_run event`);let r=sv(n.repository,`event repository`),i=$_(r.full_name,`event repository`),a=ev(i),o=iv(r.id,`event repository ID`),s=sv(n.workflow_run,`workflow_run`),c=Q_(rv(s.path,`workflow path`));if(c!==Q_(t))throw Error(`workflow_run path ${c} does not match ${t}`);if(s.status!==`completed`||s.conclusion!==`success`||s.event!==`pull_request`)throw Error(`Kapture trusted run requires one successful pull_request capture run`);let l=sv(s.head_repository,`workflow_run head repository`),u=cv(s.pull_requests,`workflow_run pull_requests`);if(u.length>1)throw Error(`workflow_run must contain at most one pull request`);let d=u[0]?J_(u[0]):void 0;return{repository:{id:o,fullName:i,ref:a},run:{id:iv(s.id,`workflow run ID`),runNumber:iv(s.run_number,`workflow run number`),attempt:iv(s.run_attempt,`workflow run attempt`),workflowId:iv(s.workflow_id,`workflow ID`),workflowPath:c,status:`completed`,conclusion:`success`,event:`pull_request`,headSha:tv(s.head_sha,`workflow run head SHA`),headBranch:nv(s.head_branch,`workflow run head branch`),headRepository:{id:iv(l.id,`workflow run head repository ID`),fullName:$_(l.full_name,`workflow run head repository`)}},...d?{pullRequest:d}:{}}}async function d_(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size<1||n.size>65536)throw Error(`Trusted receipt must be a file no larger than 65536 bytes`);let r;try{r=JSON.parse(await x(t,`utf8`))}catch{throw Error(`Trusted receipt does not contain valid JSON`)}let i=a_.safeParse(r);if(!i.success){let e=i.error.issues[0];throw Error(`Invalid trusted receipt${e?.path.length?` at ${e.path.join(`.`)}`:``}: ${e?.message??`unknown error`}`)}return L_(i.data),i.data}async function f_(e,t){let n=(await e.listWorkflowRuns(t.workflowId,t.headBranch)).filter(e=>e.headRepositoryId===t.headRepository.id).reduce((e,t)=>e?t.runNumber===e.runNumber?t.id>e.id?t:e:t.runNumber>e.runNumber?t:e:t,void 0);if(!n||n.id!==t.id)throw Error(`A newer Kapture capture run owns this repository and branch`)}function p_(e,t){let n=/^kapture-context-pr-([1-9][0-9]*)-base-([0-9a-f]{40})-head-([0-9a-f]{40})$/,r=e.filter(e=>n.test(e.name)?h_(e,t):!1);if(r.length!==1||!r[0])throw Error(`Triggering run must contain exactly one immutable Kapture context artifact`);let i=r[0];if(i.sizeInBytes>33685504)throw Error(`Kapture context artifact exceeds its compressed size limit`);let a=i.name.match(n);if(!a?.[1]||!a[2]||!a[3])throw Error(`Kapture context artifact name is invalid`);let o=`kapture-visual-report-pr-${a[1]}-base-${a[2]}-head-${a[3]}`,s=e.filter(e=>e.name===o&&h_(e,t));if(s.length!==1||!s[0])throw Error(`Triggering run must contain exactly one matching Kapture report artifact`);if(s[0].sizeInBytes>629145600)throw Error(`Kapture report artifact exceeds its compressed size limit`);let c=`pr-${a[1]}-base-${a[2]}-head-${a[3]}`,l=m_(e,`kapture-storybook-base-${c}`,t),u=m_(e,`kapture-storybook-head-${c}`,t),d=[i,l,u,s[0]];if(new Set(d.map(e=>e.id)).size!==d.length||new Set(d.map(e=>e.name)).size!==d.length)throw Error(`Kapture artifact IDs and names must be distinct`);return{context:i,baseStorybook:l,headStorybook:u,report:s[0]}}function m_(e,t,n){let r=e.filter(e=>e.name===t&&h_(e,n));if(r.length!==1||!r[0])throw Error(`Triggering run must contain exactly one non-expired ${t} artifact`);if(r[0].sizeInBytes>536870912)throw Error(`${t} exceeds its compressed size limit`);return r[0]}function h_(e,t){return!e.expired&&e.workflowRun.id===t.run.id&&e.workflowRun.repositoryId===t.repository.id&&e.workflowRun.headRepositoryId===t.run.headRepository.id&&e.workflowRun.headBranch===t.run.headBranch&&e.workflowRun.headSha===t.run.headSha&&Gg.test(e.digest)&&av(e.id)&&av(e.sizeInBytes)}async function g_(e,t,n){let r=await e.downloadArtifactArchive(t.id,n);if(r.byteLength!==t.sizeInBytes)throw Error(`Artifact ${t.id} download size does not match GitHub metadata`);if(`sha256:${m(`sha256`).update(r).digest(`hex`)}`!==t.digest)throw Error(`Artifact ${t.id} download digest does not match GitHub metadata`);return r}const __={maxEntries:2,maxFileBytes:33554432,maxTotalBytes:33619968,allowPath:e=>e===`context.json`||e===`changed-files.json`,allowDirectoryPath:()=>!1},v_=new Set([`images/`,`images/base/`,`images/head/`,`images/diff/`]),y_={maxEntries:60006,maxFileBytes:Vh,maxTotalBytes:629145600,allowPath:e=>e===`report.json`||e===`capture-boundary.json`||Yg.test(e),allowDirectoryPath:e=>v_.has(e)},b_={maxEntries:2e4,maxFileBytes:26214400,maxTotalBytes:1073741824,allowPath:()=>!0,allowDirectoryPath:()=>!0};function x_(e){let t=ug(e,__);if(t.length!==2)throw Error(`Context archive must contain exactly context.json and changed-files.json`);let n=t.find(e=>e.path===`context.json`),r=t.find(e=>e.path===`changed-files.json`);if(!n||n.uncompressedBytes<1||n.uncompressedBytes>65536||!r||r.uncompressedBytes<1||r.uncompressedBytes>33554432)throw Error(`Context archive entries are outside their fixed size contract`)}function S_(e){let t=ug(e,y_),n=new Set,r=0,i=0;for(let e of t){let t=e.path.toLocaleLowerCase(`en-US`);if(n.has(t))throw Error(`Report archive contains a case-insensitive duplicate: ${e.path}`);if(n.add(t),e.uncompressedBytes<1)throw Error(`Report archive contains an empty file: ${e.path}`);if(e.path===`report.json`&&(r+=1,e.uncompressedBytes>10485760))throw Error(`report.json exceeds its uncompressed size limit`);if(e.path===`capture-boundary.json`&&(i+=1,e.uncompressedBytes>65536))throw Error(`capture-boundary.json exceeds its uncompressed size limit`)}if(r!==1)throw Error(`Report archive must contain one root report.json file`);if(i!==1)throw Error(`Report archive must contain one root capture-boundary.json file`)}function C_(e){let t=ug(e,b_),n=new Set,r=0;for(let e of t){let t=e.path.toLocaleLowerCase(`en-US`);if(n.has(t))throw Error(`Storybook archive contains a case-insensitive duplicate: ${e.path}`);n.add(t),e.path===`index.html`&&e.uncompressedBytes>0&&(r+=1)}if(r!==1)throw Error(`Storybook archive must contain one non-empty root index.html file`)}async function w_(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch(e){throw Error(`capture-boundary.json must contain valid JSON`,{cause:e})}return i_.parse(t)}function T_(e,t){for(let n of[`context`,`baseStorybook`,`headStorybook`]){let r=e.artifacts[n],i=t[n];if(i.id!==r.id||i.name!==r.name||i.digest!==r.digest)throw Error(`Capture ${n} artifact does not match its exact downloaded identity`)}}async function E_(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch{throw Error(`Kapture context artifact does not contain valid JSON`)}let n=t_.safeParse(t);if(!n.success){let e=n.error.issues[0];throw Error(`Invalid Kapture capture context${e?.path.length?` at ${e.path.join(`.`)}`:``}: ${e?.message??`unknown error`}`)}if(n.data.preview.branch!==n.data.head.ref||n.data.preview.alias!==bg(n.data.prNumber,n.data.head.ref))throw Error(`Kapture context preview identity is not derived from its pull request branch`);return n.data}async function D_(e,t){let n=await oe(e);if(!n.isFile()||n.size<1||n.size>33554432)throw Error(`changed-files.json is outside its fixed size contract`);let r;try{r=JSON.parse(await x(e,`utf8`))}catch{throw Error(`changed-files.json does not contain valid JSON`)}let i=kg(r);if(i.pullRequest.number!==t.prNumber||i.pullRequest.baseSha!==t.base.sha||i.pullRequest.headSha!==t.head.sha)throw Error(`changed-files.json does not belong to the exact capture context`);return i}function O_(e,t){let n=e.coverage;if(!n)throw Error(`Trusted workflow reports must include audited story coverage`);let r=n.changedFilesEvidence;if(!r)throw Error(`Trusted workflow report coverage must include changed-files evidence`);let i=m(`sha256`).update(JSON.stringify(t)).digest(`hex`);if(r.provider!==t.source.provider||r.manifestDigest!==i||r.pullRequestNumber!==t.pullRequest.number||r.baseSha!==t.pullRequest.baseSha||r.headSha!==t.pullRequest.headSha)throw Error(`Trusted workflow report changed-files evidence does not match its verified context manifest`)}function k_(e,t){let n=`kapture-context-${yg(e)}`;if(t.name!==n)throw Error(`Kapture context contents do not match the immutable artifact name`)}function A_(e,t,n,r){if(e.runId!==n.id||e.base.repository!==t.repository.fullName||e.base.ref!==r||e.head.repository!==n.headRepository.fullName||e.head.repositoryId!==n.headRepository.id||e.head.ref!==n.headBranch)throw Error(`Kapture capture context does not belong to the triggering workflow run`);j_(t,e)}function j_(e,t){let n=e.pullRequest;if(n&&(n.number!==t.prNumber||n.base.repositoryId!==e.repository.id||n.base.ref!==t.base.ref||n.base.sha!==t.base.sha||n.head.repositoryId!==t.head.repositoryId||n.head.ref!==t.head.ref||n.head.sha!==t.head.sha))throw Error(`workflow_run pull request metadata conflicts with the capture context`)}function M_(e,t,n,r){if(e.number!==t.prNumber||e.state!==`open`||e.base.repository.id!==n.repository.id||e.base.repository.fullName!==t.base.repository||e.base.ref!==r||e.base.sha!==t.base.sha||e.head.repository.id!==t.head.repositoryId||e.head.repository.fullName!==t.head.repository||e.head.ref!==t.head.ref||e.head.sha!==t.head.sha)throw Error(`Kapture artifacts are stale or do not belong to the current open pull request`);j_(n,t)}async function N_(e,t,n){let[r,i]=await Promise.all([e.getContentSha(t.base.repository,n,t.base.sha),e.getContentSha(t.head.repository,n,t.head.sha)]);if(!Wg.test(r)||i!==r)throw Error(`Pull requests that modify the capture workflow require separate review before publishing`)}function P_(e,t){if(e.id!==t.run.id||e.runNumber!==t.run.runNumber||e.runAttempt!==t.run.attempt||e.workflowId!==t.run.workflowId||e.path!==t.run.workflowPath||e.status!==`completed`||e.conclusion!==`success`||e.event!==`pull_request`||e.headSha!==t.run.headSha||e.headBranch!==t.run.headBranch||e.headRepository.id!==t.run.headRepository.id||e.headRepository.fullName!==t.run.headRepository.fullName||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Triggering capture run metadata changed or no longer matches the event`)}function F_(e,t,n,r,i){if(!i.contentDigest)throw Error(`Trusted report is missing contentDigest`);if(i.headBranch!==n.head.ref)throw Error(`Trusted report branch does not match its verified pull request context`);let a=yg(n);return{schemaVersion:2,repository:{id:e.repository.id,fullName:e.repository.fullName},context:n,captureRun:{id:t.id,runNumber:t.runNumber,attempt:t.runAttempt,workflowId:t.workflowId,workflowPath:t.path,headSha:t.headSha,headBranch:t.headBranch,headRepositoryId:t.headRepository.id,headRepository:t.headRepository.fullName},artifacts:{context:I_(r.context),baseStorybook:I_(r.baseStorybook),headStorybook:I_(r.headStorybook),report:I_(r.report)},report:{contentDigest:i.contentDigest},trustedArtifactName:`kapture-trusted-report-${a}`}}function I_(e){return{id:e.id,name:e.name,sizeInBytes:e.sizeInBytes,digest:e.digest}}function L_(e){let t=yg(e.context);if(e.context.runId!==e.captureRun.id||e.context.base.repository!==e.repository.fullName||e.context.head.repository!==e.captureRun.headRepository||e.context.head.repositoryId!==e.captureRun.headRepositoryId||e.context.head.ref!==e.captureRun.headBranch||e.context.preview.branch!==e.context.head.ref||e.context.preview.alias!==bg(e.context.prNumber,e.context.head.ref)||e.artifacts.context.name!==`kapture-context-${t}`||e.artifacts.baseStorybook.name!==`kapture-storybook-base-${t}`||e.artifacts.headStorybook.name!==`kapture-storybook-head-${t}`||e.artifacts.report.name!==`kapture-visual-report-${t}`||e.trustedArtifactName!==`kapture-trusted-report-${t}`||new Set(V_(e).map(e=>e.id)).size!==4||new Set(V_(e).map(e=>e.name)).size!==4||e.artifacts.context.sizeInBytes>33685504||e.artifacts.baseStorybook.sizeInBytes>536870912||e.artifacts.headStorybook.sizeInBytes>536870912||e.artifacts.report.sizeInBytes>629145600||!Jg.test(e.captureRun.workflowPath))throw Error(`Trusted receipt fields are not internally consistent`)}function R_(e,t){if(L_(e),e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName||e.captureRun.id!==t.run.id||e.captureRun.runNumber!==t.run.runNumber||e.captureRun.attempt!==t.run.attempt||e.captureRun.workflowId!==t.run.workflowId||e.captureRun.workflowPath!==t.run.workflowPath||e.captureRun.headSha!==t.run.headSha||e.captureRun.headBranch!==t.run.headBranch||e.captureRun.headRepositoryId!==t.run.headRepository.id||e.captureRun.headRepository!==t.run.headRepository.fullName)throw Error(`Trusted receipt does not belong to the triggering workflow_run event`);j_(t,e.context)}function z_(e,t){if(e.id!==t.captureRun.id||e.runNumber!==t.captureRun.runNumber||e.runAttempt!==t.captureRun.attempt||e.workflowId!==t.captureRun.workflowId||e.path!==t.captureRun.workflowPath||e.status!==`completed`||e.conclusion!==`success`||e.event!==`pull_request`||e.headSha!==t.captureRun.headSha||e.headBranch!==t.captureRun.headBranch||e.headRepository.id!==t.captureRun.headRepositoryId||e.headRepository.fullName!==t.captureRun.headRepository||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Capture run changed after prepare-run verification`)}async function B_(e,t,n){let r=await e.listRunArtifacts(t.captureRun.id);for(let e of V_(t)){let t=r.filter(t=>t.id===e.id);if(t.length!==1||!t[0])throw Error(`Receipt-bound artifact ${e.id} is no longer available`);H_(t[0],e,n)}}function V_(e){return[e.artifacts.context,e.artifacts.baseStorybook,e.artifacts.headStorybook,e.artifacts.report]}function H_(e,t,n){if(e.id!==t.id||e.name!==t.name||e.sizeInBytes!==t.sizeInBytes||e.digest!==t.digest||!h_(e,n))throw Error(`Artifact ${t.id} no longer matches its trusted receipt binding`)}function U_(e,t,n,r){if(e.expired||e.name!==r.trustedArtifactName||e.digest!==t||e.workflowRun.id!==n||e.workflowRun.repositoryId!==r.repository.id||e.workflowRun.headRepositoryId!==r.repository.id||e.sizeInBytes>629145600)throw Error(`Trusted report artifact does not match the exact cleanup binding`)}function W_(e){let t=e.startsWith(`sha256:`)?e:`sha256:${e}`;if(!Gg.test(t))throw Error(`trusted-artifact-digest must be a 64-character SHA-256 digest`);return t}function G_(){let e=process.env.GITHUB_RUN_ID;if(!e||!/^[1-9][0-9]*$/.test(e))throw Error(`GITHUB_RUN_ID must identify the current trusted reporter workflow run`);let t=Number(e);if(!Number.isSafeInteger(t))throw Error(`GITHUB_RUN_ID must be a safe positive integer`);return t}async function K_(e,t,n,r,i,a){let o=await e.getWorkflowRun(n.id);P_(o,t),await f_(e,o),M_(await e.getPullRequest(r.prNumber),r,t,i),await N_(e,r,a)}function q_(e,t){return{repository:e.repository.ref,issueNumber:t.prNumber,headSha:t.head.sha,captureRunId:e.run.id,captureRunAttempt:e.run.attempt,captureWorkflowId:e.run.workflowId,captureRunHeadBranch:e.run.headBranch,captureRunHeadRepositoryId:e.run.headRepository.id}}function J_(e){let t=sv(e,`workflow_run pull request`),n=sv(t.base,`workflow_run pull request base`),r=sv(t.head,`workflow_run pull request head`);return{number:iv(t.number,`workflow_run pull request number`),base:{repositoryId:iv(sv(n.repo,`workflow_run pull request base repository`).id,`workflow_run pull request base repository ID`),ref:nv(n.ref,`workflow_run pull request base ref`),sha:tv(n.sha,`workflow_run pull request base SHA`)},head:{repositoryId:iv(sv(r.repo,`workflow_run pull request head repository`).id,`workflow_run pull request head repository ID`),ref:nv(r.ref,`workflow_run pull request head ref`),sha:tv(r.sha,`workflow_run pull request head SHA`)}}}async function Y_(e){let t=f(e??process.env.RUNNER_TEMP??de());return await y(t,{recursive:!0}),te(`${t}${p}kapture-prepare-`)}async function X_(e,t){let n=f(e),r=f(n,`..`);await y(r,{recursive:!0}),await se(n,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`})}async function Z_(e,t){try{await oe(e)}catch(e){if(e.code===`ENOENT`)return;throw e}throw Error(`${t} already exists: ${e}`)}function Q_(e){if(!Jg.test(e)||e.includes(`//`)||e.includes(`..`))throw Error(`capture-workflow-path must be a safe .github/workflows YAML path`);return e}function $_(e,t){let n=rv(e,`${t} full name`);if(!qg.test(n))throw Error(`${t} full name is invalid`);return n}function ev(e){let[t,n,...r]=e.split(`/`);if(!t||!n||r.length>0)throw Error(`Repository full name is invalid`);return{owner:t,repo:n}}function tv(e,t){let n=rv(e,t);if(!Wg.test(n))throw Error(`${t} must be a lowercase full SHA`);return n}function nv(e,t){let n=rv(e,t);if(ov(n))throw Error(`${t} contains control characters`);return n}function rv(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);return e}function iv(e,t){if(!av(e))throw Error(`${t} must be a positive integer`);return e}function av(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>0}function ov(e){return Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function sv(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function cv(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}function lv(e,t){let n=d(e,t);return n===``||!s(n)&&n!==`..`&&!n.startsWith(`..${p}`)}var uv=class{#e;#t;#n;constructor(e,t,n=fetch){if(!e)throw Error(`GITHUB_TOKEN is required`);this.#e=e,this.#t=t,this.#n=n}async getWorkflowRun(e){return fv(await this.#i(`GET`,`${this.#r()}/actions/runs/${e}`))}async listWorkflowRuns(e,t){let n=[];for(let r=1;r<=10;r+=1){let i=new URLSearchParams({event:`pull_request`,branch:t,per_page:`100`,page:String(r)}),a=yv(vv(await this.#i(`GET`,`${this.#r()}/actions/workflows/${e}/runs?${i}`),`workflow runs response`).workflow_runs,`workflow_runs`).map(pv);if(n.push(...a),a.length<100)return n}throw Error(`GitHub returned more than 1000 workflow runs`)}async listRunArtifacts(e){let t=[];for(let n=1;n<=10;n+=1){let r=new URLSearchParams({per_page:`100`,page:String(n)}),i=yv(vv(await this.#i(`GET`,`${this.#r()}/actions/runs/${e}/artifacts?${r}`),`artifacts response`).artifacts,`artifacts`).map(mv);if(t.push(...i),i.length<100)return t}throw Error(`GitHub returned more than 1000 workflow artifacts`)}async getArtifact(e){let t=await this.#o(`GET`,`${this.#r()}/actions/artifacts/${e}`);return t.status===404?null:(await dv(t,`GET`,`/actions/artifacts/${e}`),mv(await t.json()))}async downloadArtifactArchive(e,t){if(!Number.isSafeInteger(t)||t<=0)throw Error(`Artifact download byte limit must be positive`);let n=await this.#o(`GET`,`${this.#r()}/actions/artifacts/${e}/zip`,`manual`),r=await this.#a(n,e);await dv(r,`GET`,`/actions/artifacts/${e}/zip`);let i=r.headers.get(`content-length`);if(i!==null){let n=Number(i);if(!Number.isSafeInteger(n)||n<0||n>t)throw Error(`Artifact ${e} exceeds the ${t} byte download limit`)}if(!r.body)throw Error(`Artifact ${e} download returned no body`);let a=r.body.getReader(),o=[],s=0;try{for(;;){let{done:n,value:r}=await a.read();if(n)break;if(s+=r.byteLength,s>t)throw await a.cancel(),Error(`Artifact ${e} exceeds the ${t} byte download limit`);o.push(Buffer.from(r))}}finally{a.releaseLock()}if(s<1)throw Error(`Artifact ${e} download is empty`);return Buffer.concat(o,s)}async deleteArtifact(e){let t=await this.#o(`DELETE`,`${this.#r()}/actions/artifacts/${e}`);t.status!==404&&await dv(t,`DELETE`,`/actions/artifacts/${e}`)}async getPullRequest(e){return hv(await this.#i(`GET`,`${this.#r()}/pulls/${e}`))}async listOpenPullRequestsForHead(e,t,n){let r=_v(e),i=[];for(let e=1;e<=10;e+=1){let a=new URLSearchParams({state:`open`,base:n,head:`${r.owner}:${t}`,per_page:`100`,page:String(e)}),o=yv(await this.#i(`GET`,`${this.#r()}/pulls?${a}`),`pull requests response`).map(hv);if(i.push(...o),o.length<100)return i}throw Error(`GitHub returned more than 1000 matching pull requests`)}async getContentSha(e,t,n){let r=_v(e),i=t.split(`/`).map(encodeURIComponent).join(`/`),a=new URLSearchParams({ref:n});return Cv(vv(await this.#i(`GET`,`/repos/${encodeURIComponent(r.owner)}/${encodeURIComponent(r.repo)}/contents/${i}?${a}`),`contents response`).sha,`contents SHA`)}#r(){let{owner:e,repo:t}=this.#t;return`/repos/${encodeURIComponent(e)}/${encodeURIComponent(t)}`}async#i(e,t){let n=await this.#o(e,t);return await dv(n,e,t),n.json()}async#a(e,t){if(e.status<300||e.status>399)return e;let n=e.headers.get(`location`);if(!n)throw Error(`Artifact ${t} redirect is missing its location`);let r;try{r=new URL(n)}catch{throw Error(`Artifact ${t} redirect location is invalid`)}if(r.protocol!==`https:`||r.username||r.password)throw Error(`Artifact ${t} redirect must be a credential-free HTTPS URL`);return this.#n(r,{method:`GET`,headers:{Accept:`application/octet-stream`,"User-Agent":`kapture-cli`},redirect:`follow`})}#o(e,t,n=`follow`){return this.#n(`https://api.github.com${t}`,{method:e,headers:{Accept:`application/vnd.github+json`,Authorization:`Bearer ${this.#e}`,"X-GitHub-Api-Version":`2022-11-28`,"User-Agent":`kapture-cli`},redirect:n})}};async function dv(e,t,n){if(!e.ok)throw Error(`GitHub API ${t} ${n} failed with status ${e.status}`)}function fv(e){let t=vv(e,`workflow run`);return{id:$(t.id,`workflow run ID`),runNumber:$(t.run_number,`workflow run number`),runAttempt:$(t.run_attempt,`workflow run attempt`),workflowId:$(t.workflow_id,`workflow ID`),path:bv(t.path,`workflow path`),status:bv(t.status,`workflow run status`),conclusion:xv(t.conclusion,`workflow run conclusion`),event:bv(t.event,`workflow run event`),headSha:Cv(t.head_sha,`workflow run head SHA`),headBranch:bv(t.head_branch,`workflow run head branch`),headRepository:gv(t.head_repository,`workflow run head repository`),repository:gv(t.repository,`workflow run repository`)}}function pv(e){let t=vv(e,`workflow run candidate`);return{id:$(t.id,`workflow run ID`),runNumber:$(t.run_number,`workflow run number`),headRepositoryId:$(vv(t.head_repository,`workflow run head repository`).id,`workflow run head repository ID`)}}function mv(e){let t=vv(e,`workflow artifact`),n=vv(t.workflow_run,`artifact workflow run`);return{id:$(t.id,`artifact ID`),name:bv(t.name,`artifact name`),sizeInBytes:$(t.size_in_bytes,`artifact size`),digest:wv(t.digest,`artifact digest`),expired:Sv(t.expired,`artifact expired`),workflowRun:{id:$(n.id,`artifact workflow run ID`),repositoryId:$(n.repository_id,`artifact workflow repository ID`),headRepositoryId:$(n.head_repository_id,`artifact workflow head repository ID`),headBranch:bv(n.head_branch,`artifact workflow head branch`),headSha:Cv(n.head_sha,`artifact workflow head SHA`)}}}function hv(e){let t=vv(e,`pull request`),n=vv(t.base,`pull request base`),r=vv(t.head,`pull request head`),i=bv(t.state,`pull request state`);if(i!==`open`&&i!==`closed`)throw Error(`Pull request state is invalid`);return{number:$(t.number,`pull request number`),state:i,base:{ref:bv(n.ref,`pull request base ref`),sha:Cv(n.sha,`pull request base SHA`),repository:gv(n.repo,`pull request base repository`)},head:{ref:bv(r.ref,`pull request head ref`),sha:Cv(r.sha,`pull request head SHA`),repository:gv(r.repo,`pull request head repository`)}}}function gv(e,t){let n=vv(e,t),r=bv(n.full_name,`${t} full name`);return _v(r),{id:$(n.id,`${t} ID`),fullName:r}}function _v(e){let t=e.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!t?.[1]||!t[2])throw Error(`Repository full name is invalid`);return{owner:t[1],repo:t[2]}}function vv(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function yv(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}function $(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}function bv(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);for(let n of e){let e=n.codePointAt(0)??0;if(e<=31||e===127)throw Error(`${t} contains control characters`)}return e}function xv(e,t){return e===null?null:bv(e,t)}function Sv(e,t){if(typeof e!=`boolean`)throw Error(`${t} must be a boolean`);return e}function Cv(e,t){if(typeof e!=`string`||!/^[0-9a-f]{40}$/.test(e))throw Error(`${t} must be a lowercase full SHA`);return e}function wv(e,t){if(typeof e!=`string`||!/^sha256:[0-9a-f]{64}$/.test(e))throw Error(`${t} must be a SHA-256 digest`);return e}E();const Tv=T({meta:{name:`cleanup`,description:`Delete only exact receipt-bound Kapture artifact IDs`},args:{receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},"trusted-artifact-id":{type:`string`,description:`Exact current trusted report artifact ID`},"trusted-artifact-digest":{type:`string`,description:`upload-artifact SHA-256 digest for the current trusted report artifact`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=Dv(n),i=e[`trusted-artifact-id`]?Ev(e[`trusted-artifact-id`],`trusted-artifact-id`):void 0,a=await l_(new uv(t,r),{event:n,receiptPath:f(e.receipt),...i===void 0?{}:{trustedArtifactId:i},...e[`trusted-artifact-digest`]?{trustedArtifactDigest:e[`trusted-artifact-digest`]}:{}});await sf({"deleted-artifact-count":a.length,"deleted-artifact-ids":a.join(`,`)})}});function Ev(e,t){if(!/^[1-9][0-9]*$/.test(e))throw Error(`${t} must be a positive integer`);let n=Number(e);if(!Number.isSafeInteger(n))throw Error(`${t} must be a safe integer`);return n}function Dv(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const Ov=T({meta:{name:`context`,description:`Validate a pull request event and write immutable Kapture capture context`},args:{output:{type:`string`,required:!0,description:`Path for the normalized context JSON`},"changed-files-output":{type:`string`,required:!0,description:`Path for the versioned changed-files manifest`},"base-branch":{type:`string`,description:`Expected pull request base branch`}},async run({args:e}){let t=vg(await Kd(),e[`base-branch`]),n=process.env.GITHUB_TOKEN;if(!n)throw Error(`GITHUB_TOKEN is required`);let[r,i]=t.base.repository.split(`/`);if(!r||!i)throw Error(`Capture context repository is invalid`);let o=await Og(new Ud(n,{owner:r,repo:i}),t),s=f(e.output),c=f(e[`changed-files-output`]);if(s===c)throw Error(`output and changed-files-output must be different paths`);await Promise.all([y(a(s),{recursive:!0}),y(a(c),{recursive:!0})]),await Promise.all([se(s,`${JSON.stringify(t,null,2)}\n`,{flag:`wx`}),se(c,`${JSON.stringify(o,null,2)}\n`,{flag:`wx`})]),await sf({"artifact-suffix":yg(t),"base-repository":t.base.repository,"base-ref":t.base.ref,"base-sha":t.base.sha,"changed-files-complete":String(o.complete),"changed-files-count":o.files.length,"changed-files-path":c,"context-path":s,"head-repository":t.head.repository,"head-repository-id":t.head.repositoryId,"head-ref":t.head.ref,"head-sha":t.head.sha,"pr-number":t.prNumber,"preview-branch":t.preview.branch,"preview-alias":t.preview.alias})}}),kv=/^[0-9a-f]{40}$/,Av=/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/,jv=/^\.github\/workflows\/[A-Za-z0-9_./-]+\.ya?ml$/,Mv=`Base branch changed; rerun visual capture`,Nv=new Set([`action_required`,`cancelled`,`failure`,`neutral`,`skipped`,`stale`,`startup_failure`,`success`,`timed_out`]);async function Pv(e,t,n){let r=ey(n.captureWorkflowPath),i=iy(n.baseBranch,`base branch`),a=Md(n.statusContext),o=Lv(n.event,r),s=await Rv(e,o,i);if(!s.ok)return Zv(s.reason);if(await Uv(t,o,s.target))return Zv(`final-report-exists`,s.target);let c=await Rv(e,o,i);if(!c.ok)return Zv(c.reason,s.target);if(!Xv(s.target,c.target))return Zv(`pull-request-changed`,c.target);if(await Uv(t,o,c.target))return Zv(`final-report-exists`,c.target);let l=Jv(o,c.target);return await t.setReviewStatus(c.target.headSha,l.state,l.description,a),{status:l.state,reason:`status-written`,prNumber:c.target.prNumber,headSha:c.target.headSha}}async function Fv(e,t,n){let r=ey(n.captureWorkflowPath),i=iy(n.baseBranch,`base branch`),a=Md(n.statusContext),o=Iv(n.event,r),s=await Rv(e,o,i);if(!s.ok)return Qv(s.reason);let c=Gv(o,await Wv(t,o,s.target,a),s.target);if(c)return Qv(c,s.target);let l=await Rv(e,o,i);if(!l.ok)return Qv(l.reason,s.target);if(!Xv(s.target,l.target))return Qv(`pull-request-changed`,l.target);let u=Gv(o,await Wv(t,o,l.target,a),l.target);if(u)return Qv(u,l.target);let d=l.target.baseDrift?Mv:o.run.conclusion===`success`?`Visual report publication did not complete`:`Visual capture did not succeed (${o.run.conclusion})`;return await t.setReviewStatus(l.target.headSha,`error`,d,a),{status:`error`,reason:`status-written`,prNumber:l.target.prNumber,headSha:l.target.headSha}}function Iv(e,t){let n=Lv(e,t);if(n.run.status!==`completed`)throw Error(`Kapture finalize-run requires a completed workflow_run event`);return{...n,run:{...n.run,status:`completed`}}}function Lv(e,t){let n=ly(e,`GitHub workflow_run event`),r=oy(n.action,`workflow_run action`);if(r!==`in_progress`&&r!==`completed`)throw Error(`Kapture reconcile-run requires an in_progress or completed workflow_run event`);let i=ly(n.repository,`event repository`),a=ty(i.full_name,`event repository`),o=sy(i.id,`event repository ID`),s=ly(n.workflow_run,`workflow_run`),c=ey(oy(s.path,`workflow path`));if(c!==ey(t))throw Error(`workflow_run path ${c} does not match ${t}`);if(s.event!==`pull_request`)throw Error(`Kapture reconcile-run requires a pull_request capture run`);let l=oy(s.status,`workflow run status`),u=ay(s.conclusion,`workflow run conclusion`);if(r===`in_progress`&&(l!==`in_progress`||u!==null))throw Error(`An in_progress workflow_run event must describe an unfinished run`);if(r===`completed`&&(l!==`completed`||u===null||!Nv.has(u)))throw Error(`A completed workflow_run event must have a supported conclusion`);let d=ly(s.head_repository,`workflow_run head repository`),f={id:sy(d.id,`workflow run head repository ID`),fullName:ty(d.full_name,`workflow run head repository`)},p=iy(s.head_branch,`workflow run head branch`),m=uy(s.pull_requests,`workflow_run pull requests`);if(m.length>1)throw Error(`workflow_run must contain at most one pull request`);let h=m[0]?$v(m[0]):void 0;if(h&&(h.base.repositoryId!==o||h.head.repositoryId!==f.id||h.head.ref!==p))throw Error(`workflow_run pull request metadata conflicts with run provenance`);return{repository:{id:o,fullName:a,ref:ny(a)},run:{id:sy(s.id,`workflow run ID`),runNumber:sy(s.run_number,`workflow run number`),attempt:sy(s.run_attempt,`workflow run attempt`),workflowId:sy(s.workflow_id,`workflow ID`),workflowPath:c,status:l,conclusion:u,event:`pull_request`,headSha:ry(s.head_sha,`workflow run head SHA`),headBranch:p,headRepository:f},...h?{pullRequest:h}:{}}}async function Rv(e,t,n){let r=await e.getWorkflowRun(t.run.id);return zv(r,t),r.runAttempt===t.run.attempt?r.status!==t.run.status||r.conclusion!==t.run.conclusion?{ok:!1,reason:`stale-run-state`}:await Bv(e,r)?Vv(e,t,n):{ok:!1,reason:`superseded-run`}:{ok:!1,reason:`stale-run-attempt`}}function zv(e,t){if(e.id!==t.run.id||e.runNumber!==t.run.runNumber||e.workflowId!==t.run.workflowId||ey(e.path)!==t.run.workflowPath||e.event!==`pull_request`||e.headSha!==t.run.headSha||e.headBranch!==t.run.headBranch||e.headRepository.id!==t.run.headRepository.id||e.headRepository.fullName!==t.run.headRepository.fullName||e.repository.id!==t.repository.id||e.repository.fullName!==t.repository.fullName)throw Error(`Triggering capture run identity no longer matches the workflow_run event`)}async function Bv(e,t){let n=(await e.listWorkflowRuns(t.workflowId,t.headBranch)).filter(e=>e.headRepositoryId===t.headRepository.id);if(n.filter(e=>e.id===t.id).some(e=>e.runNumber!==t.runNumber))throw Error(`Latest workflow run metadata conflicts with the triggering run`);return n.reduce((e,t)=>e?t.runNumber===e.runNumber?t.id>e.id?t:e:t.runNumber>e.runNumber?t:e:t,void 0)?.id===t.id}async function Vv(e,t,n){if(t.pullRequest){if(t.pullRequest.base.ref!==n)return{ok:!1,reason:`base-branch-mismatch`};let r=await e.getPullRequest(t.pullRequest.number);return Hv(r,t,n)?{ok:!0,target:Yv(r,r.base.sha!==t.pullRequest.base.sha)}:{ok:!1,reason:`pull-request-not-current`}}let r=(await e.listOpenPullRequestsForHead(t.run.headRepository.fullName,t.run.headBranch,n)).filter(e=>e.state===`open`&&e.base.repository.id===t.repository.id&&e.base.repository.fullName===t.repository.fullName&&e.base.ref===n&&e.head.repository.id===t.run.headRepository.id&&e.head.repository.fullName===t.run.headRepository.fullName&&e.head.ref===t.run.headBranch);return r.length===0?{ok:!1,reason:`pull-request-not-found`}:r.length===1?{ok:!0,target:Yv(r[0])}:{ok:!1,reason:`pull-request-ambiguous`}}function Hv(e,t,n){let r=t.pullRequest;return!!(r&&e.number===r.number&&e.state===`open`&&e.base.repository.id===t.repository.id&&e.base.repository.fullName===t.repository.fullName&&e.base.ref===n&&e.head.repository.id===t.run.headRepository.id&&e.head.repository.fullName===t.run.headRepository.fullName&&e.head.ref===t.run.headBranch&&e.head.sha===r.head.sha)}async function Uv(e,t,n){return qv(await e.findCurrentReportMarker(n.prNumber,n.baseSha,n.headSha),t)}async function Wv(e,t,n,r){let i=await e.findCurrentReportMarker(n.prNumber,n.baseSha,n.headSha),a=await e.getLatestReviewStatus(n.headSha,r);return{marker:qv(i,t)?i:null,status:a}}function Gv(e,t,n){return n.baseDrift&&t.status?.state===`error`&&t.status.description===Mv?`base-drift-already-recorded`:e.run.conclusion===`success`?Kv(t)?`final-report-exists`:t.status?.state===`error`&&t.status.description===`Visual report publication did not complete`?`publication-failure-already-recorded`:void 0:t.status?.state===`error`?`capture-failure-already-recorded`:void 0}function Kv(e){let{marker:t,status:n}=e;return!t?.reportUrl||!n||t.reportUrl!==n.targetUrl?!1:t.status===`clean`?n.state===`success`&&n.description===`No visual changes`:t.status===`changed`?n.state===`pending`&&n.description===`Visual changes require approval`:n.state===`failure`}function qv(e,t){return!!(e&&e.captureRunId===t.run.id&&e.captureRunAttempt===t.run.attempt&&e.captureWorkflowId===t.run.workflowId&&e.captureRunHeadBranch===t.run.headBranch&&e.captureRunHeadRepositoryId===t.run.headRepository.id)}function Jv(e,t){return t.baseDrift?{state:`error`,description:Mv}:e.run.status===`in_progress`?{state:`pending`,description:`Visual capture is in progress`}:e.run.conclusion===`success`?{state:`pending`,description:`Visual report is awaiting publication`}:{state:`error`,description:`Visual capture did not succeed (${e.run.conclusion})`}}function Yv(e,t=!1){return{prNumber:e.number,baseSha:e.base.sha,headSha:e.head.sha,baseDrift:t}}function Xv(e,t){return e.prNumber===t.prNumber&&e.baseSha===t.baseSha&&e.headSha===t.headSha&&e.baseDrift===t.baseDrift}function Zv(e,t){return{status:`noop`,reason:e,...t?{prNumber:t.prNumber,headSha:t.headSha}:{}}}function Qv(e,t){return{status:`noop`,reason:e,...t?{prNumber:t.prNumber,headSha:t.headSha}:{}}}function $v(e){let t=ly(e,`workflow_run pull request`),n=ly(t.base,`workflow_run pull request base`),r=ly(t.head,`workflow_run pull request head`);return{number:sy(t.number,`workflow_run pull request number`),base:{repositoryId:sy(ly(n.repo,`workflow_run pull request base repository`).id,`workflow_run pull request base repository ID`),ref:iy(n.ref,`workflow_run pull request base ref`),sha:ry(n.sha,`workflow_run pull request base SHA`)},head:{repositoryId:sy(ly(r.repo,`workflow_run pull request head repository`).id,`workflow_run pull request head repository ID`),ref:iy(r.ref,`workflow_run pull request head ref`),sha:ry(r.sha,`workflow_run pull request head SHA`)}}}function ey(e){if(!jv.test(e)||e.includes(`//`)||e.includes(`..`))throw Error(`capture-workflow-path must be a safe .github/workflows YAML path`);return e}function ty(e,t){let n=oy(e,`${t} full name`);if(!Av.test(n))throw Error(`${t} full name is invalid`);return n}function ny(e){let[t,n,...r]=e.split(`/`);if(!t||!n||r.length>0)throw Error(`Repository full name is invalid`);return{owner:t,repo:n}}function ry(e,t){let n=oy(e,t);if(!kv.test(n))throw Error(`${t} must be a lowercase full SHA`);return n}function iy(e,t){let n=oy(e,t);if(cy(n))throw Error(`${t} contains control characters`);return n}function ay(e,t){return e===null?null:oy(e,t)}function oy(e,t){if(typeof e!=`string`||e.length<1||e.length>512)throw Error(`${t} must be a non-empty bounded string`);if(cy(e))throw Error(`${t} contains control characters`);return e}function sy(e,t){if(typeof e!=`number`||!Number.isSafeInteger(e)||e<=0)throw Error(`${t} must be a positive integer`);return e}function cy(e){return Array.from(e).some(e=>{let t=e.codePointAt(0)??0;return t<=31||t===127})}function ly(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`${t} must be an object`);return e}function uy(e,t){if(!Array.isArray(e))throw Error(`${t} must be an array`);return e}E();const dy=T({meta:{name:`finalize-run`,description:`Close an unfinished status for the exact completed trusted workflow run`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=fy(n),i=await Fv(new uv(t,r),new Ud(t,r),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],statusContext:Md(e[`status-context`])});await sf({status:i.status,"finalize-reason":i.reason,...i.prNumber===void 0?{}:{"pr-number":i.prNumber},...i.headSha?{"head-sha":i.headSha}:{}})}});function fy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const py=T({meta:{name:`prepare-run`,description:`Download, verify, and rebuild a completed workflow_run report`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},output:{type:`string`,default:`.kapture/trusted-report`,description:`New directory for the trusted static report`},receipt:{type:`string`,default:`.kapture/trusted-run-receipt.json`,description:`Path for the strict trusted-run receipt`},"storybook-url":{type:`string`,description:`Trusted HTTPS Storybook URL or the fixed same-origin ./storybook/ directory`},"temporary-root":{type:`string`,description:`Trusted temporary directory root (defaults to RUNNER_TEMP)`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=await o_(new uv(t,my(n)),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],outputDir:f(e.output),receiptPath:f(e.receipt),...e[`storybook-url`]?{storybookUrl:e[`storybook-url`]}:{},...e[`temporary-root`]?{temporaryRoot:f(e[`temporary-root`])}:{}});await sf({"base-sha":r.receipt.context.base.sha,"context-artifact-id":r.receipt.artifacts.context.id,"head-repository":r.receipt.context.head.repository,"head-sha":r.receipt.context.head.sha,"pr-number":r.receipt.context.prNumber,"preview-branch":r.receipt.context.preview.branch,"preview-alias":r.receipt.context.preview.alias,"raw-report-artifact-id":r.receipt.artifacts.report.id,"report-digest":r.receipt.report.contentDigest,"report-directory":r.reportDirectory,"report-path":r.reportPath,receipt:r.receiptPath,"run-attempt":r.receipt.captureRun.attempt,"run-head-branch":r.receipt.captureRun.headBranch,"run-head-repository-id":r.receipt.captureRun.headRepositoryId,"run-head-sha":r.receipt.captureRun.headSha,"run-id":r.receipt.captureRun.id,"changed-files-complete":String(r.changedFiles.complete),"changed-files-count":r.changedFiles.files.length,"trusted-artifact-name":r.receipt.trustedArtifactName,"workflow-id":r.receipt.captureRun.workflowId})}});function my(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const hy=T({meta:{name:`prepare-storybook-run`,description:`Verify and extract the exact receipt-bound head Storybook artifact`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},output:{type:`string`,required:!0,description:`New directory for the verified head Storybook`},receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},"temporary-root":{type:`string`,description:`Trusted temporary directory root (defaults beside output)`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=await c_(new uv(t,gy(n)),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],outputDir:f(e.output),receiptPath:f(e.receipt),...e[`temporary-root`]?{temporaryRoot:f(e[`temporary-root`])}:{}});await sf({"head-ref":r.context.head.ref,"head-repository":r.context.head.repository,"head-sha":r.context.head.sha,"head-storybook-artifact-id":r.artifact.id,"pr-number":r.context.prNumber,"preview-branch":r.context.preview.branch,"preview-alias":r.context.preview.alias,receipt:r.receiptPath,"storybook-directory":r.storybookDirectory})}});function gy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const _y=T({meta:{name:`publish-run`,description:`Revalidate a prepare-run receipt and publish its deployed visual report`},args:{receipt:{type:`string`,required:!0,description:`Path to the strict prepare-run receipt`},report:{type:`string`,required:!0,description:`Path to the trusted image-bound report.json`},"report-url":{type:`string`,required:!0,description:`Immutable HTTPS URL of the deployed dashboard`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`},"comment-language":{type:`string`,default:`en`,description:`PR comment language (en or ko)`}},async run({args:e}){try{let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=vy(n),i=Ad(e[`report-url`]);if(!i)throw Error(`report-url is required`);let a=await s_(new uv(t,r),new Ud(t,r),{event:n,receiptPath:f(e.receipt),reportPath:f(e.report),reportUrl:i,statusContext:Md(e[`status-context`]),commentLanguage:bd(e[`comment-language`])});if(await sf({status:a.status,"changed-count":a.changedCount,"comment-id":a.commentId,"report-digest":a.reportDigest}),a.status===`error`)throw Error(`Visual capture errors were published to the trusted report`)}catch(e){throw await sf({status:`error`}),e}}});function vy(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E();const yy=T({meta:{name:`reconcile-run`,description:`Reconcile a trusted workflow_run event with the current PR status`},args:{"capture-workflow-path":{type:`string`,default:`.github/workflows/visual-capture.yml`,description:`Trusted path of the pull_request capture workflow`},"base-branch":{type:`string`,required:!0,description:`Expected pull request base branch`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await Kd(),r=by(n),i=await Pv(new uv(t,r),new Ud(t,r),{event:n,captureWorkflowPath:e[`capture-workflow-path`],baseBranch:e[`base-branch`],statusContext:Md(e[`status-context`])});await sf({status:i.status,"reconcile-reason":i.reason,...i.prNumber===void 0?{}:{"pr-number":i.prNumber},...i.headSha?{"head-sha":i.headSha}:{}})}});function by(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`GitHub event payload must be an object`);let t=e.repository;if(!t||typeof t!=`object`||Array.isArray(t))throw Error(`GitHub event repository must be an object`);let n=t.full_name;if(typeof n!=`string`)throw Error(`GitHub event repository is invalid`);let r=n.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);if(!r?.[1]||!r[2])throw Error(`GitHub event repository is invalid`);return{owner:r[1],repo:r[2]}}E(),zh();const xy=T({meta:{name:`report`,description:`Publish a trusted Kapture PR report and commit status`},args:{report:{type:`string`,required:!0,description:`Path to image-bound trusted report.json`},"report-url":{type:`string`,description:`HTTPS URL for the full report or workflow run`},"status-context":{type:`string`,default:`Kapture Visual Review`,description:`GitHub commit status context`},"comment-language":{type:`string`,default:`en`,description:`PR comment language (en or ko)`}},async run({args:e}){try{let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await vh(e.report),r=qd(await Kd()),i=Md(e[`status-context`]),a=Ad(e[`report-url`]),o=await rf(new Ud(t,r.repository),r,n,i,a,bd(e[`comment-language`]));if(await sf({status:o.status,"changed-count":o.changedCount,"comment-id":o.commentId,"report-digest":o.reportDigest}),o.status===`error`)throw Error(`${n.summary.errors} visual capture error(s)`)}catch(e){throw await sf({status:`error`}),e}}});E(),zh();const Sy=T({meta:{name:`verify`,description:`Verify that a Kapture report matches the current pull request`},args:{report:{type:`string`,required:!0,description:`Path to untrusted report.json`}},async run({args:e}){let t=process.env.GITHUB_TOKEN;if(!t)throw Error(`GITHUB_TOKEN is required`);let n=await vh(e.report),r=qd(await Kd());await nf(new Ud(t,r.repository),r,n)}});E();const Cy=T({meta:{name:`github`,description:`Verify, publish, and approve GitHub visual reviews`},subCommands:{context:Ov,verify:Sy,report:xy,approve:cf,"prepare-run":py,"prepare-storybook-run":hy,"publish-run":_y,"reconcile-run":yy,"finalize-run":dy,cleanup:Tv}});async function wy(e,t){let{report:n,resolveImage:r}=await Ty(e),i=n.entries[t];if(!i)throw Error(`Kapture report does not contain snapshot ${t}`);let a=[],o=(e,t)=>{t&&(Ay(e,t),a.push({role:e,mediaType:`image/png`,source:r(t)}))};return o(`base`,i.baseImage),o(`head`,i.headImage),o(`diff`,i.diffImage),o(`base-repeat`,i.instability?.base?.repeatImage),o(`base-instability-diff`,i.instability?.base?.diffImage),o(`head-repeat`,i.instability?.head?.repeatImage),o(`head-instability-diff`,i.instability?.head?.diffImage),{version:1,report:{baseRevision:n.baseRevision,headRevision:n.headRevision,...n.contentDigest?{contentDigest:n.contentDigest}:{}},snapshot:{id:i.id,storyId:i.storyId,title:i.title,name:i.name,viewport:i.viewport,status:i.status,...i.changedPixels===void 0?{}:{changedPixels:i.changedPixels},...i.diffRatio===void 0?{}:{diffRatio:i.diffRatio},...i.threshold?{threshold:i.threshold}:{},...i.error?{error:i.error}:{}},images:a}}async function Ty(e){let t=ky(e);return t?Dy(t):Ey(e)}async function Ey(e){let t=f(e),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r=Oy(await x(t,`utf8`)),i=a(t);return{report:r,resolveImage:e=>{let t=f(i,e);if(d(i,t).startsWith(`..`))throw Error(`Kapture report contains an unsafe image path: ${e}`);return{type:`path`,value:t}}}}async function Dy(e){let t=await fetch(e,{redirect:`error`});if(!t.ok)throw Error(`Kapture report request failed with HTTP ${t.status}`);let n=Number(t.headers.get(`content-length`));if(Number.isFinite(n)&&n>10485760)throw Error(`Kapture report must be no larger than ${bh} bytes`);let r=await t.text();if(Buffer.byteLength(r)>10485760)throw Error(`Kapture report must be no larger than ${bh} bytes`);return{report:Oy(r),resolveImage:t=>{let n=new URL(t,e);if(n.origin!==e.origin||n.protocol!==`https:`)throw Error(`Kapture report contains an unsafe image URL: ${t}`);return{type:`url`,value:n.toString()}}}}function Oy(e){try{return gh(JSON.parse(e))}catch(e){throw e instanceof SyntaxError?Error(`Kapture report does not contain valid JSON`):e}}function ky(e){let t;try{t=new URL(e)}catch{return}if(t.protocol!==`https:`||t.username||t.password)throw Error(`Remote Kapture report must be an HTTPS URL without credentials`);return t}function Ay(e,t){let n=`images/${e}/`,r=t.slice(n.length);if(!t.startsWith(n)||!r||r.includes(`/`)||r.includes(`\\`)||!r.endsWith(`.png`))throw Error(`Kapture report contains an invalid ${e} image path: ${t}`)}var jy,My=S((()=>{E(),zh(),jy=T({meta:{name:`inspect`,description:`Print machine-readable snapshot evidence for agents and review tools`},args:{report:{type:`string`,required:!0,description:`Local report.json path or public HTTPS report.json URL`},snapshot:{type:`string`,required:!0,description:`Exact snapshot ID`}},async run({args:e}){let t=await wy(e.report,e.snapshot);process.stdout.write(`${JSON.stringify(t,null,2)}\n`)}})})),Ny=S((()=>{wc()})),Py=S((()=>{Ny()})),Fy=we({createKaptureMcpServer:()=>Ly,getSnapshotEvidenceResult:()=>Ry,startKaptureMcpServer:()=>Iy});async function Iy(e){let{serveStdio:t}=await import(`@modelcontextprotocol/server/stdio`);t(()=>Ly(e),{onerror:e=>console.error(e.message)})}async function Ly(e){let{McpServer:t}=await import(`@modelcontextprotocol/server`),n=new t({name:`kapture`,version:et},{instructions:`Use list_snapshots to find visual changes, then get_snapshot_evidence to inspect the exact PNG evidence. Unstable snapshots are nondeterministic and do not represent an approvable baseline change.`});return n.registerTool(`list_snapshots`,{title:`List Kapture snapshots`,description:`List snapshot IDs, statuses, stories, viewports, and diff metrics from a report.`,inputSchema:hs({status:z([`unchanged`,`changed`,`unstable`,`added`,`removed`,`error`]).optional().describe(`Optional exact status filter`)}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({status:t})=>{let{report:n}=await Ty(e),r=Object.values(n.entries).filter(e=>!t||e.status===t).map(e=>({id:e.id,storyId:e.storyId,title:e.title,name:e.name,viewport:e.viewport,status:e.status,changedPixels:e.changedPixels,changedPixelPercentage:e.diffRatio===void 0?void 0:e.diffRatio*100})),i={baseRevision:n.baseRevision,headRevision:n.headRevision,summary:n.summary,snapshots:r};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}],structuredContent:i}}),n.registerTool(`get_snapshot_evidence`,{title:`Get Kapture snapshot evidence`,description:`Return machine-readable metadata and the actual base, head, diff, and instability PNGs for one snapshot.`,inputSchema:hs({snapshotId:F().min(1).max(512).describe(`Exact ID returned by list_snapshots`)}),annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0}},async({snapshotId:t})=>Ry(e,t)),n}async function Ry(e,t){let n=await wy(e,t),r=await Promise.all(n.images.map(zy));return{content:[{type:`text`,text:JSON.stringify(Uy(n),null,2)},...r],structuredContent:Uy(n)}}async function zy(e){return{type:`image`,data:(e.source.type===`path`?await By(e.source.value):await Vy(e.source.value)).toString(`base64`),mimeType:`image/png`,_meta:{"kapture/role":e.role}}}async function By(e){let t=await v(e);if(t.isSymbolicLink()||!t.isFile()||t.size>Wy)throw Error(`Kapture evidence image must be no larger than ${Wy} bytes`);return Hy(await x(e),e)}async function Vy(e){let t=await fetch(e,{redirect:`error`});if(!t.ok)throw Error(`Kapture evidence request failed with HTTP ${t.status}`);let n=Number(t.headers.get(`content-length`));if(Number.isFinite(n)&&n>Wy)throw Error(`Kapture evidence image must be no larger than ${Wy} bytes`);return Hy(Buffer.from(await t.arrayBuffer()),e)}function Hy(e,t){if(e.byteLength>Wy||!e.subarray(0,8).equals(Gy))throw Error(`Kapture evidence is not a supported PNG: ${t}`);return e}function Uy(e){return{...e,images:e.images.map(t=>({role:t.role,mediaType:t.mediaType,source:t.source,contentBlockIndex:e.images.indexOf(t)+1}))}}var Wy,Gy,Ky=S((()=>{Py(),My(),Wy=26214400,Gy=Buffer.from([137,80,78,71,13,10,26,10])}));E();const qy=T({meta:{name:`mcp`,description:`Serve Kapture snapshot evidence to agents over MCP stdio`},args:{report:{type:`string`,required:!0,description:`Local report.json path or public HTTPS report.json URL`}},async run({args:e}){let{startKaptureMcpServer:t}=await Promise.resolve().then(()=>(Ky(),Fy));await t(e.report)}});_d(),E();const Jy=T({meta:{name:`plan`,description:`Select affected Storybook stories from base/head dependency manifests`},args:{"base-dir":{type:`string`,required:!0,description:`Built base Storybook directory`},"head-dir":{type:`string`,required:!0,description:`Built head Storybook directory`},"changed-files":{type:`string`,required:!0,description:`Path to a versioned changed-files manifest or legacy JSON path array`},output:{type:`string`,default:`.kapture/plan.json`,description:`Affected-story plan output path`}},async run({args:e}){let t=await Yy(f(e[`changed-files`])),n=await vl({baseDir:f(e[`base-dir`]),headDir:f(e[`head-dir`]),changedFiles:t.files,changedFilesComplete:t.complete,...t.evidence?{changedFilesEvidence:t.evidence}:{}}),r=f(e.output);await y(a(r),{recursive:!0}),await se(r,`${JSON.stringify(n,null,2)}\n`,`utf8`),n.selectionMode===`affected`?X.success(`Selected ${n.selectedStoryIds.length} of ${n.totalStoryIds.length} affected stories`):X.warn(`Selected all ${n.totalStoryIds.length} stories (${n.fallbackReasons.map(e=>e.code).join(`, `)})`),X.info(`Plan: ${r}`)}});async function Yy(e){let t;try{t=JSON.parse(await x(e,`utf8`))}catch(t){throw Error(`Failed to read changed files JSON from ${e}`,{cause:t})}if(!Array.isArray(t)){let e=kg(t);return{files:e.files,complete:e.complete,evidence:{provider:e.source.provider,manifestDigest:m(`sha256`).update(JSON.stringify(e)).digest(`hex`),pullRequestNumber:e.pullRequest.number,baseSha:e.pullRequest.baseSha,headSha:e.pullRequest.headSha}}}if(t.length>1e5)throw Error(`changed-files contains too many paths`);return{files:t.map(e=>Ag(e,`changed file path`)),complete:!0}}E();const Xy=T({meta:{name:`report`,description:`Build trusted static Kapture reports`},subCommands:{build:Gh}});_d(),E();const Zy=T({meta:{name:`test`,description:`Capture and compare base/head Storybooks in one hermetic browser environment`},args:{"base-dir":{type:`string`,required:!0,description:`Built base Storybook directory`},"head-dir":{type:`string`,required:!0,description:`Built head Storybook directory`},"base-capture-dir":{type:`string`,description:`Verified capture directory for the exact base revision; captures head only`},"base-revision":{type:`string`,required:!0,description:`Base Git revision`},"head-revision":{type:`string`,required:!0,description:`Head Git revision`},"changed-files":{type:`string`,description:`Versioned changed-files manifest used to capture only provably affected stories`},"install-browser":{type:`boolean`,default:!1,description:`Install the pinned Chrome runtime only when at least one story is selected`},"browser-with-deps":{type:`boolean`,default:!1,description:`Install Linux browser dependencies together with Chrome`},output:{type:`string`,default:`.kapture`,description:`Output directory`},workers:{type:`string`,default:`4`,description:`Concurrent isolated story lanes`},"pixel-color-threshold":{type:`string`,default:`0.2`,description:`Per-pixel perceptual color threshold`},"max-changed-pixel-percentage":{type:`string`,default:`0`,description:`Maximum percentage of changed pixels allowed without review (0 to 100)`},"frozen-time":{type:`string`,default:`2026-01-01T00:00:00.000Z`,description:`ISO time exposed to stories`},"random-seed":{type:`string`,default:`20260101`,description:`Math.random seed`},locale:{type:`string`,default:`en-US`,description:`BCP 47 browser locale`},timezone:{type:`string`,default:`UTC`,description:`IANA browser time zone`},"dashboard-dir":{type:`string`,description:`Dashboard build directory (defaults to the CLI embedded dashboard)`}},async run({args:e}){let t=nb(e.workers),n=rb(e[`pixel-color-threshold`],`pixel-color-threshold`),r=ib(e[`max-changed-pixel-percentage`],`max-changed-pixel-percentage`),i=tb(e[`random-seed`],`random-seed`),o=f(e[`base-dir`]),s=f(e[`head-dir`]),c=e[`changed-files`]?await Qy(o,s,f(e[`changed-files`]),e[`base-revision`],e[`head-revision`]):void 0;eb(c),e[`install-browser`]&&$y(c)&&(X.start(`Installing the Kapture browser runtime…`),await nt(e[`browser-with-deps`])),X.start(e[`base-capture-dir`]?`Reusing the verified base capture and capturing affected head stories…`:`Capturing base and head Storybooks in one hermetic environment…`);let l=await fu({baseDir:o,headDir:s,...e[`base-capture-dir`]?{baseCaptureDir:f(e[`base-capture-dir`])}:{},baseRevision:e[`base-revision`],headRevision:e[`head-revision`],outputDir:f(e.output),workers:t,threshold:{pixelColorThreshold:n,maxChangedPixelRatio:r/100},frozenTime:e[`frozen-time`],randomSeed:i,locale:e.locale,timezone:e.timezone,adapterVersion:et,selectionPlan:c});await Iu(e[`dashboard-dir`]?f(e[`dashboard-dir`]):f(a(me(import.meta.url)),`dashboard`),f(e.output,`report`));let{summary:u}=l.report;X.success(`${u.total} snapshots: ${u.changed} changed, ${u.unstable} unstable, ${u.added} added, ${u.removed} removed, ${u.unchanged} unchanged, ${u.errors} errors`),X.info(`Environment: ${l.report.environment.id}`),X.info(`Report: ${f(e.output,`report`,`report.json`)}`),u.errors>0&&(process.exitCode=2)}});async function Qy(e,t,n,r,i){let a=await Yy(n);if(a.evidence&&(a.evidence.baseSha!==r||a.evidence.headSha!==i))throw Error(`changed-files manifest base/head SHAs must match --base-revision and --head-revision`);return vl({baseDir:e,headDir:t,changedFiles:a.files,changedFilesComplete:a.complete,...a.evidence?{changedFilesEvidence:a.evidence}:{}})}function $y(e){return!e||e.selectedStoryIds.length>0}function eb(e){if(!e){X.info(`Story coverage: full capture (no changed-files manifest)`);return}if(e.selectionMode===`affected`){X.info(`Story coverage: ${e.selectedStoryIds.length} affected, ${e.skippedStoryIds.length} proven unaffected`);return}X.warn(`Story coverage: full fallback (${e.fallbackReasons.map(e=>e.code).join(`, `)})`)}function tb(e,t){let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0)throw Error(`${t} must be a positive integer`);return n}function nb(e){let t=tb(e,`workers`);if(t>8)throw Error(`workers must be between 1 and 8`);return t}function rb(e,t){let n=Number.parseFloat(e);if(!Number.isFinite(n)||n<0||n>1)throw Error(`${t} must be between 0 and 1`);return n}function ib(e,t){let n=Number(e);if(!Number.isFinite(n)||n<0||n>100)throw Error(`${t} must be between 0 and 100`);return n}E(),zh();const ab=T({meta:{name:`validate`,description:`Validate a Kapture report as a CI gate`},args:{report:{type:`string`,required:!0,description:`Path to report.json`},"fail-on-diff":{type:`boolean`,default:!1,description:`Exit 1 when visual changes require review`}},async run({args:e}){let t=f(e.report),n=await oe(t);if(!n.isFile()||n.size>10485760)throw Error(`Kapture report must be a file no larger than ${bh} bytes`);let r=gh(JSON.parse(await x(t,`utf8`)));if(r.summary.errors>0){X.error(`${r.summary.errors} capture or comparison error(s)`),process.exitCode=2;return}let i=r.summary.changed+r.summary.added+r.summary.removed;if(r.summary.unstable>0&&X.warn(`${r.summary.unstable} unstable snapshot(s) are non-blocking`),i>0&&e[`fail-on-diff`]){X.warn(`${i} visual change(s) require human approval`),process.exitCode=1;return}X.success(i>0?`${i} visual change(s) detected`:`No visual changes`)}});E(),My(),Ge(T({meta:{name:`kapture`,version:et,description:`Hermetic Storybook visual review`},subCommands:{test:Zy,validate:ab,browser:rt,plan:Jy,report:Xy,github:Cy,inspect:jy,mcp:qy}}));export{};