@uicopilot/storybook-addon 0.5.50 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/manager.mjs +111 -78
- 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(i=>i.trim()),t=n.filter(i=>i.trim().startsWith("//")||i.trim().startsWith("/*")||i.trim().startsWith("*")||i.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 i of r)if(i.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 Qe,he=Re(()=>{"use strict";Qe=50});var Et={};te(Et,{experimental_serverChannel:()=>ve,managerEntries:()=>bt,previewAnnotations:()=>Ct,viteFinal:()=>Te});module.exports=Ne(Et);var _=require("path"),Z=require("url");var Ee=H(require("fs/promises")),U=H(require("path")),K=require("glob");var ae=require("fs"),ce=require("module");var G={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 Fe(){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=`[${G.NAME}]`,l={debug:(...e)=>{Fe()&&console.log(V,...e)},info:(...e)=>{console.log(V,...e)},warn:(...e)=>{console.warn(V,...e)},error:(...e)=>{console.error(V,...e)}};var Je=["flex","inline-flex"],Ke=["grid","inline-grid"],Wt=[...Je,...Ke];var j=null,L=null,se=!1;async function X(){if(se)return!!j;if(se=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,ce.createRequire)(process.cwd()+"/");try{return j=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return j=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ze(){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,ae.existsSync)(n))return n}async function le(){if(L&&L.connected)return L;let e=Ze(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return L=await j.launch(n),l.debug("Headless Chrome launched for screenshots"),L}async function q(e,n){if(!await X())return null;let i=await(await le()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await i.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await i.evaluate(()=>document.fonts.ready),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,g=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(g,100)};setTimeout(g,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let s=await i.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,g=1/0,f=0,S=1/0,a=0,d=!1;function w(x){for(let y of Array.from(x.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden"||E.position==="fixed"||E.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let I=E.backgroundColor,$=I==="rgba(0, 0, 0, 0)"||I==="transparent"||I==="",M=E.borderStyle!=="none"&&E.borderWidth!=="0px",R=E.boxShadow!=="none",N=!$||M||R,F=y.children[0].getBoundingClientRect(),k=F.width>=T.width*.95&&F.height>=T.height*.95;if(!N||k){y.setAttribute("data-uic-drilled",""),w(y);continue}}g=Math.min(g,T.top),f=Math.max(f,T.bottom),S=Math.min(S,T.left),a=Math.max(a,T.right),d=!0}}if(w(p),!d)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:g,bottom:f,left:S,right:a}});await i.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let o=4,u=s?{x:Math.max(0,s.left-o),y:Math.max(0,s.top-o),width:Math.min(s.right-s.left+o*2,800),height:Math.min(s.bottom-s.top+o*2,600)}:void 0,h=await i.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(h)}finally{await i.close()}}async function ue(e,n,t,r){if(!await X())return null;let o=await(await le()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(m=>{let g=document.getElementById("storybook-root");g&&(g.innerHTML=m)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await o.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let g=window.innerWidth;function f(d){let w=d.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<g*.8&&w.height>0)return w;for(let b of Array.from(d.children)){let x=window.getComputedStyle(b);if(x.position==="fixed"||x.position==="absolute"||x.display==="none"||x.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let S=f(m);if(S)return{x:Math.max(0,S.x-8),y:Math.max(0,S.y-8),width:S.width+16,height:S.height+16};let a=m.firstElementChild;if(a){let d=a.getBoundingClientRect();return{x:d.x,y:d.y,width:d.width,height:d.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await o.close()}}async function z(){return X()}async function J(){L&&(await L.close(),L=null)}var Y=null,B=null,ye=!1;async function ct(){if(!ye){ye=!0;try{let e=await Promise.resolve().then(()=>(he(),ge));Y=e.validateCodeForFile,B=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var lt="UICOPILOT/APPLY_FIXES",ut="UICOPILOT/FIX_STARTED",dt="UICOPILOT/FIX_COMPLETED",pt="UICOPILOT/FIX_FAILED",we="UICOPILOT/ALL_FIXES_APPLIED",ft="UICOPILOT/RELOAD_REQUIRED",Se="UICOPILOT/WORKSPACE_PATH",mt="UICOPILOT/REQUEST_WORKSPACE_PATH",gt="UICOPILOT/DISCOVER_COMPONENT_FILES",xe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function be(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`],s=[`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 a of i)try{let d=await(0,K.glob)(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});d.length>0&&o.push(...d)}catch{}for(let a of s)try{let d=await(0,K.glob)(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});d.length>0&&u.push(...d)}catch{}let h=[...new Set(o)],p=[...new Set(u)],c=a=>{if(a.length===0)return;let d=a.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(d)return d;let w=a.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=a.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let d=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(d.length===0)return a[0];let w=d.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=d.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${r}/${r}.tsx`));if(b)return b;let x=d.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${r}.tsx`));return x||d[0]},g=c(h),f=m(p),S=[...h,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:g,componentFile:f,totalMatches:S.length}),{cssFile:g,componentFile:f,allMatches:[...new Set(S)]}}var ht=100;function yt(e){return new Promise(n=>setTimeout(n,e))}async function wt(e,n){if(await ct(),!Y||!B)return l.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=Y(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return l.warn(`Code validation failed for ${n}:`),console.warn(B(t)),{valid:!1,error:r}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${n}:`),console.warn(B(t))),l.debug(`Validation passed for ${n}`),{valid:!0}}var Ce=!1;function ve(e){if(Ce)return e;Ce=!0;let n=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",n),e.emit(Se,{path:n}),e.on(mt,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",n),e.emit(Se,{path:n})}),e.on(gt,async t=>{let{componentName:r,storyId:i}=t;l.debug(`Discovering files for component: ${r}`);try{let s=await be(r,n);e.emit(xe,{componentName:r,storyId:i,...s,workspacePath:n})}catch(s){l.error("File discovery error:",s),e.emit(xe,{componentName:r,storyId:i,error:s.message,allMatches:[]})}}),e.on(lt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,s=i||n;i?l.debug(`Using storybookRoot from API: ${i}`):l.debug(`Using process.cwd(): ${n}`),l.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(c){let m=c.targetFileType||"css",g=c.targetFilePath||c.generatedFix?.filePath,f="",S=c.title?.match(/^(\w+)\s/);if(S&&(f=S[1]),!f&&g){let w=g.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${g}`),g||null;if(!o.has(f)){let w=await be(f,s);o.set(f,w)}let a=o.get(f),d=m==="css"?a.cssFile:a.componentFile;return d?(l.debug(`Discovered ${m} path: ${d} (was: ${g})`),d):(l.debug(`No ${m} file discovered, using provided: ${g}`),g||null)}let h=[];for(let c of r){let{generatedFix:m}=c,g=c.targetFilePath||m?.filePath,f=await u(c)||g;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:g!==f?g:"(same)",codeLength:m?.code?.length||0}),e.emit(ut,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let S=await wt(m.code,f);if(!S.valid)throw new Error(`Code validation failed: ${S.error}. Fix was not applied to prevent breaking the file.`);let a=U.isAbsolute(f)?f:U.join(s,f);l.debug(`Writing to absolute path: ${a}`),await Ee.writeFile(a,m.code,"utf-8"),await yt(ht);let d={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(dt,{issueId:c.id,result:d}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),h.push(d)}catch(S){let a=S.message||"Unknown error";e.emit(pt,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),h.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(we,{results:h,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(ft,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){l.error("Fatal error during fix application:",r),e.emit(we,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Te(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(s,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(s,o)=>{try{if(!await z()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(s.url||"",`http://${s.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${s.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let g=await q(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(u){l.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(s,o)=>{try{if(!await z()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(s.url||"",`http://${s.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${s.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let g=await q(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let S=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await S.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let x=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let E=()=>{clearTimeout(x),y.off("storyRendered",E),setTimeout(b,100)};y.on("storyRendered",E)}else clearTimeout(x),setTimeout(b,300)}catch{clearTimeout(x),b()}}));let d=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),x={};if(b){let C=window.getComputedStyle(b);for(let I=0;I<C.length;I++)x[C[I]]=C.getPropertyValue(C[I])}let y={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(C){return C.replace(/-([a-z])/g,(I,$)=>$.toUpperCase())}function T(C,I){if(I>4)return null;let $=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes($))return null;let M=C.className,R=typeof M=="string"?M:M?.baseVal||"",N=C.id||void 0,Q=C.getAttribute("role")||void 0,F;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let v=P.textContent?.trim();if(v){F=v.length>50?v.substring(0,50)+"...":v;break}}let k=$;N?k=`${$}#${N}`:R&&(k=`${$}.${R.split(" ").filter(Boolean).join(".")}`);let Ie=window.getComputedStyle(C),Pe=["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"],W={};for(let P of Pe){let v=Ie.getPropertyValue(P),A=E(P);v&&!y[A]?.includes(v)&&(W[A]=v)}if($==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let v=C.getAttribute(P);v&&(W[E(P)]=v)}let ee=[];for(let P of Array.from(C.children)){let v=window.getComputedStyle(P);if(v.display==="none"||v.visibility==="hidden")continue;let A=T(P,I+1);A&&ee.push(A)}return{selector:k,tagName:$,className:R,id:N,role:Q,textContent:F,styles:W,children:ee}}return{computedStyles:x,domTree:b?T(b,0):null}}),w=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:d.computedStyles,domTree:d.domTree}))}finally{await a.close(),await S.close()}}catch(u){l.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(s,o)=>{if(s.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await z()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let w of s)h.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:m,storyId:g}=p;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let S=`http://${s.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${g||"unknown"}`);let a=await ue(c,m||[],S,{storyId:g});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let d=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${d}`}))}catch(u){l.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=s=>{J().catch(()=>{}).finally(()=>{process.kill(process.pid,s)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var O={},St=()=>{if(typeof O<"u"&&O.url){let e=(0,Z.fileURLToPath)(O.url),n=(0,_.dirname)(e);return(0,_.join)(n,"manager.mjs")}return(0,_.join)(__dirname,"manager.mjs")},xt=()=>{if(typeof O<"u"&&O.url){let e=(0,Z.fileURLToPath)(O.url),n=(0,_.dirname)(e);return(0,_.join)(n,"preview.mjs")}return(0,_.join)(__dirname,"preview.mjs")};function bt(e=[]){return[...e,St()]}function Ct(e=[]){return[...e,xt()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
|
|
1
|
+
"use strict";var _e=Object.create;var D=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Re=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ne=(e,n)=>()=>(e&&(n=e(e=0)),n);var te=(e,n)=>{for(var t in n)D(e,t,{get:n[t],enumerable:!0})},ne=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Re(n))!Fe.call(e,i)&&i!==t&&D(e,i,{get:()=>n[i],enumerable:!(r=$e(n,i))||r.enumerable});return e};var H=(e,n,t)=>(t=e!=null?_e(Me(e)):{},ne(n||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Oe=e=>ne(D({},"__esModule",{value:!0}),e);var he={};te(he,{detectFileType:()=>fe,formatValidationResult:()=>lt,isValidCode:()=>ct,validateCode:()=>me,validateCodeForFile:()=>ge});function nt(e,n={}){let t=n.minLength??tt;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 ot(e){let n=e.split(`
|
|
2
|
+
`).filter(i=>i.trim()),t=n.filter(i=>i.trim().startsWith("//")||i.trim().startsWith("/*")||i.trim().startsWith("*")||i.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 i of r)if(i.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 it(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,i="",s=!1;for(let o=0;o<e.length;o++){let u=e[o],h=e[o-1];if((u==='"'||u==="'"||u==="`")&&h!=="\\"){r?u===i&&(r=!1,s=!1):(r=!0,i=u,u==="`"&&(s=!0));continue}if(!r){if(n[u])t.push(n[u]);else if(Object.values(n).includes(u)&&t.pop()!==u)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${u}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function pe(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 i=/import\s+(?:React|\{[^}]*\})\s+from\s+['"]react['"]/.test(e);/<[A-Z][a-zA-Z]*|<[a-z]+[\s/>]/.test(e)&&!i&&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 u=[{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:h,message:p}of u)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:r}}function st(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 s=(e.match(/\{[^}]+\}/g)||[]).length;return s===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"}),s>0&&s<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${s} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function at(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 fe(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 me(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},i=nt(e,t);i&&r.errors.push(i);let s=rt(e);s&&r.errors.push(s);let o=ot(e);o&&r.errors.push(o);let u=it(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:h,warnings:p}=at(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:h,warnings:p}=pe(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:h,warnings:p}=st(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"ts":case"js":{let{errors:h,warnings:p}=pe(e,t);r.errors.push(...h),r.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function ge(e,n,t={}){let r=fe(n);return me(e,r,t)}function ct(e,n,t={}){return ge(e,n,t).valid}function lt(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 tt,ye=Ne(()=>{"use strict";tt=50});var Tt={};te(Tt,{experimental_serverChannel:()=>Te,managerEntries:()=>Et,previewAnnotations:()=>vt,viteFinal:()=>Ie});module.exports=Oe(Tt);var $=require("path"),Z=require("url");var ve=H(require("fs/promises")),U=H(require("path")),Y=require("glob");var ce=require("fs"),le=require("module");var G={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 ke(){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=`[${G.NAME}]`,l={debug:(...e)=>{ke()&&console.log(V,...e)},info:(...e)=>{console.log(V,...e)},warn:(...e)=>{console.warn(V,...e)},error:(...e)=>{console.error(V,...e)}};var Je=["flex","inline-flex"],Ze=["grid","inline-grid"],Zt=[...Je,...Ze];var z=null,_=null,ae=!1;async function X(){if(ae)return!!z;if(ae=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,le.createRequire)(process.cwd()+"/");try{return z=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return z=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function et(){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,ce.existsSync)(n))return n}async function ue(){if(_&&_.connected)return _;let e=et(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return _=await z.launch(n),l.debug("Headless Chrome launched for screenshots"),_}async function q(e,n){if(!await X())return null;let i=await(await ue()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await i.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await i.evaluate(()=>document.fonts.ready),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,g=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(g,100)};setTimeout(g,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let s=await i.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,g=1/0,f=0,w=1/0,a=0,d=!1;function S(x){for(let y of Array.from(x.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden"||E.position==="fixed"||E.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),S(y);continue}if(y.children.length===1){let I=E.backgroundColor,L=I==="rgba(0, 0, 0, 0)"||I==="transparent"||I==="",M=E.borderStyle!=="none"&&E.borderWidth!=="0px",F=E.boxShadow!=="none",N=!L||M||F,O=y.children[0].getBoundingClientRect(),k=O.width>=T.width*.95&&O.height>=T.height*.95;if(!N||k){y.setAttribute("data-uic-drilled",""),S(y);continue}}g=Math.min(g,T.top),f=Math.max(f,T.bottom),w=Math.min(w,T.left),a=Math.max(a,T.right),d=!0}}if(S(p),!d)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:g,bottom:f,left:w,right:a}});await i.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let o=4,u=s?{x:Math.max(0,s.left-o),y:Math.max(0,s.top-o),width:Math.min(s.right-s.left+o*2,800),height:Math.min(s.bottom-s.top+o*2,600)}:void 0,h=await i.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(h)}finally{await i.close()}}async function de(e,n,t,r){if(!await X())return null;let o=await(await ue()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(m=>{let g=document.getElementById("storybook-root");g&&(g.innerHTML=m)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await o.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let g=window.innerWidth;function f(d){let S=d.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<g*.8&&S.height>0)return S;for(let b of Array.from(d.children)){let x=window.getComputedStyle(b);if(x.position==="fixed"||x.position==="absolute"||x.display==="none"||x.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let w=f(m);if(w)return{x:Math.max(0,w.x-8),y:Math.max(0,w.y-8),width:w.width+16,height:w.height+16};let a=m.firstElementChild;if(a){let d=a.getBoundingClientRect();return{x:d.x,y:d.y,width:d.width,height:d.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await o.close()}}async function j(){return X()}async function K(){_&&(await _.close(),_=null)}var J=null,B=null,Se=!1;async function ut(){if(!Se){Se=!0;try{let e=await Promise.resolve().then(()=>(ye(),he));J=e.validateCodeForFile,B=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var dt="UICOPILOT/APPLY_FIXES",pt="UICOPILOT/FIX_STARTED",ft="UICOPILOT/FIX_COMPLETED",mt="UICOPILOT/FIX_FAILED",we="UICOPILOT/ALL_FIXES_APPLIED",gt="UICOPILOT/RELOAD_REQUIRED",xe="UICOPILOT/WORKSPACE_PATH",ht="UICOPILOT/REQUEST_WORKSPACE_PATH",yt="UICOPILOT/DISCOVER_COMPONENT_FILES",be="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Ce(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`],s=[`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 a of i)try{let d=await(0,Y.glob)(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});d.length>0&&o.push(...d)}catch{}for(let a of s)try{let d=await(0,Y.glob)(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});d.length>0&&u.push(...d)}catch{}let h=[...new Set(o)],p=[...new Set(u)],c=a=>{if(a.length===0)return;let d=a.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(d)return d;let S=a.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(S)return S;let b=a.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let d=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(d.length===0)return a[0];let S=d.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(S)return S;let b=d.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${r}/${r}.tsx`));if(b)return b;let x=d.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${r}.tsx`));return x||d[0]},g=c(h),f=m(p),w=[...h,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:g,componentFile:f,totalMatches:w.length}),{cssFile:g,componentFile:f,allMatches:[...new Set(w)]}}var St=100;function wt(e){return new Promise(n=>setTimeout(n,e))}async function xt(e,n){if(await ut(),!J||!B)return l.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=J(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return l.warn(`Code validation failed for ${n}:`),console.warn(B(t)),{valid:!1,error:r}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${n}:`),console.warn(B(t))),l.debug(`Validation passed for ${n}`),{valid:!0}}var Ee=!1;function Te(e){if(Ee)return e;Ee=!0;let n=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",n),e.emit(xe,{path:n}),e.on(ht,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",n),e.emit(xe,{path:n})}),e.on(yt,async t=>{let{componentName:r,storyId:i}=t;l.debug(`Discovering files for component: ${r}`);try{let s=await Ce(r,n);e.emit(be,{componentName:r,storyId:i,...s,workspacePath:n})}catch(s){l.error("File discovery error:",s),e.emit(be,{componentName:r,storyId:i,error:s.message,allMatches:[]})}}),e.on(dt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,s=i||n;i?l.debug(`Using storybookRoot from API: ${i}`):l.debug(`Using process.cwd(): ${n}`),l.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(c){let m=c.targetFileType||"css",g=c.targetFilePath||c.generatedFix?.filePath,f="",w=c.title?.match(/^(\w+)\s/);if(w&&(f=w[1]),!f&&g){let S=g.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(f=S[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${g}`),g||null;if(!o.has(f)){let S=await Ce(f,s);o.set(f,S)}let a=o.get(f),d=m==="css"?a.cssFile:a.componentFile;return d?(l.debug(`Discovered ${m} path: ${d} (was: ${g})`),d):(l.debug(`No ${m} file discovered, using provided: ${g}`),g||null)}let h=[];for(let c of r){let{generatedFix:m}=c,g=c.targetFilePath||m?.filePath,f=await u(c)||g;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:g!==f?g:"(same)",codeLength:m?.code?.length||0}),e.emit(pt,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let w=await xt(m.code,f);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let a=U.isAbsolute(f)?f:U.join(s,f);l.debug(`Writing to absolute path: ${a}`),await ve.writeFile(a,m.code,"utf-8"),await wt(St);let d={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(ft,{issueId:c.id,result:d}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),h.push(d)}catch(w){let a=w.message||"Unknown error";e.emit(mt,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),h.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(we,{results:h,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(gt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){l.error("Fatal error during fix application:",r),e.emit(we,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Ie(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(s,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(s,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 p=new URL(s.url||"",`http://${s.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${s.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let g=await q(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(u){l.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(s,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(s.url||"",`http://${s.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${s.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let g=await q(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let w=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await w.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let x=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let E=()=>{clearTimeout(x),y.off("storyRendered",E),setTimeout(b,100)};y.on("storyRendered",E)}else clearTimeout(x),setTimeout(b,300)}catch{clearTimeout(x),b()}}));let d=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),x={};if(b){let C=window.getComputedStyle(b);for(let I=0;I<C.length;I++)x[C[I]]=C.getPropertyValue(C[I])}let y={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(C){return C.replace(/-([a-z])/g,(I,L)=>L.toUpperCase())}function T(C,I){if(I>4)return null;let L=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let M=C.className,F=typeof M=="string"?M:M?.baseVal||"",N=C.id||void 0,Q=C.getAttribute("role")||void 0,O;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let v=P.textContent?.trim();if(v){O=v.length>50?v.substring(0,50)+"...":v;break}}let k=L;N?k=`${L}#${N}`:F&&(k=`${L}.${F.split(" ").filter(Boolean).join(".")}`);let Pe=window.getComputedStyle(C),Le=["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"],W={};for(let P of Le){let v=Pe.getPropertyValue(P),A=E(P);v&&!y[A]?.includes(v)&&(W[A]=v)}if(L==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let v=C.getAttribute(P);v&&(W[E(P)]=v)}let ee=[];for(let P of Array.from(C.children)){let v=window.getComputedStyle(P);if(v.display==="none"||v.visibility==="hidden")continue;let A=T(P,I+1);A&&ee.push(A)}return{selector:k,tagName:L,className:F,id:N,role:Q,textContent:O,styles:W,children:ee}}return{computedStyles:x,domTree:b?T(b,0):null}}),S=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${S}`,computedStyles:d.computedStyles,domTree:d.domTree}))}finally{await a.close(),await w.close()}}catch(u){l.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(s,o)=>{if(s.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 h=[];for await(let S of s)h.push(typeof S=="string"?Buffer.from(S):S);let p=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:m,storyId:g}=p;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${s.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${g||"unknown"}`);let a=await de(c,m||[],w,{storyId:g});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let d=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${d}`}))}catch(u){l.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{K().catch(()=>{})});let r=s=>{K().catch(()=>{}).finally(()=>{process.kill(process.pid,s)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var R={},bt=()=>{if(typeof R<"u"&&R.url){let e=(0,Z.fileURLToPath)(R.url),n=(0,$.dirname)(e);return(0,$.join)(n,"manager.mjs")}return(0,$.join)(__dirname,"manager.mjs")},Ct=()=>{if(typeof R<"u"&&R.url){let e=(0,Z.fileURLToPath)(R.url),n=(0,$.dirname)(e);return(0,$.join)(n,"preview.mjs")}return(0,$.join)(__dirname,"preview.mjs")};function Et(e=[]){return[...e,bt()]}function vt(e=[]){return[...e,Ct()]}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 Be,ae=be(()=>{"use strict";Be=50});import{dirname as he,join as j}from"path";import{fileURLToPath as ye}from"url";import*as ge from"fs/promises";import*as V from"path";import{glob as ce}from"glob";import{existsSync as Ve}from"fs";import{createRequire as je}from"module";var B={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 Ee(){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=`[${B.NAME}]`,l={debug:(...e)=>{Ee()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var Ae=["flex","inline-flex"],De=["grid","inline-grid"],Nt=[...Ae,...De];var A=null,L=null,Q=!1;async function U(){if(Q)return!!A;if(Q=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=je(process.cwd()+"/");try{return A=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return A=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function ze(){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(Ve(n))return n}async function ee(){if(L&&L.connected)return L;let e=ze(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return L=await A.launch(n),l.debug("Headless Chrome launched for screenshots"),L}async function W(e,n){if(!await U())return null;let s=await(await ee()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,g=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(g,100)};setTimeout(g,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let i=await s.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,g=1/0,f=0,S=1/0,a=0,d=!1;function w(x){for(let y of Array.from(x.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden"||E.position==="fixed"||E.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let I=E.backgroundColor,$=I==="rgba(0, 0, 0, 0)"||I==="transparent"||I==="",_=E.borderStyle!=="none"&&E.borderWidth!=="0px",O=E.boxShadow!=="none",M=!$||_||O,R=y.children[0].getBoundingClientRect(),N=R.width>=T.width*.95&&R.height>=T.height*.95;if(!M||N){y.setAttribute("data-uic-drilled",""),w(y);continue}}g=Math.min(g,T.top),f=Math.max(f,T.bottom),S=Math.min(S,T.left),a=Math.max(a,T.right),d=!0}}if(w(p),!d)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:g,bottom:f,left:S,right:a}});await s.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let o=4,u=i?{x:Math.max(0,i.left-o),y:Math.max(0,i.top-o),width:Math.min(i.right-i.left+o*2,800),height:Math.min(i.bottom-i.top+o*2,600)}:void 0,h=await s.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(h)}finally{await s.close()}}async function te(e,n,t,r){if(!await U())return null;let o=await(await ee()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(m=>{let g=document.getElementById("storybook-root");g&&(g.innerHTML=m)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await o.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let g=window.innerWidth;function f(d){let w=d.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<g*.8&&w.height>0)return w;for(let b of Array.from(d.children)){let x=window.getComputedStyle(b);if(x.position==="fixed"||x.position==="absolute"||x.display==="none"||x.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let S=f(m);if(S)return{x:Math.max(0,S.x-8),y:Math.max(0,S.y-8),width:S.width+16,height:S.height+16};let a=m.firstElementChild;if(a){let d=a.getBoundingClientRect();return{x:d.x,y:d.y,width:d.width,height:d.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await o.close()}}async function D(){return U()}async function G(){L&&(await L.close(),L=null)}var X=null,H=null,le=!1;async function Ze(){if(!le){le=!0;try{let e=await Promise.resolve().then(()=>(ae(),se));X=e.validateCodeForFile,H=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var Qe="UICOPILOT/APPLY_FIXES",et="UICOPILOT/FIX_STARTED",tt="UICOPILOT/FIX_COMPLETED",nt="UICOPILOT/FIX_FAILED",ue="UICOPILOT/ALL_FIXES_APPLIED",rt="UICOPILOT/RELOAD_REQUIRED",de="UICOPILOT/WORKSPACE_PATH",ot="UICOPILOT/REQUEST_WORKSPACE_PATH",it="UICOPILOT/DISCOVER_COMPONENT_FILES",pe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function fe(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`],i=[`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 a of s)try{let d=await ce(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});d.length>0&&o.push(...d)}catch{}for(let a of i)try{let d=await ce(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});d.length>0&&u.push(...d)}catch{}let h=[...new Set(o)],p=[...new Set(u)],c=a=>{if(a.length===0)return;let d=a.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(d)return d;let w=a.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=a.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let d=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(d.length===0)return a[0];let w=d.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=d.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${r}/${r}.tsx`));if(b)return b;let x=d.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${r}.tsx`));return x||d[0]},g=c(h),f=m(p),S=[...h,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:g,componentFile:f,totalMatches:S.length}),{cssFile:g,componentFile:f,allMatches:[...new Set(S)]}}var st=100;function at(e){return new Promise(n=>setTimeout(n,e))}async function ct(e,n){if(await Ze(),!X||!H)return l.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=X(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return l.warn(`Code validation failed for ${n}:`),console.warn(H(t)),{valid:!1,error:r}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${n}:`),console.warn(H(t))),l.debug(`Validation passed for ${n}`),{valid:!0}}var me=!1;function lt(e){if(me)return e;me=!0;let n=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",n),e.emit(de,{path:n}),e.on(ot,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",n),e.emit(de,{path:n})}),e.on(it,async t=>{let{componentName:r,storyId:s}=t;l.debug(`Discovering files for component: ${r}`);try{let i=await fe(r,n);e.emit(pe,{componentName:r,storyId:s,...i,workspacePath:n})}catch(i){l.error("File discovery error:",i),e.emit(pe,{componentName:r,storyId:s,error:i.message,allMatches:[]})}}),e.on(Qe,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,i=s||n;s?l.debug(`Using storybookRoot from API: ${s}`):l.debug(`Using process.cwd(): ${n}`),l.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(c){let m=c.targetFileType||"css",g=c.targetFilePath||c.generatedFix?.filePath,f="",S=c.title?.match(/^(\w+)\s/);if(S&&(f=S[1]),!f&&g){let w=g.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${g}`),g||null;if(!o.has(f)){let w=await fe(f,i);o.set(f,w)}let a=o.get(f),d=m==="css"?a.cssFile:a.componentFile;return d?(l.debug(`Discovered ${m} path: ${d} (was: ${g})`),d):(l.debug(`No ${m} file discovered, using provided: ${g}`),g||null)}let h=[];for(let c of r){let{generatedFix:m}=c,g=c.targetFilePath||m?.filePath,f=await u(c)||g;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:g!==f?g:"(same)",codeLength:m?.code?.length||0}),e.emit(et,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let S=await ct(m.code,f);if(!S.valid)throw new Error(`Code validation failed: ${S.error}. Fix was not applied to prevent breaking the file.`);let a=V.isAbsolute(f)?f:V.join(i,f);l.debug(`Writing to absolute path: ${a}`),await ge.writeFile(a,m.code,"utf-8"),await at(st);let d={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(tt,{issueId:c.id,result:d}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),h.push(d)}catch(S){let a=S.message||"Unknown error";e.emit(nt,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),h.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(ue,{results:h,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(rt,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){l.error("Fatal error during fix application:",r),e.emit(ue,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function ut(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(i,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(i,o)=>{try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(i.url||"",`http://${i.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${i.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let g=await W(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(u){l.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(i,o)=>{try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(i.url||"",`http://${i.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${i.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let g=await W(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let S=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await S.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let x=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let E=()=>{clearTimeout(x),y.off("storyRendered",E),setTimeout(b,100)};y.on("storyRendered",E)}else clearTimeout(x),setTimeout(b,300)}catch{clearTimeout(x),b()}}));let d=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),x={};if(b){let C=window.getComputedStyle(b);for(let I=0;I<C.length;I++)x[C[I]]=C.getPropertyValue(C[I])}let y={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(C){return C.replace(/-([a-z])/g,(I,$)=>$.toUpperCase())}function T(C,I){if(I>4)return null;let $=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes($))return null;let _=C.className,O=typeof _=="string"?_:_?.baseVal||"",M=C.id||void 0,q=C.getAttribute("role")||void 0,R;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let v=P.textContent?.trim();if(v){R=v.length>50?v.substring(0,50)+"...":v;break}}let N=$;M?N=`${$}#${M}`:O&&(N=`${$}.${O.split(" ").filter(Boolean).join(".")}`);let we=window.getComputedStyle(C),Se=["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"],z={};for(let P of Se){let v=we.getPropertyValue(P),F=E(P);v&&!y[F]?.includes(v)&&(z[F]=v)}if($==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let v=C.getAttribute(P);v&&(z[E(P)]=v)}let J=[];for(let P of Array.from(C.children)){let v=window.getComputedStyle(P);if(v.display==="none"||v.visibility==="hidden")continue;let F=T(P,I+1);F&&J.push(F)}return{selector:N,tagName:$,className:O,id:M,role:q,textContent:R,styles:z,children:J}}return{computedStyles:x,domTree:b?T(b,0):null}}),w=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,computedStyles:d.computedStyles,domTree:d.domTree}))}finally{await a.close(),await S.close()}}catch(u){l.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(i,o)=>{if(i.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let w of i)h.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:m,storyId:g}=p;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let S=`http://${i.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${g||"unknown"}`);let a=await te(c,m||[],S,{storyId:g});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let d=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${d}`}))}catch(u){l.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{G().catch(()=>{})});let r=i=>{G().catch(()=>{}).finally(()=>{process.kill(process.pid,i)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var dt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),n=he(e);return j(n,"manager.mjs")}return j(__dirname,"manager.mjs")},pt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),n=he(e);return j(n,"preview.mjs")}return j(__dirname,"preview.mjs")};function Fn(e=[]){return[...e,dt()]}function kn(e=[]){return[...e,pt()]}export{lt as experimental_serverChannel,Fn as managerEntries,kn as previewAnnotations,ut as viteFinal};
|
|
1
|
+
var be=Object.defineProperty;var Ce=(e,n)=>()=>(e&&(n=e(e=0)),n);var Ee=(e,n)=>{for(var t in n)be(e,t,{get:n[t],enumerable:!0})};var ae={};Ee(ae,{detectFileType:()=>oe,formatValidationResult:()=>Qe,isValidCode:()=>Ze,validateCode:()=>ie,validateCodeForFile:()=>se});function Ge(e,n={}){let t=n.minLength??We;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 Xe(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 qe(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 Ke(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,s="",i=!1;for(let o=0;o<e.length;o++){let u=e[o],h=e[o-1];if((u==='"'||u==="'"||u==="`")&&h!=="\\"){r?u===s&&(r=!1,i=!1):(r=!0,s=u,u==="`"&&(i=!0));continue}if(!r){if(n[u])t.push(n[u]);else if(Object.values(n).includes(u)&&t.pop()!==u)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${u}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function re(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 u=[{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:h,message:p}of u)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,severity:"error"});return{errors:t,warnings:r}}function Ye(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 i=(e.match(/\{[^}]+\}/g)||[]).length;return i===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"}),i>0&&i<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${i} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Je(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 oe(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 ie(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},s=Ge(e,t);s&&r.errors.push(s);let i=Xe(e);i&&r.errors.push(i);let o=qe(e);o&&r.errors.push(o);let u=Ke(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:h,warnings:p}=Je(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:h,warnings:p}=re(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:h,warnings:p}=Ye(e,t);r.errors.push(...h),r.warnings.push(...p);break}case"ts":case"js":{let{errors:h,warnings:p}=re(e,t);r.errors.push(...h),r.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function se(e,n,t={}){let r=oe(n);return ie(e,r,t)}function Ze(e,n,t={}){return se(e,n,t).valid}function Qe(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 We,ce=Ce(()=>{"use strict";We=50});import{dirname as ye,join as z}from"path";import{fileURLToPath as Se}from"url";import*as he from"fs/promises";import*as V from"path";import{glob as le}from"glob";import{existsSync as je}from"fs";import{createRequire as Be}from"module";var B={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 k=`[${B.NAME}]`,l={debug:(...e)=>{ve()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var He=["flex","inline-flex"],Ve=["grid","inline-grid"],zt=[...He,...Ve];var A=null,_=null,ee=!1;async function U(){if(ee)return!!A;if(ee=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=Be(process.cwd()+"/");try{return A=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return A=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function Ue(){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(je(n))return n}async function te(){if(_&&_.connected)return _;let e=Ue(),n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return _=await A.launch(n),l.debug("Headless Chrome launched for screenshots"),_}async function W(e,n){if(!await U())return null;let s=await(await te()).newPage();try{await s.setCacheEnabled(!1),await s.setViewport({width:n?.width||800,height:n?.height||600,deviceScaleFactor:1}),await s.goto(e,{waitUntil:"networkidle2",timeout:15e3}),await s.evaluate(()=>document.fonts.ready),await s.waitForSelector("#storybook-root > *",{timeout:1e4}),await s.waitForFunction(()=>new Promise(p=>{let c=document.querySelectorAll("style").length,m=0,g=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(g,100)};setTimeout(g,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let i=await s.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,g=1/0,f=0,w=1/0,a=0,d=!1;function S(x){for(let y of Array.from(x.children)){let E=window.getComputedStyle(y);if(E.display==="none"||E.visibility==="hidden"||E.position==="fixed"||E.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),S(y);continue}if(y.children.length===1){let I=E.backgroundColor,L=I==="rgba(0, 0, 0, 0)"||I==="transparent"||I==="",$=E.borderStyle!=="none"&&E.borderWidth!=="0px",R=E.boxShadow!=="none",M=!L||$||R,F=y.children[0].getBoundingClientRect(),N=F.width>=T.width*.95&&F.height>=T.height*.95;if(!M||N){y.setAttribute("data-uic-drilled",""),S(y);continue}}g=Math.min(g,T.top),f=Math.max(f,T.bottom),w=Math.min(w,T.left),a=Math.max(a,T.right),d=!0}}if(S(p),!d)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:g,bottom:f,left:w,right:a}});await s.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let o=4,u=i?{x:Math.max(0,i.left-o),y:Math.max(0,i.top-o),width:Math.min(i.right-i.left+o*2,800),height:Math.min(i.bottom-i.top+o*2,600)}:void 0,h=await s.screenshot({type:"png",omitBackground:!0,...u?{clip:u}:{fullPage:!1}});return Buffer.from(h)}finally{await s.close()}}async function ne(e,n,t,r){if(!await U())return null;let o=await(await te()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let u=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${u}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(m=>{let g=document.getElementById("storybook-root");g&&(g.innerHTML=m)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(m=>setTimeout(m,500));let p=await o.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let g=window.innerWidth;function f(d){let S=d.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<g*.8&&S.height>0)return S;for(let b of Array.from(d.children)){let x=window.getComputedStyle(b);if(x.position==="fixed"||x.position==="absolute"||x.display==="none"||x.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let w=f(m);if(w)return{x:Math.max(0,w.x-8),y:Math.max(0,w.y-8),width:w.width+16,height:w.height+16};let a=m.firstElementChild;if(a){let d=a.getBoundingClientRect();return{x:d.x,y:d.y,width:d.width,height:d.height}}return null});if(!p)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:p});return Buffer.from(c)}finally{await o.close()}}async function D(){return U()}async function G(){_&&(await _.close(),_=null)}var X=null,H=null,ue=!1;async function et(){if(!ue){ue=!0;try{let e=await Promise.resolve().then(()=>(ce(),ae));X=e.validateCodeForFile,H=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var tt="UICOPILOT/APPLY_FIXES",nt="UICOPILOT/FIX_STARTED",rt="UICOPILOT/FIX_COMPLETED",ot="UICOPILOT/FIX_FAILED",de="UICOPILOT/ALL_FIXES_APPLIED",it="UICOPILOT/RELOAD_REQUIRED",pe="UICOPILOT/WORKSPACE_PATH",st="UICOPILOT/REQUEST_WORKSPACE_PATH",at="UICOPILOT/DISCOVER_COMPONENT_FILES",fe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function me(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`],i=[`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 a of s)try{let d=await le(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});d.length>0&&o.push(...d)}catch{}for(let a of i)try{let d=await le(a,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});d.length>0&&u.push(...d)}catch{}let h=[...new Set(o)],p=[...new Set(u)],c=a=>{if(a.length===0)return;let d=a.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(d)return d;let S=a.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(S)return S;let b=a.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||a[0]},m=a=>{if(a.length===0)return;let d=a.filter(y=>!y.includes(".stories.")&&!y.includes(".test."));if(d.length===0)return a[0];let S=d.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(S)return S;let b=d.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${r}/${r}.tsx`));if(b)return b;let x=d.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${r}.tsx`));return x||d[0]},g=c(h),f=m(p),w=[...h,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:g,componentFile:f,totalMatches:w.length}),{cssFile:g,componentFile:f,allMatches:[...new Set(w)]}}var ct=100;function lt(e){return new Promise(n=>setTimeout(n,e))}async function ut(e,n){if(await et(),!X||!H)return l.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=X(e,n);if(!t.valid){let r=t.errors.map(s=>s.message).join("; ");return l.warn(`Code validation failed for ${n}:`),console.warn(H(t)),{valid:!1,error:r}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${n}:`),console.warn(H(t))),l.debug(`Validation passed for ${n}`),{valid:!0}}var ge=!1;function dt(e){if(ge)return e;ge=!0;let n=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",n),e.emit(pe,{path:n}),e.on(st,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",n),e.emit(pe,{path:n})}),e.on(at,async t=>{let{componentName:r,storyId:s}=t;l.debug(`Discovering files for component: ${r}`);try{let i=await me(r,n);e.emit(fe,{componentName:r,storyId:s,...i,workspacePath:n})}catch(i){l.error("File discovery error:",i),e.emit(fe,{componentName:r,storyId:s,error:i.message,allMatches:[]})}}),e.on(tt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:s}=t,i=s||n;s?l.debug(`Using storybookRoot from API: ${s}`):l.debug(`Using process.cwd(): ${n}`),l.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function u(c){let m=c.targetFileType||"css",g=c.targetFilePath||c.generatedFix?.filePath,f="",w=c.title?.match(/^(\w+)\s/);if(w&&(f=w[1]),!f&&g){let S=g.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);S&&(f=S[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${g}`),g||null;if(!o.has(f)){let S=await me(f,i);o.set(f,S)}let a=o.get(f),d=m==="css"?a.cssFile:a.componentFile;return d?(l.debug(`Discovered ${m} path: ${d} (was: ${g})`),d):(l.debug(`No ${m} file discovered, using provided: ${g}`),g||null)}let h=[];for(let c of r){let{generatedFix:m}=c,g=c.targetFilePath||m?.filePath,f=await u(c)||g;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:g!==f?g:"(same)",codeLength:m?.code?.length||0}),e.emit(nt,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let w=await ut(m.code,f);if(!w.valid)throw new Error(`Code validation failed: ${w.error}. Fix was not applied to prevent breaking the file.`);let a=V.isAbsolute(f)?f:V.join(i,f);l.debug(`Writing to absolute path: ${a}`),await he.writeFile(a,m.code,"utf-8"),await lt(ct);let d={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(rt,{issueId:c.id,result:d}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),h.push(d)}catch(w){let a=w.message||"Unknown error";e.emit(ot,{issueId:c.id,error:a}),l.error(`\u2717 Error: ${a}`),h.push({success:!1,issueId:c.id,error:a,timestamp:new Date})}}let p={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(de,{results:h,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(it,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){l.error("Fatal error during fix application:",r),e.emit(de,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function pt(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(i,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(i,o)=>{try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(i.url||"",`http://${i.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${i.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let g=await W(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(u){l.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(i,o)=>{try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(i.url||"",`http://${i.headers.host}`).searchParams.get("storyId");if(!p){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let m=`http://${i.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let g=await W(m,{selector:"#storybook-root > *"});if(!g){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let w=await f.launch({headless:!0,args:["--no-sandbox","--disable-setuid-sandbox"]}),a=await w.newPage();try{await a.setCacheEnabled(!1),await a.setViewport({width:800,height:600}),await a.goto(m,{waitUntil:"networkidle2",timeout:15e3}),await a.evaluate(()=>document.fonts.ready),await a.waitForSelector("#storybook-root > *",{timeout:1e4}),await a.evaluate(()=>new Promise(b=>{let x=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let E=()=>{clearTimeout(x),y.off("storyRendered",E),setTimeout(b,100)};y.on("storyRendered",E)}else clearTimeout(x),setTimeout(b,300)}catch{clearTimeout(x),b()}}));let d=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),x={};if(b){let C=window.getComputedStyle(b);for(let I=0;I<C.length;I++)x[C[I]]=C.getPropertyValue(C[I])}let y={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(C){return C.replace(/-([a-z])/g,(I,L)=>L.toUpperCase())}function T(C,I){if(I>4)return null;let L=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let $=C.className,R=typeof $=="string"?$:$?.baseVal||"",M=C.id||void 0,q=C.getAttribute("role")||void 0,F;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let v=P.textContent?.trim();if(v){F=v.length>50?v.substring(0,50)+"...":v;break}}let N=L;M?N=`${L}#${M}`:R&&(N=`${L}.${R.split(" ").filter(Boolean).join(".")}`);let we=window.getComputedStyle(C),xe=["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"],j={};for(let P of xe){let v=we.getPropertyValue(P),O=E(P);v&&!y[O]?.includes(v)&&(j[O]=v)}if(L==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let v=C.getAttribute(P);v&&(j[E(P)]=v)}let K=[];for(let P of Array.from(C.children)){let v=window.getComputedStyle(P);if(v.display==="none"||v.visibility==="hidden")continue;let O=T(P,I+1);O&&K.push(O)}return{selector:N,tagName:L,className:R,id:M,role:q,textContent:F,styles:j,children:K}}return{computedStyles:x,domTree:b?T(b,0):null}}),S=g.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${S}`,computedStyles:d.computedStyles,domTree:d.domTree}))}finally{await a.close(),await w.close()}}catch(u){l.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(i,o)=>{if(i.method!=="POST"){o.writeHead(405,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"POST required"}));return}try{if(!await D()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let S of i)h.push(typeof S=="string"?Buffer.from(S):S);let p=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:m,storyId:g}=p;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let w=`http://${i.headers.host||"localhost:6006"}`;l.debug(`Taking snapshot screenshot for ${g||"unknown"}`);let a=await ne(c,m||[],w,{storyId:g});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let d=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${d}`}))}catch(u){l.error("Snapshot screenshot error:",u.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:u.message}))}}),t.httpServer?.on("close",()=>{G().catch(()=>{})});let r=i=>{G().catch(()=>{}).finally(()=>{process.kill(process.pid,i)})},s=globalThis;s.__uicopilotShutdownRegistered||(s.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var ft=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Se(import.meta.url),n=ye(e);return z(n,"manager.mjs")}return z(__dirname,"manager.mjs")},mt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=Se(import.meta.url),n=ye(e);return z(n,"preview.mjs")}return z(__dirname,"preview.mjs")};function rr(e=[]){return[...e,ft()]}function or(e=[]){return[...e,mt()]}export{dt as experimental_serverChannel,rr as managerEntries,or as previewAnnotations,pt as viteFinal};
|