@uicopilot/storybook-addon 0.18.3 → 0.19.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/README.md +26 -14
- package/dist/manager.mjs +94 -90
- package/dist/preset.js +3 -3
- package/dist/preset.mjs +3 -3
- package/package.json +1 -1
package/dist/preset.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).filter(
|
|
3
|
-
`)}var st,Ce=De(()=>{"use strict";st=50});var Ot={};oe(Ot,{experimental_serverChannel:()=>$e,managerEntries:()=>_t,previewAnnotations:()=>$t,viteFinal:()=>Oe});module.exports=Be(Ot);var O=require("path"),ne=require("url");var _e=se(require("fs/promises")),U=se(require("path")),ee=require("glob");var pe=require("fs"),fe=require("module");var K={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Ve(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var B=`[${K.NAME}]`,p={debug:(...e)=>{Ve()&&console.log(B,...e)},info:(...e)=>{console.log(B,...e)},warn:(...e)=>{console.warn(B,...e)},error:(...e)=>{console.error(B,...e)}};var tt=["flex","inline-flex"],nt=["grid","inline-grid"],on=[...tt,...nt];function V(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let i=e.getBoundingClientRect(),a=d=>{let c=r.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let s=d.getBoundingClientRect();return s.width===0||s.height===0||d.children.length===0&&!(d.textContent??"").trim()},o=d=>{if(i.width===0||i.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=i.width*.9&&c.height>=i.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(s=>!a(s));if(c.length!==1||u!==e&&!o(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var me=V.toString(),H=null,$=null,de=!1;async function Y(){if(de)return!!H;if(de=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,fe.createRequire)(process.cwd()+"/");try{return H=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return H=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function it(){let e=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium"];for(let n of e)if((0,pe.existsSync)(n))return n}async function ge(){return J()}async function J(){if($&&$.connected)return $;let e=it(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await H.launch(n),p.debug("Headless Chrome launched for screenshots"),$}async function Z(e,n){if(!await Y())return null;let i=await(await J()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await i.goto(e,{waitUntil:"load",timeout:15e3}),await i.evaluate(()=>document.fonts.ready),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.waitForFunction(()=>new Promise(c=>{let s=document.querySelectorAll("style").length,y=0,f=()=>{let m=document.querySelectorAll("style").length;if(m===s){if(y++,y>=3){c(!0);return}}else y=0,s=m;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await i.evaluate(c=>{let s=document.querySelector("#storybook-root");if(!s)return null;let y=window.innerHeight,f=window.innerWidth,m=C=>C.setAttribute("data-uic-drilled",""),I=()=>{let C=document.createElement("style");C.id="uic-drilled-bg-reset",C.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(C),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(s),b=E?.getBoundingClientRect(),x=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==s&&b&&b.width>0&&b.height>0&&!x){for(let T=E.parentElement;T&&T!==s;T=T.parentElement)m(T);return I(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,g=0,w=1/0,v=0,h=!1;function S(C){for(let E of Array.from(C.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let x=E.getBoundingClientRect();if(x.height<=0||x.width<=0)continue;if((x.width>=f*.9||x.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),S(E);continue}if(E.children.length===1){let L=b.backgroundColor,M=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",F=b.borderStyle!=="none"&&b.borderWidth!=="0px",k=b.boxShadow!=="none",W=!M||F||k,N=E.children[0].getBoundingClientRect(),X=N.width>=x.width*.95&&N.height>=x.height*.95;if(!W||X){E.setAttribute("data-uic-drilled",""),S(E);continue}}l=Math.min(l,x.top),g=Math.max(g,x.bottom),w=Math.min(w,x.left),v=Math.max(v,x.right),h=!0}}return S(s),h?(I(),{top:l,bottom:g,left:w,right:v}):null},me);await i.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let o=4,u=a?{x:Math.max(0,a.left-o),y:Math.max(0,a.top-o),width:Math.min(a.right-a.left+o*2,800),height:Math.min(a.bottom-a.top+o*2,600)}:void 0,d=await i.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await i.close()}}async function he(e,n,t,r){if(!await Y())return null;let o=await(await J()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(d,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await o.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let m=window.innerWidth,I=window.innerHeight,l=8;try{let S=new Function("return ("+y+")")()(f),C=S?.getBoundingClientRect(),E=!!C&&C.width>=m*.9&&C.height>=I*.9;if(S&&S!==f&&C&&C.width>0&&C.height>0&&!E)return{x:Math.max(0,C.x-l),y:Math.max(0,C.y-l),width:C.width+l*2,height:C.height+l*2}}catch{}function g(h){let S=h.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<m*.8&&S.height>0)return S;for(let C of Array.from(h.children)){let E=window.getComputedStyle(C);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=g(C);if(b)return b}return null}let w=g(f);if(w)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2};let v=f.firstElementChild;if(v){let h=v.getBoundingClientRect();return{x:h.x,y:h.y,width:h.width,height:h.height}}return null},me);if(!c)throw new Error("Could not determine component bounds from snapshot");let s=await o.screenshot({type:"png",clip:c});return Buffer.from(s)}finally{await o.close()}}async function j(){return Y()}async function Q(){$&&(await $.close(),$=null)}var gt=V.toString(),te=null,z=null,Ee=!1;async function ht(){if(!Ee){Ee=!0;try{let e=await Promise.resolve().then(()=>(Ce(),be));te=e.validateCodeForFile,z=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var yt="UICOPILOT/APPLY_FIXES",St="UICOPILOT/FIX_STARTED",wt="UICOPILOT/FIX_COMPLETED",xt="UICOPILOT/FIX_FAILED",ve="UICOPILOT/ALL_FIXES_APPLIED",bt="UICOPILOT/RELOAD_REQUIRED",Ie="UICOPILOT/WORKSPACE_PATH",Ct="UICOPILOT/REQUEST_WORKSPACE_PATH",Et="UICOPILOT/DISCOVER_COMPONENT_FILES",Te="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Pe(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),i=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],o=[],u=[];for(let l of i)try{let g=await(0,ee.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});g.length>0&&o.push(...g)}catch{}for(let l of a)try{let g=await(0,ee.glob)(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});g.length>0&&u.push(...g)}catch{}let d=[...new Set(o)],c=[...new Set(u)],s=l=>{if(l.length===0)return;let g=l.find(h=>h.includes(`/fui-${t}/`)&&h.endsWith(".css"));if(g)return g;let w=l.find(h=>h.toLowerCase().includes(`/${t}/${t}.css`)||h.includes(`/${r}/${r}.css`));if(w)return w;let v=l.find(h=>h.toLowerCase().endsWith(`/${t}.css`)||h.endsWith(`/${r}.css`));return v||l[0]},y=l=>{if(l.length===0)return;let g=l.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(g.length===0)return l[0];let w=g.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let v=g.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(v)return v;let h=g.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return h||g[0]},f=s(d),m=y(c),I=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:m,totalMatches:I.length}),{cssFile:f,componentFile:m,allMatches:[...new Set(I)]}}var vt=100;function It(e){return new Promise(n=>setTimeout(n,e))}async function Tt(e,n){if(await ht(),!te||!z)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=te(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(z(t)),{valid:!1,error:r}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(z(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var Le=!1;function $e(e){if(Le)return e;Le=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(Ie,{path:n}),e.on(Ct,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(Ie,{path:n})}),e.on(Et,async t=>{let{componentName:r,storyId:i}=t;p.debug(`Discovering files for component: ${r}`);try{let a=await Pe(r,n);e.emit(Te,{componentName:r,storyId:i,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(Te,{componentName:r,storyId:i,error:a.message,allMatches:[]})}}),e.on(yt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,a=i||n;i?p.debug(`Using storybookRoot from API: ${i}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(s){let y=s.targetFileType||"css",f=s.targetFilePath||s.generatedFix?.filePath,m="",I=s.title?.match(/^(\w+)\s/);if(I&&(m=I[1]),!m&&f){let w=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(m=w[1])}if(!m)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!o.has(m)){let w=await Pe(m,a);o.set(m,w)}let l=o.get(m),g=y==="css"?l.cssFile:l.componentFile;return g?(p.debug(`Discovered ${y} path: ${g} (was: ${f})`),g):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let s of r){let{generatedFix:y}=s,f=s.targetFilePath||y?.filePath,m=await u(s)||f;p.debug("Processing issue:",{id:s.id,type:s.type,targetFileType:s.targetFileType||"css",targetPath:m,providedPath:f!==m?f:"(same)",codeLength:y?.code?.length||0}),e.emit(St,{issueId:s.id});try{if(!y||!y.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let I=await Tt(y.code,m);if(!I.valid)throw new Error(`Code validation failed: ${I.error}. Fix was not applied to prevent breaking the file.`);let l=U.isAbsolute(m)?m:U.join(a,m);p.debug(`Writing to absolute path: ${l}`),await _e.writeFile(l,y.code,"utf-8"),await It(vt);let g={success:!0,issueId:s.id,filePath:m,timestamp:new Date};e.emit(wt,{issueId:s.id,result:g}),p.debug(`\u2713 Applied ${s.targetFileType||"css"} fix to: ${m}`),d.push(g)}catch(I){let l=I.message||"Unknown error";e.emit(xt,{issueId:s.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:s.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(s=>s.success).length,failed:d.filter(s=>!s.success).length};e.emit(ve,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(bt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(s=>s.success).map(s=>s.filePath)})}catch(r){p.error("Fatal error during fix application:",r),e.emit(ve,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Oe(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await Z(y,{selector:"#storybook-root > *"});if(!f){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=f.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(u){p.error("Screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=new URL(a.url||"",`http://${a.headers.host}`),c=d.searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let s=d.searchParams.get("domOnly")==="1",f=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture${s?" (domOnly)":""}: ${c}`);let m=null;if(!s&&(m=await Z(f,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let l=await(await ge()).newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(f,{waitUntil:"load",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(w=>{let v=setTimeout(w,5e3);try{let h=window.__STORYBOOK_ADDONS_CHANNEL__;if(h){let S=()=>{clearTimeout(v),h.off("storyRendered",S),setTimeout(w,100)};h.on("storyRendered",S)}else clearTimeout(v),setTimeout(w,300)}catch{clearTimeout(v),w()}}));let g=await l.evaluate(w=>{let v=document.getElementById("storybook-root")||document.getElementById("root"),h=null;if(v)try{h=new Function("return ("+w+")")()(v)}catch{h=v.firstElementChild}let S={};if(h){let x=window.getComputedStyle(h);for(let T=0;T<x.length;T++)S[x[T]]=x.getPropertyValue(x[T])}let C={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function E(x){return x.replace(/-([a-z])/g,(T,L)=>L.toUpperCase())}function b(x,T){if(T>4)return null;let L=x.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let M=x.className,F=typeof M=="string"?M:M?.baseVal||"",k=x.id||void 0,W=x.getAttribute("role")||void 0,G;for(let _ of Array.from(x.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){G=P.length>50?P.substring(0,50)+"...":P;break}}let N=L;k?N=`${L}#${k}`:F&&(N=`${L}.${F.split(" ").filter(Boolean).join(".")}`);let X=window.getComputedStyle(x),Ne=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],q={};for(let _ of Ne){let P=X.getPropertyValue(_),A=E(_);P&&!C[A]?.includes(P)&&(q[A]=P)}if(L==="svg"||x.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=x.getAttribute(_);P&&(q[E(_)]=P)}let re=[];for(let _ of Array.from(x.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let A=b(_,T+1);A&&re.push(A)}return{selector:N,tagName:L,className:F,id:k,role:W,textContent:G,styles:q,children:re}}return{computedStyles:S,domTree:h?b(h,0):null}},gt);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:g.computedStyles,domTree:g.domTree}))}finally{await l.close()}}catch(u){p.error("Capture error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,o)=>{if(a.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let w of a)d.push(typeof w=="string"?Buffer.from(w):w);let c=JSON.parse(Buffer.concat(d).toString()),{html:s,stylesheetUrls:y,storyId:f}=c;if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let I=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await he(s,y||[],I,{storyId:f});if(!l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let g=l.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{Q().catch(()=>{})});let r=a=>{Q().catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var R={},Pt=()=>{if(typeof R<"u"&&R.url){let e=(0,ne.fileURLToPath)(R.url),n=(0,O.dirname)(e);return(0,O.join)(n,"manager.mjs")}return(0,O.join)(__dirname,"manager.mjs")},Lt=()=>{if(typeof R<"u"&&R.url){let e=(0,ne.fileURLToPath)(R.url),n=(0,O.dirname)(e);return(0,O.join)(n,"preview.mjs")}return(0,O.join)(__dirname,"preview.mjs")};function _t(e=[]){return[...e,Pt()]}function $t(e=[]){return[...e,Lt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
|
|
1
|
+
"use strict";var Ue=Object.create;var N=Object.defineProperty;var ze=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Ge=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var Ke=(e,n)=>()=>(e&&(n=e(e=0)),n);var ae=(e,n)=>{for(var t in n)N(e,t,{get:n[t],enumerable:!0})},ce=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of We(n))!Xe.call(e,o)&&o!==t&&N(e,o,{get:()=>n[o],enumerable:!(r=ze(n,o))||r.enumerable});return e};var le=(e,n,t)=>(t=e!=null?Ue(Ge(e)):{},ce(n||!e||!e.__esModule?N(t,"default",{value:e,enumerable:!0}):t,e)),qe=e=>ce(N({},"__esModule",{value:!0}),e);var Ie={};ae(Ie,{detectFileType:()=>Ee,formatValidationResult:()=>kt,isValidCode:()=>Ft,validateCode:()=>ve,validateCodeForFile:()=>Te});function Ot(e,n={}){let t=n.minLength??_t;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function Rt(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function Lt(e){let n=e.split(`
|
|
2
|
+
`).filter(o=>o.trim()),t=n.filter(o=>o.trim().startsWith("//")||o.trim().startsWith("/*")||o.trim().startsWith("*")||o.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let o of r)if(o.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function $t(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,o="",a=!1;for(let i=0;i<e.length;i++){let c=e[i],f=e[i-1];if((c==='"'||c==="'"||c==="`")&&f!=="\\"){r?c===o&&(r=!1,a=!1):(r=!0,o=c,c==="`"&&(a=!0));continue}if(!r){if(n[c])t.push(n[c]);else if(Object.values(n).includes(c)&&t.pop()!==c)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${c}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function Ce(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let o=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!o&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let c=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:f,message:l}of c)f.test(e)&&t.push({code:"TSX_INCOMPLETE",message:l,severity:"error"});return{errors:t,warnings:r}}function Mt(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let a=(e.match(/\{[^}]+\}/g)||[]).length;return a===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),a>0&&a<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${a} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Nt(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function Ee(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function ve(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},o=Ot(e,t);o&&r.errors.push(o);let a=Rt(e);a&&r.errors.push(a);let i=Lt(e);i&&r.errors.push(i);let c=$t(e);switch(c&&(t.strict?r.errors.push({...c,severity:"error"}):r.warnings.push(c)),n){case"stories":{let{errors:f,warnings:l}=Nt(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"tsx":case"jsx":{let{errors:f,warnings:l}=Ce(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"css":case"scss":case"less":{let{errors:f,warnings:l}=Mt(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"ts":case"js":{let{errors:f,warnings:l}=Ce(e,t);r.errors.push(...f),r.warnings.push(...l.filter(s=>!s.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Te(e,n,t={}){let r=Ee(n);return ve(e,r,t)}function Ft(e,n,t={}){return Te(e,n,t).valid}function kt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
|
|
3
|
+
`)}var _t,Pe=Ke(()=>{"use strict";_t=50});var Zt={};ae(Zt,{experimental_serverChannel:()=>ke,managerEntries:()=>Yt,previewAnnotations:()=>Jt,viteFinal:()=>Ae});module.exports=qe(Zt);var O=require("path"),ie=require("url");var Fe=le(require("fs/promises")),V=le(require("path")),re=require("glob");var z=require("fs"),W=require("module");var U={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Ye(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var F=`[${U.NAME}]`,g={debug:(...e)=>{Ye()&&console.log(F,...e)},info:(...e)=>{console.log(F,...e)},warn:(...e)=>{console.warn(F,...e)},error:(...e)=>{console.error(F,...e)}};var dt=["flex","inline-flex"],pt=["grid","inline-grid"],Pn=[...dt,...pt];function k(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let o=e.getBoundingClientRect(),a=l=>{let s=r.getComputedStyle(l);if(s.position==="fixed"||s.display==="none"||s.visibility==="hidden")return!0;let d=l.getBoundingClientRect();return d.width===0||d.height===0||l.children.length===0&&!(l.textContent??"").trim()},i=l=>{if(o.width===0||o.height===0)return!1;let s=l.getBoundingClientRect();return s.width>=o.width*.9&&s.height>=o.height*.9},c=e;for(let l=0;l<6;l+=1){let s=Array.from(c.children).filter(d=>!a(d));if(s.length!==1||c!==e&&!i(c))break;c=s[0]}if(c!==e&&i(c)){let l=Array.from(c.children).filter(s=>!a(s));if(l.length>1&&f(l))return l[0].setAttribute("data-uicopilot-instances",String(l.length)),l[0]}if(c===e)return e.firstElementChild??e;return c;function f(l){let s=u=>{let m=u.className,w=typeof m=="string"?m:"";return`${u.tagName}.${w.split(" ")[0]??""}`},d=s(l[0]);return l.every(u=>s(u)===d)}}var yt={},ge=k.toString(),L=null,_=null,me=!1;async function X(){if(me)return!!L;if(me=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return g.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,W.createRequire)(process.cwd()+"/");try{return L=e("puppeteer"),g.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return L=e("puppeteer-core"),g.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return L=(0,W.createRequire)(yt.url)("puppeteer-core"),g.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return g.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function gt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if((0,z.existsSync)(e))return e;g.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(o=>!o.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let o of r)if((0,z.existsSync)(o))return o}async function he(){return K()}var A=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},G=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function K(){if(_&&_.connected)return _;let e=gt();if(!e&&!ht())throw new A;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{_=await L.launch(n)}catch(t){throw e?new G(e,t):new A}return g.debug("Headless Chrome launched for screenshots"),_}function ht(){try{return typeof L?.executablePath=="function"}catch{return!1}}async function q(e,n){if(!await X())return null;let o=await(await K()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await o.goto(e,{waitUntil:"load",timeout:15e3}),await o.evaluate(()=>document.fonts.ready),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.waitForFunction(()=>new Promise(l=>{let s=document.querySelectorAll("style").length,d=0,u=()=>{let m=document.querySelectorAll("style").length;if(m===s){if(d++,d>=3){l(!0);return}}else d=0,s=m;setTimeout(u,100)};setTimeout(u,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(l=>setTimeout(l,500));let a=await o.evaluate(l=>{let s=document.querySelector("#storybook-root");if(!s)return null;let d=window.innerHeight,u=window.innerWidth,m=v=>v.setAttribute("data-uic-drilled",""),w=()=>{let v=document.createElement("style");v.id="uic-drilled-bg-reset",v.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(v),document.body.offsetHeight};try{let T=new Function("return ("+l+")")()(s),y=T?.getBoundingClientRect(),E=!!y&&y.width>=u*.9&&y.height>=d*.9;if(T&&T!==s&&y&&y.width>0&&y.height>0&&!E){for(let P=T.parentElement;P&&P!==s;P=P.parentElement)m(P);return w(),{top:y.top,bottom:y.bottom,left:y.left,right:y.right}}}catch{}let p=1/0,h=0,S=1/0,C=0,b=!1;function x(v){for(let T of Array.from(v.children)){let y=window.getComputedStyle(T);if(y.display==="none"||y.visibility==="hidden"||y.position==="fixed"||y.position==="absolute")continue;let E=T.getBoundingClientRect();if(E.height<=0||E.width<=0)continue;if((E.width>=u*.9||E.height>=d*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),x(T);continue}if(T.children.length===1){let j=y.backgroundColor,De=j==="rgba(0, 0, 0, 0)"||j==="transparent"||j==="",Be=y.borderStyle!=="none"&&y.borderWidth!=="0px",He=y.boxShadow!=="none",Ve=!De||Be||He,se=T.children[0].getBoundingClientRect(),je=se.width>=E.width*.95&&se.height>=E.height*.95;if(!Ve||je){T.setAttribute("data-uic-drilled",""),x(T);continue}}p=Math.min(p,E.top),h=Math.max(h,E.bottom),S=Math.min(S,E.left),C=Math.max(C,E.right),b=!0}}return x(s),b?(w(),{top:p,bottom:h,left:S,right:C}):null},ge);await o.evaluate(()=>new Promise(l=>requestAnimationFrame(()=>l())));let i=4,c=a?{x:Math.max(0,a.left-i),y:Math.max(0,a.top-i),width:Math.min(a.right-a.left+i*2,800),height:Math.min(a.bottom-a.top+i*2,600)}:void 0,f=await o.screenshot({type:"png",omitBackground:!0,...c?{clip:c}:{fullPage:!1}});return Buffer.from(f)}finally{await o.close()}}async function ye(e,n,t,r){if(!await X())return null;let i=await(await K()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let c=r?.storyId||"",f=`${t}/iframe.html?viewMode=story&id=${c}&globals=`;await i.goto(f,{waitUntil:"load",timeout:15e3}),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.evaluate(d=>{let u=document.getElementById("storybook-root");u&&(u.innerHTML=d)},e),await i.evaluate(()=>document.fonts.ready),await new Promise(d=>setTimeout(d,500));let l=await i.evaluate(d=>{let u=document.querySelector("#storybook-root");if(!u)return null;let m=window.innerWidth,w=window.innerHeight,p=8;try{let x=new Function("return ("+d+")")()(u),v=x?.getBoundingClientRect(),T=!!v&&v.width>=m*.9&&v.height>=w*.9;if(x&&x!==u&&v&&v.width>0&&v.height>0&&!T)return{x:Math.max(0,v.x-p),y:Math.max(0,v.y-p),width:v.width+p*2,height:v.height+p*2}}catch{}function h(b){let x=b.getBoundingClientRect();if(x.width===0||x.height===0)return null;if(x.width<m*.8&&x.height>0)return x;for(let v of Array.from(b.children)){let T=window.getComputedStyle(v);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let y=h(v);if(y)return y}return null}let S=h(u);if(S)return{x:Math.max(0,S.x-p),y:Math.max(0,S.y-p),width:S.width+p*2,height:S.height+p*2};let C=u.firstElementChild;if(C){let b=C.getBoundingClientRect();return{x:b.x,y:b.y,width:b.width,height:b.height}}return null},ge);if(!l)throw new Error("Could not determine component bounds from snapshot");let s=await i.screenshot({type:"png",clip:l});return Buffer.from(s)}finally{await i.close()}}async function D(){return X()}async function Y(){_&&(await _.close(),_=null)}async function J(e,n){return await e.evaluate(r=>{let o=document.getElementById("storybook-root")||document.getElementById("root"),a=null;if(o)try{a=new Function("return ("+r+")")()(o)}catch{a=o.firstElementChild}let i={};if(a){let s=window.getComputedStyle(a);for(let d=0;d<s.length;d++)i[s[d]]=s.getPropertyValue(s[d])}let c={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function f(s){return s.replace(/-([a-z])/g,(d,u)=>u.toUpperCase())}function l(s,d){if(d>4)return null;let u=s.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(u))return null;let m=s.className,w=typeof m=="string"?m:m?.baseVal||"",p=s.id||void 0,h=s.getAttribute("role")||void 0,S;for(let y of Array.from(s.childNodes))if(y.nodeType===3){let E=y.textContent?.trim();if(E){S=E.length>50?E.substring(0,50)+"...":E;break}}let C=u;p?C=`${u}#${p}`:w&&(C=`${u}.${w.split(" ").filter(Boolean).join(".")}`);let b=window.getComputedStyle(s),x=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],v={};for(let y of x){let E=b.getPropertyValue(y),P=f(y);E&&!c[P]?.includes(E)&&(v[P]=E)}if(u==="svg"||s.closest("svg"))for(let y of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=s.getAttribute(y);E&&(v[f(y)]=E)}let T=[];for(let y of Array.from(s.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden")continue;let P=l(y,d+1);P&&T.push(P)}return{selector:C,tagName:u,className:w,id:p,role:h,textContent:S,styles:v,children:T}}return{computedStyles:i,domTree:a?l(a,0):null}},n)}async function B(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let o=setTimeout(r,t);try{let a=window.__STORYBOOK_ADDONS_CHANNEL__;if(a){let i=()=>{clearTimeout(o),a.off("storyRendered",i),setTimeout(r,100)};a.on("storyRendered",i)}else clearTimeout(o),setTimeout(r,300)}catch{clearTimeout(o),r()}}),n)}async function we(e,n,t=15e3){return await e.evaluate((r,o)=>{let a=window,i=a.__STORYBOOK_PREVIEW__,c=a.__STORYBOOK_ADDONS_CHANNEL__;return!i||!c||typeof i.renderSelection!="function"||typeof i.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(f=>{let l=!1,s=w=>{if(!l){l=!0,clearTimeout(m);try{c.off("storyRendered",d),c.off("storyErrored",u),c.off("storyMissing",u)}catch{}f(w)}},d=w=>{let p=typeof w=="string"?w:w?.storyId||w?.id;(!p||p===r)&&setTimeout(()=>s("ok"),100)},u=()=>s("errored"),m=setTimeout(()=>s("timeout"),o);c.on("storyRendered",d),c.on("storyErrored",u),c.on("storyMissing",u);try{i.selectionStore.setSelection({storyId:r,viewMode:"story"}),i.renderSelection()}catch{s("nav-failed")}})},n,t)}async function Se(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function Z(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(o=>{let a=r.getAttribute(o)??"";return o!=="class"?`${o}=${a}`:`class=${a.split(/\s+/).filter(c=>c&&!c.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var wt=6,St=15,bt=9e4,xt=2e4;function Ct(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:St}function Et(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var I=[],ee=[];function vt(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function te(){let e=ee.shift();e&&e()}function be(){let e=Date.now(),n=I.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>bt);if(n.length===0){I.length===0&&Q();return}I=I.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});I.length===0&&Q()}var $=null;function Tt(){$||($=setInterval(be,3e4),$.unref?.())}function Q(){$&&(clearInterval($),$=null)}async function It(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(vt(n,t),{waitUntil:"load",timeout:xt}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await B(r),r}catch(o){throw await r.close().catch(()=>{}),o}}async function Pt(e,n,t){for(;;){be();let r=I.find(o=>o.baseUrl===n&&!o.busy&&o.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(I.length<wt){let o={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};I.push(o),Tt();try{return o.page=await It(e,n,t),o.baseline=await Z(o.page),{entry:o,fresh:!0}}catch{return I=I.filter(a=>a!==o),te(),null}}await new Promise(o=>ee.push(o))}}function R(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Ct())&&(I=I.filter(t=>t!==e),e.page?.close().catch(()=>{})),te()}async function xe(e,n,t,r){if(!Et())return{ok:!1,reason:"disabled"};let o=await Pt(e,n,t);if(!o)return{ok:!1,reason:"boot-failed"};let{entry:a,fresh:i}=o,c=a.page;try{if(!i){let l=await we(c,t);if(l!=="ok")return R(a,!0),{ok:!1,reason:`switch-${l}`};let s=await Se(c);if(s&&s!==t)return R(a,!0),{ok:!1,reason:"selection-mismatch"};if(a.baseline===null)return R(a,!0),{ok:!1,reason:"baseline-unavailable"};let d=await Z(c);if(d===null)return R(a,!0),{ok:!1,reason:"document-unreadable"};if(d!==a.baseline)return R(a,!0),{ok:!1,reason:"document-drift"};await c.evaluate(()=>document.fonts.ready)}let f=await r(c);return R(a,!1),{ok:!0,value:f,booted:i}}catch(f){return R(a,!0),{ok:!1,reason:`error:${f.message}`}}}async function ne(){Q();let e=I;for(I=[];ee.length;)te();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var _e=k.toString(),oe=null,H=null,Oe=!1;async function At(){if(!Oe){Oe=!0;try{let e=await Promise.resolve().then(()=>(Pe(),Ie));oe=e.validateCodeForFile,H=e.formatValidationResult,g.debug("Code validator loaded - fix validation enabled")}catch{g.debug("Code validator not available - skipping fix validation")}}}var Dt="UICOPILOT/APPLY_FIXES",Bt="UICOPILOT/FIX_STARTED",Ht="UICOPILOT/FIX_COMPLETED",Vt="UICOPILOT/FIX_FAILED",Re="UICOPILOT/ALL_FIXES_APPLIED",jt="UICOPILOT/RELOAD_REQUIRED",Le="UICOPILOT/WORKSPACE_PATH",Ut="UICOPILOT/REQUEST_WORKSPACE_PATH",zt="UICOPILOT/DISCOVER_COMPONENT_FILES",$e="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Me(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),o=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],i=[],c=[];for(let p of o)try{let h=await(0,re.glob)(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&i.push(...h)}catch{}for(let p of a)try{let h=await(0,re.glob)(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&c.push(...h)}catch{}let f=[...new Set(i)],l=[...new Set(c)],s=p=>{if(p.length===0)return;let h=p.find(b=>b.includes(`/fui-${t}/`)&&b.endsWith(".css"));if(h)return h;let S=p.find(b=>b.toLowerCase().includes(`/${t}/${t}.css`)||b.includes(`/${r}/${r}.css`));if(S)return S;let C=p.find(b=>b.toLowerCase().endsWith(`/${t}.css`)||b.endsWith(`/${r}.css`));return C||p[0]},d=p=>{if(p.length===0)return;let h=p.filter(x=>!x.includes(".stories.")&&!x.includes(".test."));if(h.length===0)return p[0];let S=h.find(x=>x.includes(`/fui-${t}/`)&&(x.endsWith(".tsx")||x.endsWith(".jsx")));if(S)return S;let C=h.find(x=>x.toLowerCase().includes(`/${t}/${t}.tsx`)||x.includes(`/${r}/${r}.tsx`));if(C)return C;let b=h.find(x=>x.toLowerCase().endsWith(`/${t}.tsx`)||x.endsWith(`/${r}.tsx`));return b||h[0]},u=s(f),m=d(l),w=[...f,...l];return g.debug(`Discovered files for "${e}":`,{cssFile:u,componentFile:m,totalMatches:w.length}),{cssFile:u,componentFile:m,allMatches:[...new Set(w)]}}var Wt=100;function Gt(e){return new Promise(n=>setTimeout(n,e))}async function Xt(e,n){if(await At(),!oe||!H)return g.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=oe(e,n);if(!t.valid){let r=t.errors.map(o=>o.message).join("; ");return g.warn(`Code validation failed for ${n}:`),console.warn(H(t)),{valid:!1,error:r}}return t.warnings.length>0&&(g.warn(`Code validation warnings for ${n}:`),console.warn(H(t))),g.debug(`Validation passed for ${n}`),{valid:!0}}var Ne=!1;function ke(e){if(Ne)return e;Ne=!0;let n=process.cwd();return g.debug("Apply fixes initialized"),g.debug("Workspace:",n),e.emit(Le,{path:n}),e.on(Ut,()=>{g.debug("Workspace path requested by browser"),g.debug("Emitting workspace path response:",n),e.emit(Le,{path:n})}),e.on(zt,async t=>{let{componentName:r,storyId:o}=t;g.debug(`Discovering files for component: ${r}`);try{let a=await Me(r,n);e.emit($e,{componentName:r,storyId:o,...a,workspacePath:n})}catch(a){g.error("File discovery error:",a),e.emit($e,{componentName:r,storyId:o,error:a.message,allMatches:[]})}}),e.on(Dt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:o}=t,a=o||n;o?g.debug(`Using storybookRoot from API: ${o}`):g.debug(`Using process.cwd(): ${n}`),g.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let i=new Map;async function c(s){let d=s.targetFileType||"css",u=s.targetFilePath||s.generatedFix?.filePath,m="",w=s.title?.match(/^(\w+)\s/);if(w&&(m=w[1]),!m&&u){let S=u.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(m=S[1])}if(!m)return g.debug(`Could not extract component name, using provided path: ${u}`),u||null;if(!i.has(m)){let S=await Me(m,a);i.set(m,S)}let p=i.get(m),h=d==="css"?p.cssFile:p.componentFile;return h?(g.debug(`Discovered ${d} path: ${h} (was: ${u})`),h):(g.debug(`No ${d} file discovered, using provided: ${u}`),u||null)}let f=[];for(let s of r){let{generatedFix:d}=s,u=s.targetFilePath||d?.filePath,m=await c(s)||u;g.debug("Processing issue:",{id:s.id,type:s.type,targetFileType:s.targetFileType||"css",targetPath:m,providedPath:u!==m?u:"(same)",codeLength:d?.code?.length||0}),e.emit(Bt,{issueId:s.id});try{if(!d||!d.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");g.debug("Code to write (first 200 chars):",d.code.substring(0,200)),g.debug(`Code length: ${d.code.length} chars`);let w=await Xt(d.code,m);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let p=V.isAbsolute(m)?m:V.join(a,m);g.debug(`Writing to absolute path: ${p}`),await Fe.writeFile(p,d.code,"utf-8"),await Gt(Wt);let h={success:!0,issueId:s.id,filePath:m,timestamp:new Date};e.emit(Ht,{issueId:s.id,result:h}),g.debug(`\u2713 Applied ${s.targetFileType||"css"} fix to: ${m}`),f.push(h)}catch(w){let p=w.message||"Unknown error";e.emit(Vt,{issueId:s.id,error:p}),g.error(`\u2717 Error: ${p}`),f.push({success:!1,issueId:s.id,error:p,timestamp:new Date})}}let l={total:f.length,succeeded:f.filter(s=>s.success).length,failed:f.filter(s=>!s.success).length};e.emit(Re,{results:f,summary:l}),g.debug(`Completed: ${l.succeeded}/${l.total} fixes applied`),l.succeeded>0&&e.emit(jt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:f.filter(s=>s.success).map(s=>s.filePath)})}catch(r){g.error("Fatal error during fix application:",r),e.emit(Re,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Ae(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,i)=>{i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,i)=>{try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let l=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!l){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let d=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Taking screenshot: ${l}`);let u=await q(d,{selector:"#storybook-root > *"});if(!u){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=u.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(c){g.error("Screenshot error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,i)=>{try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=new URL(a.url||"",`http://${a.headers.host}`),l=f.searchParams.get("storyId");if(!l){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let s=f.searchParams.get("domOnly")==="1",d=a.headers.host||"localhost:6006",u=`http://${d}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Full capture${s?" (domOnly)":""}: ${l}`);let m=null;if(!s&&(m=await q(u,{selector:"#storybook-root > *"}),!m)){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let w=await he(),p=f.searchParams.get("warm")==="0",h=null,S="cold";if(!p){let C=`http://${d}`,b=await xe(w,C,l,x=>J(x,_e));b.ok?(h=b.value,S=b.booted?"warm-boot":"warm"):g.debug(`Warm capture unavailable (${b.reason}): ${l}`)}if(!h){let C=await w.newPage();try{await C.setCacheEnabled(!1),await C.setViewport({width:800,height:600}),await C.goto(u,{waitUntil:"load",timeout:15e3}),await C.evaluate(()=>document.fonts.ready),await C.waitForSelector("#storybook-root > *",{timeout:1e4}),await B(C),h=await J(C,_e)}finally{await C.close()}}g.debug(`Capture path for ${l}: ${S}`),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:h.computedStyles,domTree:h.domTree}))}catch(c){g.error("Capture error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,i)=>{if(a.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=[];for await(let S of a)f.push(typeof S=="string"?Buffer.from(S):S);let l=JSON.parse(Buffer.concat(f).toString()),{html:s,stylesheetUrls:d,storyId:u}=l;if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${a.headers.host||"localhost:6006"}`;g.debug(`Taking snapshot screenshot for ${u||"unknown"}`);let p=await ye(s,d||[],w,{storyId:u});if(!p){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=p.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(c){g.error("Snapshot screenshot error:",c.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:c.message}))}}),t.httpServer?.on("close",()=>{ne().catch(()=>{}).finally(()=>Y().catch(()=>{}))});let r=a=>{ne().catch(()=>{}).then(()=>Y()).catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var M={},Kt=()=>{if(typeof M<"u"&&M.url){let e=(0,ie.fileURLToPath)(M.url),n=(0,O.dirname)(e);return(0,O.join)(n,"manager.mjs")}return(0,O.join)(__dirname,"manager.mjs")},qt=()=>{if(typeof M<"u"&&M.url){let e=(0,ie.fileURLToPath)(M.url),n=(0,O.dirname)(e);return(0,O.join)(n,"preview.mjs")}return(0,O.join)(__dirname,"preview.mjs")};function Yt(e=[]){return[...e,Kt()]}function Jt(e=[]){return[...e,qt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
|
package/dist/preset.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`).filter(s=>s.trim()),t=n.filter(s=>s.trim().startsWith("//")||s.trim().startsWith("/*")||s.trim().startsWith("*")||s.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let s of r)if(s.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function
|
|
3
|
-
`)}var Ye,fe=Te(()=>{"use strict";Ye=50});import{dirname as Ce,join as j}from"path";import{fileURLToPath as Ee}from"url";import*as be from"fs/promises";import*as H from"path";import{glob as me}from"glob";import{existsSync as Xe}from"fs";import{createRequire as qe}from"module";var X={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Le(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var k=`[${X.NAME}]`,p={debug:(...e)=>{Le()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var ze=["flex","inline-flex"],Ue=["grid","inline-grid"],Xt=[...ze,...Ue];function A(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let s=e.getBoundingClientRect(),a=d=>{let c=r.getComputedStyle(d);if(c.position==="fixed"||c.display==="none"||c.visibility==="hidden")return!0;let i=d.getBoundingClientRect();return i.width===0||i.height===0||d.children.length===0&&!(d.textContent??"").trim()},o=d=>{if(s.width===0||s.height===0)return!1;let c=d.getBoundingClientRect();return c.width>=s.width*.9&&c.height>=s.height*.9},u=e;for(let d=0;d<6;d+=1){let c=Array.from(u.children).filter(i=>!a(i));if(c.length!==1||u!==e&&!o(u))break;u=c[0]}return u===e?e.firstElementChild??e:u}var ie=A.toString(),D=null,$=null,oe=!1;async function q(){if(oe)return!!D;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return p.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=qe(process.cwd()+"/");try{return D=e("puppeteer"),p.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return D=e("puppeteer-core"),p.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return p.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ke(){let e=["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium"];for(let n of e)if(Xe(n))return n}async function se(){return K()}async function K(){if($&&$.connected)return $;let e=Ke(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await D.launch(n),p.debug("Headless Chrome launched for screenshots"),$}async function Y(e,n){if(!await q())return null;let s=await(await K()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"load",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(c=>{let i=document.querySelectorAll("style").length,y=0,f=()=>{let m=document.querySelectorAll("style").length;if(m===i){if(y++,y>=3){c(!0);return}}else y=0,i=m;setTimeout(f,100)};setTimeout(f,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(c=>setTimeout(c,500));let a=await s.evaluate(c=>{let i=document.querySelector("#storybook-root");if(!i)return null;let y=window.innerHeight,f=window.innerWidth,m=C=>C.setAttribute("data-uic-drilled",""),I=()=>{let C=document.createElement("style");C.id="uic-drilled-bg-reset",C.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(C),document.body.offsetHeight};try{let E=new Function("return ("+c+")")()(i),b=E?.getBoundingClientRect(),x=!!b&&b.width>=f*.9&&b.height>=y*.9;if(E&&E!==i&&b&&b.width>0&&b.height>0&&!x){for(let T=E.parentElement;T&&T!==i;T=T.parentElement)m(T);return I(),{top:b.top,bottom:b.bottom,left:b.left,right:b.right}}}catch{}let l=1/0,g=0,w=1/0,v=0,h=!1;function S(C){for(let E of Array.from(C.children)){let b=window.getComputedStyle(E);if(b.display==="none"||b.visibility==="hidden"||b.position==="fixed"||b.position==="absolute")continue;let x=E.getBoundingClientRect();if(x.height<=0||x.width<=0)continue;if((x.width>=f*.9||x.height>=y*.9)&&E.children.length>0){E.setAttribute("data-uic-drilled",""),S(E);continue}if(E.children.length===1){let L=b.backgroundColor,N=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",R=b.borderStyle!=="none"&&b.borderWidth!=="0px",M=b.boxShadow!=="none",z=!N||R||M,O=E.children[0].getBoundingClientRect(),W=O.width>=x.width*.95&&O.height>=x.height*.95;if(!z||W){E.setAttribute("data-uic-drilled",""),S(E);continue}}l=Math.min(l,x.top),g=Math.max(g,x.bottom),w=Math.min(w,x.left),v=Math.max(v,x.right),h=!0}}return S(i),h?(I(),{top:l,bottom:g,left:w,right:v}):null},ie);await s.evaluate(()=>new Promise(c=>requestAnimationFrame(()=>c())));let o=4,u=a?{x:Math.max(0,a.left-o),y:Math.max(0,a.top-o),width:Math.min(a.right-a.left+o*2,800),height:Math.min(a.bottom-a.top+o*2,600)}:void 0,d=await s.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(d)}finally{await s.close()}}async function ae(e,n,t,r){if(!await q())return null;let o=await(await K()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",d=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(d,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(y=>{let f=document.getElementById("storybook-root");f&&(f.innerHTML=y)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(y=>setTimeout(y,500));let c=await o.evaluate(y=>{let f=document.querySelector("#storybook-root");if(!f)return null;let m=window.innerWidth,I=window.innerHeight,l=8;try{let S=new Function("return ("+y+")")()(f),C=S?.getBoundingClientRect(),E=!!C&&C.width>=m*.9&&C.height>=I*.9;if(S&&S!==f&&C&&C.width>0&&C.height>0&&!E)return{x:Math.max(0,C.x-l),y:Math.max(0,C.y-l),width:C.width+l*2,height:C.height+l*2}}catch{}function g(h){let S=h.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<m*.8&&S.height>0)return S;for(let C of Array.from(h.children)){let E=window.getComputedStyle(C);if(E.position==="fixed"||E.position==="absolute"||E.display==="none"||E.visibility==="hidden")continue;let b=g(C);if(b)return b}return null}let w=g(f);if(w)return{x:Math.max(0,w.x-l),y:Math.max(0,w.y-l),width:w.width+l*2,height:w.height+l*2};let v=f.firstElementChild;if(v){let h=v.getBoundingClientRect();return{x:h.x,y:h.y,width:h.width,height:h.height}}return null},ie);if(!c)throw new Error("Could not determine component bounds from snapshot");let i=await o.screenshot({type:"png",clip:c});return Buffer.from(i)}finally{await o.close()}}async function B(){return q()}async function J(){$&&(await $.close(),$=null)}var it=A.toString(),Z=null,V=null,ge=!1;async function st(){if(!ge){ge=!0;try{let e=await Promise.resolve().then(()=>(fe(),pe));Z=e.validateCodeForFile,V=e.formatValidationResult,p.debug("Code validator loaded - fix validation enabled")}catch{p.debug("Code validator not available - skipping fix validation")}}}var at="UICOPILOT/APPLY_FIXES",ct="UICOPILOT/FIX_STARTED",lt="UICOPILOT/FIX_COMPLETED",ut="UICOPILOT/FIX_FAILED",he="UICOPILOT/ALL_FIXES_APPLIED",dt="UICOPILOT/RELOAD_REQUIRED",ye="UICOPILOT/WORKSPACE_PATH",pt="UICOPILOT/REQUEST_WORKSPACE_PATH",ft="UICOPILOT/DISCOVER_COMPONENT_FILES",Se="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function we(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),s=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],o=[],u=[];for(let l of s)try{let g=await me(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});g.length>0&&o.push(...g)}catch{}for(let l of a)try{let g=await me(l,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});g.length>0&&u.push(...g)}catch{}let d=[...new Set(o)],c=[...new Set(u)],i=l=>{if(l.length===0)return;let g=l.find(h=>h.includes(`/fui-${t}/`)&&h.endsWith(".css"));if(g)return g;let w=l.find(h=>h.toLowerCase().includes(`/${t}/${t}.css`)||h.includes(`/${r}/${r}.css`));if(w)return w;let v=l.find(h=>h.toLowerCase().endsWith(`/${t}.css`)||h.endsWith(`/${r}.css`));return v||l[0]},y=l=>{if(l.length===0)return;let g=l.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(g.length===0)return l[0];let w=g.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let v=g.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(v)return v;let h=g.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return h||g[0]},f=i(d),m=y(c),I=[...d,...c];return p.debug(`Discovered files for "${e}":`,{cssFile:f,componentFile:m,totalMatches:I.length}),{cssFile:f,componentFile:m,allMatches:[...new Set(I)]}}var mt=100;function gt(e){return new Promise(n=>setTimeout(n,e))}async function ht(e,n){if(await st(),!Z||!V)return p.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Z(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return p.warn(`Code validation failed for ${n}:`),console.warn(V(t)),{valid:!1,error:r}}return t.warnings.length>0&&(p.warn(`Code validation warnings for ${n}:`),console.warn(V(t))),p.debug(`Validation passed for ${n}`),{valid:!0}}var xe=!1;function yt(e){if(xe)return e;xe=!0;let n=process.cwd();return p.debug("Apply fixes initialized"),p.debug("Workspace:",n),e.emit(ye,{path:n}),e.on(pt,()=>{p.debug("Workspace path requested by browser"),p.debug("Emitting workspace path response:",n),e.emit(ye,{path:n})}),e.on(ft,async t=>{let{componentName:r,storyId:s}=t;p.debug(`Discovering files for component: ${r}`);try{let a=await we(r,n);e.emit(Se,{componentName:r,storyId:s,...a,workspacePath:n})}catch(a){p.error("File discovery error:",a),e.emit(Se,{componentName:r,storyId:s,error:a.message,allMatches:[]})}}),e.on(at,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,a=s||n;s?p.debug(`Using storybookRoot from API: ${s}`):p.debug(`Using process.cwd(): ${n}`),p.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(i){let y=i.targetFileType||"css",f=i.targetFilePath||i.generatedFix?.filePath,m="",I=i.title?.match(/^(\w+)\s/);if(I&&(m=I[1]),!m&&f){let w=f.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(m=w[1])}if(!m)return p.debug(`Could not extract component name, using provided path: ${f}`),f||null;if(!o.has(m)){let w=await we(m,a);o.set(m,w)}let l=o.get(m),g=y==="css"?l.cssFile:l.componentFile;return g?(p.debug(`Discovered ${y} path: ${g} (was: ${f})`),g):(p.debug(`No ${y} file discovered, using provided: ${f}`),f||null)}let d=[];for(let i of r){let{generatedFix:y}=i,f=i.targetFilePath||y?.filePath,m=await u(i)||f;p.debug("Processing issue:",{id:i.id,type:i.type,targetFileType:i.targetFileType||"css",targetPath:m,providedPath:f!==m?f:"(same)",codeLength:y?.code?.length||0}),e.emit(ct,{issueId:i.id});try{if(!y||!y.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");p.debug("Code to write (first 200 chars):",y.code.substring(0,200)),p.debug(`Code length: ${y.code.length} chars`);let I=await ht(y.code,m);if(!I.valid)throw new Error(`Code validation failed: ${I.error}. Fix was not applied to prevent breaking the file.`);let l=H.isAbsolute(m)?m:H.join(a,m);p.debug(`Writing to absolute path: ${l}`),await be.writeFile(l,y.code,"utf-8"),await gt(mt);let g={success:!0,issueId:i.id,filePath:m,timestamp:new Date};e.emit(lt,{issueId:i.id,result:g}),p.debug(`\u2713 Applied ${i.targetFileType||"css"} fix to: ${m}`),d.push(g)}catch(I){let l=I.message||"Unknown error";e.emit(ut,{issueId:i.id,error:l}),p.error(`\u2717 Error: ${l}`),d.push({success:!1,issueId:i.id,error:l,timestamp:new Date})}}let c={total:d.length,succeeded:d.filter(i=>i.success).length,failed:d.filter(i=>!i.success).length};e.emit(he,{results:d,summary:c}),p.debug(`Completed: ${c.succeeded}/${c.total} fixes applied`),c.succeeded>0&&e.emit(dt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:d.filter(i=>i.success).map(i=>i.filePath)})}catch(r){p.error("Fatal error during fix application:",r),e.emit(he,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function St(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,o)=>{try{if(!await B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let c=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let y=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Taking screenshot: ${c}`);let f=await Y(y,{selector:"#storybook-root > *"});if(!f){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=f.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(u){p.error("Screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=new URL(a.url||"",`http://${a.headers.host}`),c=d.searchParams.get("storyId");if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let i=d.searchParams.get("domOnly")==="1",f=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${c}&globals=`;p.debug(`Full capture${i?" (domOnly)":""}: ${c}`);let m=null;if(!i&&(m=await Y(f,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let l=await(await se()).newPage();try{await l.setCacheEnabled(!1),await l.setViewport({width:800,height:600}),await l.goto(f,{waitUntil:"load",timeout:15e3}),await l.evaluate(()=>document.fonts.ready),await l.waitForSelector("#storybook-root > *",{timeout:1e4}),await l.evaluate(()=>new Promise(w=>{let v=setTimeout(w,5e3);try{let h=window.__STORYBOOK_ADDONS_CHANNEL__;if(h){let S=()=>{clearTimeout(v),h.off("storyRendered",S),setTimeout(w,100)};h.on("storyRendered",S)}else clearTimeout(v),setTimeout(w,300)}catch{clearTimeout(v),w()}}));let g=await l.evaluate(w=>{let v=document.getElementById("storybook-root")||document.getElementById("root"),h=null;if(v)try{h=new Function("return ("+w+")")()(v)}catch{h=v.firstElementChild}let S={};if(h){let x=window.getComputedStyle(h);for(let T=0;T<x.length;T++)S[x[T]]=x.getPropertyValue(x[T])}let C={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function E(x){return x.replace(/-([a-z])/g,(T,L)=>L.toUpperCase())}function b(x,T){if(T>4)return null;let L=x.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let N=x.className,R=typeof N=="string"?N:N?.baseVal||"",M=x.id||void 0,z=x.getAttribute("role")||void 0,U;for(let _ of Array.from(x.childNodes))if(_.nodeType===3){let P=_.textContent?.trim();if(P){U=P.length>50?P.substring(0,50)+"...":P;break}}let O=L;M?O=`${L}#${M}`:R&&(O=`${L}.${R.split(" ").filter(Boolean).join(".")}`);let W=window.getComputedStyle(x),ve=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],G={};for(let _ of ve){let P=W.getPropertyValue(_),F=E(_);P&&!C[F]?.includes(P)&&(G[F]=P)}if(L==="svg"||x.closest("svg"))for(let _ of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let P=x.getAttribute(_);P&&(G[E(_)]=P)}let Q=[];for(let _ of Array.from(x.children)){let P=window.getComputedStyle(_);if(P.display==="none"||P.visibility==="hidden")continue;let F=b(_,T+1);F&&Q.push(F)}return{selector:O,tagName:L,className:R,id:M,role:z,textContent:U,styles:G,children:Q}}return{computedStyles:S,domTree:h?b(h,0):null}},it);o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:g.computedStyles,domTree:g.domTree}))}finally{await l.close()}}catch(u){p.error("Capture error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,o)=>{if(a.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await B()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let d=[];for await(let w of a)d.push(typeof w=="string"?Buffer.from(w):w);let c=JSON.parse(Buffer.concat(d).toString()),{html:i,stylesheetUrls:y,storyId:f}=c;if(!i){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let I=`http://${a.headers.host||"localhost:6006"}`;p.debug(`Taking snapshot screenshot for ${f||"unknown"}`);let l=await ae(i,y||[],I,{storyId:f});if(!l){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let g=l.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${g}`}))}catch(u){p.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{J().catch(()=>{})});let r=a=>{J().catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var wt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ee(import.meta.url),n=Ce(e);return j(n,"manager.mjs")}return j(__dirname,"manager.mjs")},xt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Ee(import.meta.url),n=Ce(e);return j(n,"preview.mjs")}return j(__dirname,"preview.mjs")};function Ar(e=[]){return[...e,wt()]}function Dr(e=[]){return[...e,xt()]}export{yt as experimental_serverChannel,Ar as managerEntries,Dr as previewAnnotations,St as viteFinal};
|
|
1
|
+
var Ae=Object.defineProperty;var De=(e,n)=>()=>(e&&(n=e(e=0)),n);var Be=(e,n)=>{for(var t in n)Ae(e,t,{get:n[t],enumerable:!0})};var Se={};Be(Se,{detectFileType:()=>he,formatValidationResult:()=>Tt,isValidCode:()=>vt,validateCode:()=>ye,validateCodeForFile:()=>we});function wt(e,n={}){let t=n.minLength??yt;return e.length<t?{code:"CODE_TOO_SHORT",message:`Code is too short (${e.length} chars). Minimum: ${t}. Likely incomplete or a snippet.`,severity:"error"}:null}function St(e){let n=[/^[+-]{3}\s+[ab]\//m,/^@@\s+-\d+,\d+\s+\+\d+,\d+\s+@@/m,/^diff --git/m,/^index [a-f0-9]+\.\.[a-f0-9]+/m];for(let t of n)if(t.test(e))return{code:"CODE_IS_DIFF",message:"Code appears to be a diff/patch format, not complete file content.",severity:"error"};return null}function bt(e){let n=e.split(`
|
|
2
|
+
`).filter(s=>s.trim()),t=n.filter(s=>s.trim().startsWith("//")||s.trim().startsWith("/*")||s.trim().startsWith("*")||s.trim().startsWith("#"));if(n.length>0&&t.length/n.length>.8)return{code:"CODE_IS_INSTRUCTIONS",message:"Code appears to be mostly comments/instructions, not actual implementation.",severity:"error"};let r=[/^\/\/\s*(Change|Replace|Update|Modify|Add|Remove|Delete)\s+(from|to|this|the)/im,/^\/\/\s*To:/m,/^\/\/\s*From:/m];for(let s of r)if(s.test(e))return{code:"CODE_IS_INSTRUCTIONS",message:'Code contains instruction comments (e.g., "// Change from:" / "// To:") instead of actual code.',severity:"error"};return null}function xt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,s="",a=!1;for(let o=0;o<e.length;o++){let c=e[o],f=e[o-1];if((c==='"'||c==="'"||c==="`")&&f!=="\\"){r?c===s&&(r=!1,a=!1):(r=!0,s=c,c==="`"&&(a=!0));continue}if(!r){if(n[c])t.push(n[c]);else if(Object.values(n).includes(c)&&t.pop()!==c)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${c}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ge(e,n={}){let t=[],r=[];e.includes("import ")||t.push({code:"TSX_MISSING_IMPORTS",message:"Component file missing import statements. A complete file must have imports.",severity:"error"}),e.includes("export ")||t.push({code:"TSX_MISSING_EXPORTS",message:"Component file missing exports. A complete file must export something.",severity:"error"});let s=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!s&&r.push({code:"TSX_NO_REACT_IMPORT",message:"JSX detected but no React import. OK for React 17+ with automatic runtime.",severity:"warning"}),/export\s+(default\s+)?function\s+\w+/.test(e)||/export\s+(const|let)\s+\w+\s*[:=]/.test(e)||/export\s+default\s+\w+/.test(e)||/export\s+\{[^}]+\}/.test(e)||r.push({code:"TSX_NO_COMPONENT_DEF",message:"No clear component definition found. Expected function or const export.",severity:"warning"});let c=[{pattern:/\.\.\.\s*$/,message:'Code ends with "..." - likely truncated'},{pattern:/\/\/\s*\.\.\./m,message:'Contains "// ..." - likely incomplete'},{pattern:/{\s*\/\*\s*\.\.\.\s*\*\/\s*}/m,message:'Contains "{/* ... */}" placeholder'}];for(let{pattern:f,message:l}of c)f.test(e)&&t.push({code:"TSX_INCOMPLETE",message:l,severity:"error"});return{errors:t,warnings:r}}function Ct(e,n={}){let t=[],r=[];(e.includes("import ")||e.includes("export "))&&t.push({code:"CSS_HAS_JS_CODE",message:"CSS file contains JavaScript import/export statements. Wrong file type.",severity:"error"}),/[.#\w\[\]]+\s*\{[\s\S]*?:\s*[^;]+;?[\s\S]*?\}/.test(e)||t.push({code:"CSS_INVALID_SYNTAX",message:"No valid CSS syntax found. Expected selector { property: value; } pattern.",severity:"error"});let a=(e.match(/\{[^}]+\}/g)||[]).length;return a===0&&t.push({code:"CSS_NO_RULES",message:"No CSS rules found. File appears empty or malformed.",severity:"error"}),(e.includes("/* ... */")||e.includes("// ..."))&&t.push({code:"CSS_INCOMPLETE",message:"CSS contains placeholder comments (/* ... */) - likely incomplete.",severity:"error"}),a>0&&a<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${a} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Et(e,n={}){let t=[],r=[];return e.includes("import ")||t.push({code:"STORIES_MISSING_IMPORTS",message:"Stories file missing import statements.",severity:"error"}),/@storybook\//.test(e)||t.push({code:"STORIES_NO_STORYBOOK_IMPORT",message:"Stories file must import from @storybook/* (e.g., @storybook/react).",severity:"error"}),e.includes("Meta")||e.includes("ComponentMeta")||r.push({code:"STORIES_NO_META_TYPE",message:"Stories file should have Meta type import for type safety.",severity:"warning"}),e.includes("StoryObj")||e.includes("ComponentStory")||e.includes("Story")||r.push({code:"STORIES_NO_STORY_TYPE",message:"Stories file should have StoryObj/Story type for type safety.",severity:"warning"}),e.includes("export default")||t.push({code:"STORIES_NO_DEFAULT_EXPORT",message:"Stories file must have a default export (meta configuration).",severity:"error"}),/export\s+const\s+\w+\s*[:=]/.test(e)||t.push({code:"STORIES_NO_STORY_EXPORTS",message:"Stories file must have at least one named export (story definition).",severity:"error"}),/import\s+\{?\s*\w+\s*\}?\s+from\s+['"]\.\//.test(e)||r.push({code:"STORIES_NO_COMPONENT_IMPORT",message:"Stories file should import the component being documented.",severity:"warning"}),(e.includes("// ... other")||e.includes("/* ... */"))&&t.push({code:"STORIES_INCOMPLETE",message:"Stories file contains placeholder comments - likely incomplete.",severity:"error"}),{errors:t,warnings:r}}function he(e){let n=e.toLowerCase();if(n.includes(".stories."))return"stories";switch(n.split(".").pop()){case"tsx":return"tsx";case"jsx":return"jsx";case"ts":return"ts";case"js":return"js";case"css":return"css";case"scss":return"scss";case"less":return"less";default:return"unknown"}}function ye(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},s=wt(e,t);s&&r.errors.push(s);let a=St(e);a&&r.errors.push(a);let o=bt(e);o&&r.errors.push(o);let c=xt(e);switch(c&&(t.strict?r.errors.push({...c,severity:"error"}):r.warnings.push(c)),n){case"stories":{let{errors:f,warnings:l}=Et(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"tsx":case"jsx":{let{errors:f,warnings:l}=ge(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"css":case"scss":case"less":{let{errors:f,warnings:l}=Ct(e,t);r.errors.push(...f),r.warnings.push(...l);break}case"ts":case"js":{let{errors:f,warnings:l}=ge(e,t);r.errors.push(...f),r.warnings.push(...l.filter(i=>!i.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function we(e,n,t={}){let r=he(n);return ye(e,r,t)}function vt(e,n,t={}){return we(e,n,t).valid}function Tt(e){if(e.valid&&e.warnings.length===0)return`\u2713 Valid ${e.fileType} code`;let n=[];if(e.valid)n.push(`\u26A0 Valid ${e.fileType} code with warnings`);else{n.push(`\u2717 Invalid ${e.fileType} code`),n.push(""),n.push("Errors:");for(let t of e.errors)n.push(` - [${t.code}] ${t.message}`)}if(e.warnings.length>0){n.push(""),n.push("Warnings:");for(let t of e.warnings)n.push(` - [${t.code}] ${t.message}`)}return n.join(`
|
|
3
|
+
`)}var yt,be=De(()=>{"use strict";yt=50});import{dirname as Re,join as B}from"path";import{fileURLToPath as Le}from"url";import*as Oe from"fs/promises";import*as D from"path";import{glob as xe}from"glob";import{existsSync as ie}from"fs";import{createRequire as se}from"module";var V={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function He(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var $=`[${V.NAME}]`,g={debug:(...e)=>{He()&&console.log($,...e)},info:(...e)=>{console.log($,...e)},warn:(...e)=>{console.warn($,...e)},error:(...e)=>{console.error($,...e)}};var tt=["flex","inline-flex"],nt=["grid","inline-grid"],gn=[...tt,...nt];function M(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let s=e.getBoundingClientRect(),a=l=>{let i=r.getComputedStyle(l);if(i.position==="fixed"||i.display==="none"||i.visibility==="hidden")return!0;let d=l.getBoundingClientRect();return d.width===0||d.height===0||l.children.length===0&&!(l.textContent??"").trim()},o=l=>{if(s.width===0||s.height===0)return!1;let i=l.getBoundingClientRect();return i.width>=s.width*.9&&i.height>=s.height*.9},c=e;for(let l=0;l<6;l+=1){let i=Array.from(c.children).filter(d=>!a(d));if(i.length!==1||c!==e&&!o(c))break;c=i[0]}if(c!==e&&o(c)){let l=Array.from(c.children).filter(i=>!a(i));if(l.length>1&&f(l))return l[0].setAttribute("data-uicopilot-instances",String(l.length)),l[0]}if(c===e)return e.firstElementChild??e;return c;function f(l){let i=u=>{let m=u.className,w=typeof m=="string"?m:"";return`${u.tagName}.${w.split(" ")[0]??""}`},d=i(l[0]);return l.every(u=>i(u)===d)}}var ce=M.toString(),R=null,_=null,ae=!1;async function U(){if(ae)return!!R;if(ae=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return g.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=se(process.cwd()+"/");try{return R=e("puppeteer"),g.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return R=e("puppeteer-core"),g.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return R=se(import.meta.url)("puppeteer-core"),g.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return g.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function it(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if(ie(e))return e;g.warn(`STORYBOOK_UICOPILOT_CHROME_PATH is set to "${e}" but no file exists there \u2014 falling back to discovery`)}let n=process.platform==="win32",t=process.env,r=n?[`${t.PROGRAMFILES??"C:\\Program Files"}\\Google\\Chrome\\Application\\chrome.exe`,`${t["PROGRAMFILES(X86)"]??"C:\\Program Files (x86)"}\\Google\\Chrome\\Application\\chrome.exe`,`${t.LOCALAPPDATA??""}\\Google\\Chrome\\Application\\chrome.exe`,`${t.PROGRAMFILES??"C:\\Program Files"}\\Microsoft\\Edge\\Application\\msedge.exe`].filter(s=>!s.startsWith("\\")):["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary","/Applications/Chromium.app/Contents/MacOS/Chromium","/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/usr/bin/chromium-browser","/usr/bin/chromium","/snap/bin/chromium"];for(let s of r)if(ie(s))return s}async function le(){return z()}var N=class extends Error{constructor(){super("No Chrome or Chromium found. Install Google Chrome, or set STORYBOOK_UICOPILOT_CHROME_PATH to an executable. (Capture needs a real browser to render your stories.)"),this.name="BrowserNotFoundError"}},j=class extends Error{constructor(n,t){super(`Found a browser at "${n}" but could not drive it: ${t instanceof Error?t.message:String(t)}. This usually means the installed browser and puppeteer-core versions are incompatible.`),this.name="BrowserIncompatibleError"}};async function z(){if(_&&_.connected)return _;let e=it();if(!e&&!st())throw new N;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{_=await R.launch(n)}catch(t){throw e?new j(e,t):new N}return g.debug("Headless Chrome launched for screenshots"),_}function st(){try{return typeof R?.executablePath=="function"}catch{return!1}}async function W(e,n){if(!await U())return null;let s=await(await z()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"load",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(l=>{let i=document.querySelectorAll("style").length,d=0,u=()=>{let m=document.querySelectorAll("style").length;if(m===i){if(d++,d>=3){l(!0);return}}else d=0,i=m;setTimeout(u,100)};setTimeout(u,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(l=>setTimeout(l,500));let a=await s.evaluate(l=>{let i=document.querySelector("#storybook-root");if(!i)return null;let d=window.innerHeight,u=window.innerWidth,m=v=>v.setAttribute("data-uic-drilled",""),w=()=>{let v=document.createElement("style");v.id="uic-drilled-bg-reset",v.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(v),document.body.offsetHeight};try{let T=new Function("return ("+l+")")()(i),y=T?.getBoundingClientRect(),E=!!y&&y.width>=u*.9&&y.height>=d*.9;if(T&&T!==i&&y&&y.width>0&&y.height>0&&!E){for(let P=T.parentElement;P&&P!==i;P=P.parentElement)m(P);return w(),{top:y.top,bottom:y.bottom,left:y.left,right:y.right}}}catch{}let p=1/0,h=0,S=1/0,C=0,b=!1;function x(v){for(let T of Array.from(v.children)){let y=window.getComputedStyle(T);if(y.display==="none"||y.visibility==="hidden"||y.position==="fixed"||y.position==="absolute")continue;let E=T.getBoundingClientRect();if(E.height<=0||E.width<=0)continue;if((E.width>=u*.9||E.height>=d*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),x(T);continue}if(T.children.length===1){let H=y.backgroundColor,$e=H==="rgba(0, 0, 0, 0)"||H==="transparent"||H==="",Me=y.borderStyle!=="none"&&y.borderWidth!=="0px",Ne=y.boxShadow!=="none",Fe=!$e||Me||Ne,ee=T.children[0].getBoundingClientRect(),ke=ee.width>=E.width*.95&&ee.height>=E.height*.95;if(!Fe||ke){T.setAttribute("data-uic-drilled",""),x(T);continue}}p=Math.min(p,E.top),h=Math.max(h,E.bottom),S=Math.min(S,E.left),C=Math.max(C,E.right),b=!0}}return x(i),b?(w(),{top:p,bottom:h,left:S,right:C}):null},ce);await s.evaluate(()=>new Promise(l=>requestAnimationFrame(()=>l())));let o=4,c=a?{x:Math.max(0,a.left-o),y:Math.max(0,a.top-o),width:Math.min(a.right-a.left+o*2,800),height:Math.min(a.bottom-a.top+o*2,600)}:void 0,f=await s.screenshot({type:"png",omitBackground:!0,...c?{clip:c}:{fullPage:!1}});return Buffer.from(f)}finally{await s.close()}}async function ue(e,n,t,r){if(!await U())return null;let o=await(await z()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let c=r?.storyId||"",f=`${t}/iframe.html?viewMode=story&id=${c}&globals=`;await o.goto(f,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(d=>{let u=document.getElementById("storybook-root");u&&(u.innerHTML=d)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(d=>setTimeout(d,500));let l=await o.evaluate(d=>{let u=document.querySelector("#storybook-root");if(!u)return null;let m=window.innerWidth,w=window.innerHeight,p=8;try{let x=new Function("return ("+d+")")()(u),v=x?.getBoundingClientRect(),T=!!v&&v.width>=m*.9&&v.height>=w*.9;if(x&&x!==u&&v&&v.width>0&&v.height>0&&!T)return{x:Math.max(0,v.x-p),y:Math.max(0,v.y-p),width:v.width+p*2,height:v.height+p*2}}catch{}function h(b){let x=b.getBoundingClientRect();if(x.width===0||x.height===0)return null;if(x.width<m*.8&&x.height>0)return x;for(let v of Array.from(b.children)){let T=window.getComputedStyle(v);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let y=h(v);if(y)return y}return null}let S=h(u);if(S)return{x:Math.max(0,S.x-p),y:Math.max(0,S.y-p),width:S.width+p*2,height:S.height+p*2};let C=u.firstElementChild;if(C){let b=C.getBoundingClientRect();return{x:b.x,y:b.y,width:b.width,height:b.height}}return null},ce);if(!l)throw new Error("Could not determine component bounds from snapshot");let i=await o.screenshot({type:"png",clip:l});return Buffer.from(i)}finally{await o.close()}}async function F(){return U()}async function G(){_&&(await _.close(),_=null)}async function X(e,n){return await e.evaluate(r=>{let s=document.getElementById("storybook-root")||document.getElementById("root"),a=null;if(s)try{a=new Function("return ("+r+")")()(s)}catch{a=s.firstElementChild}let o={};if(a){let i=window.getComputedStyle(a);for(let d=0;d<i.length;d++)o[i[d]]=i.getPropertyValue(i[d])}let c={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function f(i){return i.replace(/-([a-z])/g,(d,u)=>u.toUpperCase())}function l(i,d){if(d>4)return null;let u=i.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(u))return null;let m=i.className,w=typeof m=="string"?m:m?.baseVal||"",p=i.id||void 0,h=i.getAttribute("role")||void 0,S;for(let y of Array.from(i.childNodes))if(y.nodeType===3){let E=y.textContent?.trim();if(E){S=E.length>50?E.substring(0,50)+"...":E;break}}let C=u;p?C=`${u}#${p}`:w&&(C=`${u}.${w.split(" ").filter(Boolean).join(".")}`);let b=window.getComputedStyle(i),x=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],v={};for(let y of x){let E=b.getPropertyValue(y),P=f(y);E&&!c[P]?.includes(E)&&(v[P]=E)}if(u==="svg"||i.closest("svg"))for(let y of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let E=i.getAttribute(y);E&&(v[f(y)]=E)}let T=[];for(let y of Array.from(i.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden")continue;let P=l(y,d+1);P&&T.push(P)}return{selector:C,tagName:u,className:w,id:p,role:h,textContent:S,styles:v,children:T}}return{computedStyles:o,domTree:a?l(a,0):null}},n)}async function k(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let s=setTimeout(r,t);try{let a=window.__STORYBOOK_ADDONS_CHANNEL__;if(a){let o=()=>{clearTimeout(s),a.off("storyRendered",o),setTimeout(r,100)};a.on("storyRendered",o)}else clearTimeout(s),setTimeout(r,300)}catch{clearTimeout(s),r()}}),n)}async function de(e,n,t=15e3){return await e.evaluate((r,s)=>{let a=window,o=a.__STORYBOOK_PREVIEW__,c=a.__STORYBOOK_ADDONS_CHANNEL__;return!o||!c||typeof o.renderSelection!="function"||typeof o.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(f=>{let l=!1,i=w=>{if(!l){l=!0,clearTimeout(m);try{c.off("storyRendered",d),c.off("storyErrored",u),c.off("storyMissing",u)}catch{}f(w)}},d=w=>{let p=typeof w=="string"?w:w?.storyId||w?.id;(!p||p===r)&&setTimeout(()=>i("ok"),100)},u=()=>i("errored"),m=setTimeout(()=>i("timeout"),s);c.on("storyRendered",d),c.on("storyErrored",u),c.on("storyMissing",u);try{o.selectionStore.setSelection({storyId:r,viewMode:"story"}),o.renderSelection()}catch{i("nav-failed")}})},n,t)}async function pe(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function K(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(s=>{let a=r.getAttribute(s)??"";return s!=="class"?`${s}=${a}`:`class=${a.split(/\s+/).filter(c=>c&&!c.startsWith("sb-")).sort().join(" ")}`}).join("|"):"<missing>",t=document.getElementById("storybook-root")||document.getElementById("root");return[`html[${n(document.documentElement)}]`,`body[${n(document.body)}]`,`root[${n(t)}]`].join(" ")})}catch{return null}}var at=6,ct=15,lt=9e4,ut=2e4;function dt(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:ct}function pt(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var I=[],Y=[];function ft(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function J(){let e=Y.shift();e&&e()}function fe(){let e=Date.now(),n=I.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>lt);if(n.length===0){I.length===0&&q();return}I=I.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});I.length===0&&q()}var L=null;function mt(){L||(L=setInterval(fe,3e4),L.unref?.())}function q(){L&&(clearInterval(L),L=null)}async function gt(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(ft(n,t),{waitUntil:"load",timeout:ut}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await k(r),r}catch(s){throw await r.close().catch(()=>{}),s}}async function ht(e,n,t){for(;;){fe();let r=I.find(s=>s.baseUrl===n&&!s.busy&&s.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(I.length<at){let s={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};I.push(s),mt();try{return s.page=await gt(e,n,t),s.baseline=await K(s.page),{entry:s,fresh:!0}}catch{return I=I.filter(a=>a!==s),J(),null}}await new Promise(s=>Y.push(s))}}function O(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=dt())&&(I=I.filter(t=>t!==e),e.page?.close().catch(()=>{})),J()}async function me(e,n,t,r){if(!pt())return{ok:!1,reason:"disabled"};let s=await ht(e,n,t);if(!s)return{ok:!1,reason:"boot-failed"};let{entry:a,fresh:o}=s,c=a.page;try{if(!o){let l=await de(c,t);if(l!=="ok")return O(a,!0),{ok:!1,reason:`switch-${l}`};let i=await pe(c);if(i&&i!==t)return O(a,!0),{ok:!1,reason:"selection-mismatch"};if(a.baseline===null)return O(a,!0),{ok:!1,reason:"baseline-unavailable"};let d=await K(c);if(d===null)return O(a,!0),{ok:!1,reason:"document-unreadable"};if(d!==a.baseline)return O(a,!0),{ok:!1,reason:"document-drift"};await c.evaluate(()=>document.fonts.ready)}let f=await r(c);return O(a,!1),{ok:!0,value:f,booted:o}}catch(f){return O(a,!0),{ok:!1,reason:`error:${f.message}`}}}async function Z(){q();let e=I;for(I=[];Y.length;)J();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Ce=M.toString(),Q=null,A=null,Ee=!1;async function It(){if(!Ee){Ee=!0;try{let e=await Promise.resolve().then(()=>(be(),Se));Q=e.validateCodeForFile,A=e.formatValidationResult,g.debug("Code validator loaded - fix validation enabled")}catch{g.debug("Code validator not available - skipping fix validation")}}}var Pt="UICOPILOT/APPLY_FIXES",_t="UICOPILOT/FIX_STARTED",Ot="UICOPILOT/FIX_COMPLETED",Rt="UICOPILOT/FIX_FAILED",ve="UICOPILOT/ALL_FIXES_APPLIED",Lt="UICOPILOT/RELOAD_REQUIRED",Te="UICOPILOT/WORKSPACE_PATH",$t="UICOPILOT/REQUEST_WORKSPACE_PATH",Mt="UICOPILOT/DISCOVER_COMPONENT_FILES",Ie="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Pe(e,n){let t=e.toLowerCase(),r=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),s=[`src/**/fui-${t}/fui-${t}.css`,`src/**/fui-${t}/*.css`,`src/**/${t}/${t}.css`,`src/**/${r}/${r}.css`,`src/**/*${t}*.css`,`src/**/*${r}*.css`,`styles/**/*${t}*.css`],a=[`src/**/fui-${t}/fui-${t}.tsx`,`src/**/fui-${t}/*.tsx`,`src/**/${t}/${t}.tsx`,`src/**/${r}/${r}.tsx`,`src/**/*${r}*.tsx`,`src/**/*${r}*.jsx`],o=[],c=[];for(let p of s)try{let h=await xe(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});h.length>0&&o.push(...h)}catch{}for(let p of a)try{let h=await xe(p,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});h.length>0&&c.push(...h)}catch{}let f=[...new Set(o)],l=[...new Set(c)],i=p=>{if(p.length===0)return;let h=p.find(b=>b.includes(`/fui-${t}/`)&&b.endsWith(".css"));if(h)return h;let S=p.find(b=>b.toLowerCase().includes(`/${t}/${t}.css`)||b.includes(`/${r}/${r}.css`));if(S)return S;let C=p.find(b=>b.toLowerCase().endsWith(`/${t}.css`)||b.endsWith(`/${r}.css`));return C||p[0]},d=p=>{if(p.length===0)return;let h=p.filter(x=>!x.includes(".stories.")&&!x.includes(".test."));if(h.length===0)return p[0];let S=h.find(x=>x.includes(`/fui-${t}/`)&&(x.endsWith(".tsx")||x.endsWith(".jsx")));if(S)return S;let C=h.find(x=>x.toLowerCase().includes(`/${t}/${t}.tsx`)||x.includes(`/${r}/${r}.tsx`));if(C)return C;let b=h.find(x=>x.toLowerCase().endsWith(`/${t}.tsx`)||x.endsWith(`/${r}.tsx`));return b||h[0]},u=i(f),m=d(l),w=[...f,...l];return g.debug(`Discovered files for "${e}":`,{cssFile:u,componentFile:m,totalMatches:w.length}),{cssFile:u,componentFile:m,allMatches:[...new Set(w)]}}var Nt=100;function Ft(e){return new Promise(n=>setTimeout(n,e))}async function kt(e,n){if(await It(),!Q||!A)return g.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Q(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return g.warn(`Code validation failed for ${n}:`),console.warn(A(t)),{valid:!1,error:r}}return t.warnings.length>0&&(g.warn(`Code validation warnings for ${n}:`),console.warn(A(t))),g.debug(`Validation passed for ${n}`),{valid:!0}}var _e=!1;function At(e){if(_e)return e;_e=!0;let n=process.cwd();return g.debug("Apply fixes initialized"),g.debug("Workspace:",n),e.emit(Te,{path:n}),e.on($t,()=>{g.debug("Workspace path requested by browser"),g.debug("Emitting workspace path response:",n),e.emit(Te,{path:n})}),e.on(Mt,async t=>{let{componentName:r,storyId:s}=t;g.debug(`Discovering files for component: ${r}`);try{let a=await Pe(r,n);e.emit(Ie,{componentName:r,storyId:s,...a,workspacePath:n})}catch(a){g.error("File discovery error:",a),e.emit(Ie,{componentName:r,storyId:s,error:a.message,allMatches:[]})}}),e.on(Pt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,a=s||n;s?g.debug(`Using storybookRoot from API: ${s}`):g.debug(`Using process.cwd(): ${n}`),g.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function c(i){let d=i.targetFileType||"css",u=i.targetFilePath||i.generatedFix?.filePath,m="",w=i.title?.match(/^(\w+)\s/);if(w&&(m=w[1]),!m&&u){let S=u.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(m=S[1])}if(!m)return g.debug(`Could not extract component name, using provided path: ${u}`),u||null;if(!o.has(m)){let S=await Pe(m,a);o.set(m,S)}let p=o.get(m),h=d==="css"?p.cssFile:p.componentFile;return h?(g.debug(`Discovered ${d} path: ${h} (was: ${u})`),h):(g.debug(`No ${d} file discovered, using provided: ${u}`),u||null)}let f=[];for(let i of r){let{generatedFix:d}=i,u=i.targetFilePath||d?.filePath,m=await c(i)||u;g.debug("Processing issue:",{id:i.id,type:i.type,targetFileType:i.targetFileType||"css",targetPath:m,providedPath:u!==m?u:"(same)",codeLength:d?.code?.length||0}),e.emit(_t,{issueId:i.id});try{if(!d||!d.code||!m)throw new Error("Missing AI-generated fix data (code or filePath)");g.debug("Code to write (first 200 chars):",d.code.substring(0,200)),g.debug(`Code length: ${d.code.length} chars`);let w=await kt(d.code,m);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let p=D.isAbsolute(m)?m:D.join(a,m);g.debug(`Writing to absolute path: ${p}`),await Oe.writeFile(p,d.code,"utf-8"),await Ft(Nt);let h={success:!0,issueId:i.id,filePath:m,timestamp:new Date};e.emit(Ot,{issueId:i.id,result:h}),g.debug(`\u2713 Applied ${i.targetFileType||"css"} fix to: ${m}`),f.push(h)}catch(w){let p=w.message||"Unknown error";e.emit(Rt,{issueId:i.id,error:p}),g.error(`\u2717 Error: ${p}`),f.push({success:!1,issueId:i.id,error:p,timestamp:new Date})}}let l={total:f.length,succeeded:f.filter(i=>i.success).length,failed:f.filter(i=>!i.success).length};e.emit(ve,{results:f,summary:l}),g.debug(`Completed: ${l.succeeded}/${l.total} fixes applied`),l.succeeded>0&&e.emit(Lt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:f.filter(i=>i.success).map(i=>i.filePath)})}catch(r){g.error("Fatal error during fix application:",r),e.emit(ve,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Dt(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(a,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(a,o)=>{try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let l=new URL(a.url||"",`http://${a.headers.host}`).searchParams.get("storyId");if(!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let d=`http://${a.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Taking screenshot: ${l}`);let u=await W(d,{selector:"#storybook-root > *"});if(!u){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let m=u.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${m}`}))}catch(c){g.error("Screenshot error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/capture",async(a,o)=>{try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=new URL(a.url||"",`http://${a.headers.host}`),l=f.searchParams.get("storyId");if(!l){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let i=f.searchParams.get("domOnly")==="1",d=a.headers.host||"localhost:6006",u=`http://${d}/iframe.html?viewMode=story&id=${l}&globals=`;g.debug(`Full capture${i?" (domOnly)":""}: ${l}`);let m=null;if(!i&&(m=await W(u,{selector:"#storybook-root > *"}),!m)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let w=await le(),p=f.searchParams.get("warm")==="0",h=null,S="cold";if(!p){let C=`http://${d}`,b=await me(w,C,l,x=>X(x,Ce));b.ok?(h=b.value,S=b.booted?"warm-boot":"warm"):g.debug(`Warm capture unavailable (${b.reason}): ${l}`)}if(!h){let C=await w.newPage();try{await C.setCacheEnabled(!1),await C.setViewport({width:800,height:600}),await C.goto(u,{waitUntil:"load",timeout:15e3}),await C.evaluate(()=>document.fonts.ready),await C.waitForSelector("#storybook-root > *",{timeout:1e4}),await k(C),h=await X(C,Ce)}finally{await C.close()}}g.debug(`Capture path for ${l}: ${S}`),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:m?`data:image/png;base64,${m.toString("base64")}`:void 0,computedStyles:h.computedStyles,domTree:h.domTree}))}catch(c){g.error("Capture error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(a,o)=>{if(a.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await F()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let f=[];for await(let S of a)f.push(typeof S=="string"?Buffer.from(S):S);let l=JSON.parse(Buffer.concat(f).toString()),{html:i,stylesheetUrls:d,storyId:u}=l;if(!i){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${a.headers.host||"localhost:6006"}`;g.debug(`Taking snapshot screenshot for ${u||"unknown"}`);let p=await ue(i,d||[],w,{storyId:u});if(!p){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let h=p.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${h}`}))}catch(c){g.error("Snapshot screenshot error:",c.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:c.message}))}}),t.httpServer?.on("close",()=>{Z().catch(()=>{}).finally(()=>G().catch(()=>{}))});let r=a=>{Z().catch(()=>{}).then(()=>G()).catch(()=>{}).finally(()=>{process.kill(process.pid,a)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var Bt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Le(import.meta.url),n=Re(e);return B(n,"manager.mjs")}return B(__dirname,"manager.mjs")},Ht=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Le(import.meta.url),n=Re(e);return B(n,"preview.mjs")}return B(__dirname,"preview.mjs")};function ho(e=[]){return[...e,Bt()]}function yo(e=[]){return[...e,Ht()]}export{At as experimental_serverChannel,ho as managerEntries,yo as previewAnnotations,Dt as viteFinal};
|