@uicopilot/storybook-addon 0.18.3 → 0.20.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/preset.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var Re=Object.create;var D=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var ke=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var De=(e,n)=>()=>(e&&(n=e(e=0)),n);var oe=(e,n)=>{for(var t in n)D(e,t,{get:n[t],enumerable:!0})},ie=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Fe(n))!Ae.call(e,i)&&i!==t&&D(e,i,{get:()=>n[i],enumerable:!(r=Me(n,i))||r.enumerable});return e};var se=(e,n,t)=>(t=e!=null?Re(ke(e)):{},ie(n||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Be=e=>ie(D({},"__esModule",{value:!0}),e);var be={};oe(be,{detectFileType:()=>Se,formatValidationResult:()=>mt,isValidCode:()=>ft,validateCode:()=>we,validateCodeForFile:()=>xe});function at(e,n={}){let t=n.minLength??st;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 ct(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(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 ut(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,i="",a=!1;for(let o=0;o<e.length;o++){let u=e[o],d=e[o-1];if((u==='"'||u==="'"||u==="`")&&d!=="\\"){r?u===i&&(r=!1,a=!1):(r=!0,i=u,u==="`"&&(a=!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 ye(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:d,message:c}of u)d.test(e)&&t.push({code:"TSX_INCOMPLETE",message:c,severity:"error"});return{errors:t,warnings:r}}function dt(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 pt(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 Se(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 we(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},i=at(e,t);i&&r.errors.push(i);let a=ct(e);a&&r.errors.push(a);let o=lt(e);o&&r.errors.push(o);let u=ut(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:d,warnings:c}=pt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"tsx":case"jsx":{let{errors:d,warnings:c}=ye(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"css":case"scss":case"less":{let{errors:d,warnings:c}=dt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"ts":case"js":{let{errors:d,warnings:c}=ye(e,t);r.errors.push(...d),r.warnings.push(...c.filter(s=>!s.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function xe(e,n,t={}){let r=Se(n);return we(e,r,t)}function ft(e,n,t={}){return xe(e,n,t).valid}function mt(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 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 Ye=Object.create;var V=Object.defineProperty;var Je=Object.getOwnPropertyDescriptor;var Ze=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,et=Object.prototype.hasOwnProperty;var tt=(e,n)=>()=>(e&&(n=e(e=0)),n);var fe=(e,n)=>{for(var t in n)V(e,t,{get:n[t],enumerable:!0})},pe=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Ze(n))!et.call(e,o)&&o!==t&&V(e,o,{get:()=>n[o],enumerable:!(r=Je(n,o))||r.enumerable});return e};var me=(e,n,t)=>(t=e!=null?Ye(Qe(e)):{},pe(n||!e||!e.__esModule?V(t,"default",{value:e,enumerable:!0}):t,e)),nt=e=>pe(V({},"__esModule",{value:!0}),e);var Ae={};fe(Ae,{detectFileType:()=>ke,formatValidationResult:()=>qt,isValidCode:()=>Kt,validateCode:()=>Fe,validateCodeForFile:()=>Le});function jt(e,n={}){let t=n.minLength??Vt;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 zt(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 Ut(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 Wt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,o="",l=!1;for(let i=0;i<e.length;i++){let d=e[i],h=e[i-1];if((d==='"'||d==="'"||d==="`")&&h!=="\\"){r?d===o&&(r=!1,l=!1):(r=!0,o=d,d==="`"&&(l=!0));continue}if(!r){if(n[d])t.push(n[d]);else if(Object.values(n).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function Ne(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 d=[{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:s}of d)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:s,severity:"error"});return{errors:t,warnings:r}}function Xt(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 l=(e.match(/\{[^}]+\}/g)||[]).length;return l===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"}),l>0&&l<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${l} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Gt(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 ke(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 Fe(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},o=jt(e,t);o&&r.errors.push(o);let l=zt(e);l&&r.errors.push(l);let i=Ut(e);i&&r.errors.push(i);let d=Wt(e);switch(d&&(t.strict?r.errors.push({...d,severity:"error"}):r.warnings.push(d)),n){case"stories":{let{errors:h,warnings:s}=Gt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"tsx":case"jsx":{let{errors:h,warnings:s}=Ne(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"css":case"scss":case"less":{let{errors:h,warnings:s}=Xt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"ts":case"js":{let{errors:h,warnings:s}=Ne(e,t);r.errors.push(...h),r.warnings.push(...s.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Le(e,n,t={}){let r=ke(n);return Fe(e,r,t)}function Kt(e,n,t={}){return Le(e,n,t).valid}function qt(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 Vt,De=tt(()=>{"use strict";Vt=50});var fn={};fe(fn,{experimental_serverChannel:()=>Ge,managerEntries:()=>un,previewAnnotations:()=>dn,viteFinal:()=>Ke});module.exports=nt(fn);var N=require("path"),de=require("url");var Xe=me(require("fs/promises")),K=me(require("path")),le=require("glob");var Y=require("fs"),J=require("module");var q={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 rt(){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 j=`[${q.NAME}]`,y={debug:(...e)=>{rt()&&console.log(j,...e)},info:(...e)=>{console.log(j,...e)},warn:(...e)=>{console.warn(j,...e)},error:(...e)=>{console.error(j,...e)}};var wt=["flex","inline-flex"],bt=["grid","inline-grid"],Bn=[...wt,...bt];function z(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let o=e.getBoundingClientRect(),l=u=>{let a=r.getComputedStyle(u);if(a.position==="fixed"||a.display==="none"||a.visibility==="hidden")return!0;let p=u.getBoundingClientRect();return p.width===0||p.height===0||u.children.length===0&&!(u.textContent??"").trim()},i=u=>{if(o.width===0||o.height===0)return!1;let a=u.getBoundingClientRect();return a.width>=o.width*.9&&a.height>=o.height*.9},d=[],h=u=>{for(let a of Array.from(u.children))a.hasAttribute("data-uicopilot-instance")?d.push(a):h(a)};if(h(e),d.length>1){let u=g=>{let m=[];for(let f=g;f&&f!==e;f=f.parentElement)m.unshift(f);return m},a=d.map(u),p=e;for(let g=0;;g+=1){let m=a[0][g];if(!m||!a.every(f=>f[g]===m))break;p=m}if(p!==e)return p}let s=e;for(let u=0;u<6;u+=1){if(s!==e&&s.hasAttribute("data-uicopilot-instance"))return s;let a=Array.from(s.children).filter(p=>!l(p));if(a.length!==1||s!==e&&!i(s))break;s=a[0]}if(s!==e&&i(s)){let u=Array.from(s.children).filter(a=>!l(a));if(u.length>1&&c(u))return u[0].setAttribute("data-uicopilot-instances",String(u.length)),u[0]}if(s===e)return e.firstElementChild??e;return s;function c(u){let a=g=>{let m=g.className,f=typeof m=="string"?m:"";return`${g.tagName}.${f.split(" ")[0]??""}`},p=a(u[0]);return u.every(g=>a(g)===p)}}var vt={},Ce=z.toString(),F=null,$=null,Ee=!1;async function Q(){if(Ee)return!!F;if(Ee=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return y.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,J.createRequire)(process.cwd()+"/");try{return F=e("puppeteer"),y.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return F=e("puppeteer-core"),y.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return F=(0,J.createRequire)(vt.url)("puppeteer-core"),y.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return y.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function Tt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if((0,Y.existsSync)(e))return e;y.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,Y.existsSync)(o))return o}async function Te(){return ee()}var U=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"}},Z=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 ee(){if($&&$.connected)return $;let e=Tt();if(!e&&!It())throw new U;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{$=await F.launch(n)}catch(t){throw e?new Z(e,t):new U}return y.debug("Headless Chrome launched for screenshots"),$}function It(){try{return typeof F?.executablePath=="function"}catch{return!1}}async function te(e,n){if(!await Q())return null;let o=await(await ee()).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(s=>{let c=document.querySelectorAll("style").length,u=0,a=()=>{let p=document.querySelectorAll("style").length;if(p===c){if(u++,u>=3){s(!0);return}}else u=0,c=p;setTimeout(a,100)};setTimeout(a,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(s=>setTimeout(s,500));let l=await o.evaluate(s=>{let c=document.querySelector("#storybook-root");if(!c)return null;let u=window.innerHeight,a=window.innerWidth,p=E=>E.setAttribute("data-uic-drilled",""),g=()=>{let E=document.createElement("style");E.id="uic-drilled-bg-reset",E.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(E),document.body.offsetHeight};try{let T=new Function("return ("+s+")")()(c),C=T?.getBoundingClientRect(),_=!!C&&C.width>=a*.9&&C.height>=u*.9;if(T&&T!==c&&C&&C.width>0&&C.height>0&&!_){for(let P=T.parentElement;P&&P!==c;P=P.parentElement)p(P);return g(),{top:C.top,bottom:C.bottom,left:C.left,right:C.right}}}catch{}let m=1/0,f=0,w=1/0,b=0,x=!1;function S(E){for(let T of Array.from(E.children)){let C=window.getComputedStyle(T);if(C.display==="none"||C.visibility==="hidden"||C.position==="fixed"||C.position==="absolute")continue;let _=T.getBoundingClientRect();if(_.height<=0||_.width<=0)continue;if((_.width>=a*.9||_.height>=u*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),S(T);continue}if(T.children.length===1){let D=C.backgroundColor,R=D==="rgba(0, 0, 0, 0)"||D==="transparent"||D==="",H=C.borderStyle!=="none"&&C.borderWidth!=="0px",v=C.boxShadow!=="none",I=!R||H||v,B=T.children[0].getBoundingClientRect(),qe=B.width>=_.width*.95&&B.height>=_.height*.95;if(!I||qe){T.setAttribute("data-uic-drilled",""),S(T);continue}}m=Math.min(m,_.top),f=Math.max(f,_.bottom),w=Math.min(w,_.left),b=Math.max(b,_.right),x=!0}}return S(c),x?(g(),{top:m,bottom:f,left:w,right:b}):null},Ce);await o.evaluate(()=>new Promise(s=>requestAnimationFrame(()=>s())));let i=4,d=l?{x:Math.max(0,l.left-i),y:Math.max(0,l.top-i),width:Math.min(l.right-l.left+i*2,800),height:Math.min(l.bottom-l.top+i*2,600)}:void 0,h=await o.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(h)}finally{await o.close()}}async function Ie(e,n,t,r){if(!await Q())return null;let i=await(await ee()).newPage();try{await i.setCacheEnabled(!1),await i.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let d=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await i.goto(h,{waitUntil:"load",timeout:15e3}),await i.waitForSelector("#storybook-root > *",{timeout:1e4}),await i.evaluate(u=>{let a=document.getElementById("storybook-root");a&&(a.innerHTML=u)},e),await i.evaluate(()=>document.fonts.ready),await new Promise(u=>setTimeout(u,500));let s=await i.evaluate(u=>{let a=document.querySelector("#storybook-root");if(!a)return null;let p=window.innerWidth,g=window.innerHeight,m=8;try{let S=new Function("return ("+u+")")()(a),E=S?.getBoundingClientRect(),T=!!E&&E.width>=p*.9&&E.height>=g*.9;if(S&&S!==a&&E&&E.width>0&&E.height>0&&!T)return{x:Math.max(0,E.x-m),y:Math.max(0,E.y-m),width:E.width+m*2,height:E.height+m*2}}catch{}function f(x){let S=x.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<p*.8&&S.height>0)return S;for(let E of Array.from(x.children)){let T=window.getComputedStyle(E);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let C=f(E);if(C)return C}return null}let w=f(a);if(w)return{x:Math.max(0,w.x-m),y:Math.max(0,w.y-m),width:w.width+m*2,height:w.height+m*2};let b=a.firstElementChild;if(b){let x=b.getBoundingClientRect();return{x:x.x,y:x.y,width:x.width,height:x.height}}return null},Ce);if(!s)throw new Error("Could not determine component bounds from snapshot");let c=await i.screenshot({type:"png",clip:s});return Buffer.from(c)}finally{await i.close()}}async function W(){return Q()}async function ne(){$&&(await $.close(),$=null)}function ve(e,n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();return{x:Math.round(t.left-r.left),y:Math.round(t.top-r.top),w:Math.round(t.width),h:Math.round(t.height)}}function _e(e,n){let t=s=>{let c=Object.keys(s).find(u=>u.startsWith("__reactFiber$"));return c?s[c]:void 0},r=s=>!!s&&s.nodeType===1&&typeof s.getBoundingClientRect=="function",o=s=>s.elementType===e||s.type===e,l=s=>{for(let c=s?.child??null;c;c=c.sibling){if(c.tag===5&&r(c.stateNode)){let a=c.stateNode.getBoundingClientRect();if(a.width>0&&a.height>0)return c.stateNode}let u=l(c);if(u)return u}},i=s=>{for(let c=s.return;c;c=c.return)if(o(c))return!0;return!1},d=new Set,h=[];for(let s of n)for(let c of[s,...Array.from(s.querySelectorAll("*"))])for(let u=t(c)??null;u;u=u.return){if(!o(u)||d.has(u)||(d.add(u),i(u)))continue;let a=l(u);a&&h.push(a)}return h}async function Pe(e,n,t,r){let o=e.document;o.querySelectorAll("[data-uicopilot-instance]").forEach(a=>a.removeAttribute("data-uicopilot-instance")),o.querySelectorAll("[data-uicopilot-instance-count]").forEach(a=>a.removeAttribute("data-uicopilot-instance-count"));let l=e.__STORYBOOK_PREVIEW__;if(!l?.storyStoreValue)return 0;let i;try{i=await l.storyStoreValue.loadStory({storyId:n})}catch{return 0}let d=r??o.getElementById("storybook-root")??o.getElementById("root");if(!d||!i.component)return 0;let h=r?[]:Array.from(o.body.children).filter(a=>a!==d&&!a.contains(d)&&a.tagName!=="SCRIPT"),s=[d,...h],c=t(i.component,s);if(c.length===0&&i.subcomponents){let a=Object.values(i.subcomponents).flatMap(p=>p?t(p,s):[]);c=Array.from(new Set(a)).filter(p=>!a.some(g=>g!==p&&g.contains(p))).sort((p,g)=>p.compareDocumentPosition(g)&4?-1:1)}return c.forEach((a,p)=>a.setAttribute("data-uicopilot-instance",String(p+1))),[d,...h].some(a=>[a,...Array.from(a.querySelectorAll("*"))].some(p=>Object.keys(p).some(g=>g.startsWith("__reactFiber$"))))&&d.setAttribute("data-uicopilot-instance-count",String(c.length)),c.length}var _t=ve.toString(),Pt=_e.toString(),Ot=Pe.toString(),Mt="data-uicopilot-instance";async function re(e,n,t){return t&&await e.evaluate(async(o,l,i)=>{let d=new Function("return ("+o+")")(),h=new Function("return ("+l+")")();return d(window,i,h)},Ot,Pt,t),await e.evaluate((o,l,i)=>{let d=new Function("return ("+l+")")(),h=document.getElementById("storybook-root")||document.getElementById("root"),s=null;if(h)try{s=new Function("return ("+o+")")()(h)}catch{s=h.firstElementChild}let c={};if(s){let f=window.getComputedStyle(s);for(let w=0;w<f.length;w++)c[f[w]]=f.getPropertyValue(f[w])}let u={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function a(f){return f.replace(/-([a-z])/g,(w,b)=>b.toUpperCase())}function p(f,w){if(w>4)return null;let b=f.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(b))return null;let x=f.className,S=typeof x=="string"?x:x?.baseVal||"",E=f.id||void 0,T=f.getAttribute("role")||void 0,C;for(let v of Array.from(f.childNodes))if(v.nodeType===3){let I=v.textContent?.trim();if(I){C=I.length>50?I.substring(0,50)+"...":I;break}}let _=b;E?_=`${b}#${E}`:S&&(_=`${b}.${S.split(" ").filter(Boolean).join(".")}`);let P=window.getComputedStyle(f),D=["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"],R={};for(let v of D){let I=P.getPropertyValue(v),M=a(v);I&&!u[M]?.includes(I)&&(R[M]=I)}if(!R.border){let v=["top","right","bottom","left"].filter(I=>parseFloat(P.getPropertyValue(`border-${I}-width`))>0&&P.getPropertyValue(`border-${I}-style`)!=="none");if(v.length>0){let I=v.reduce((M,B)=>parseFloat(P.getPropertyValue(`border-${B}-width`))>parseFloat(P.getPropertyValue(`border-${M}-width`))?B:M);R.border=`${P.getPropertyValue(`border-${I}-width`)} ${P.getPropertyValue(`border-${I}-style`)} ${P.getPropertyValue(`border-${I}-color`)}`,R.borderSides=v.join(" ")}}if(b==="svg"||f.closest("svg"))for(let v of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=f.getAttribute(v);I&&(R[a(v)]=I)}let H=[];for(let v of Array.from(f.children)){let I=window.getComputedStyle(v);if(I.display==="none"||I.visibility==="hidden")continue;let M=p(v,w+1);M&&H.push(M)}return{selector:_,tagName:b,className:S,id:E,role:T,textContent:C,rect:s?d(f,s):void 0,instance:Number(f.getAttribute(i))>0?Number(f.getAttribute(i)):void 0,styles:R,children:H}}let g=s?p(s,0):null,m=document.querySelector("["+i+"-count]");return g&&m&&(g.instanceCount=Number(m.getAttribute(i+"-count"))),{computedStyles:c,domTree:g}},n,_t,Mt)}async function X(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let o=setTimeout(r,t);try{let l=window.__STORYBOOK_ADDONS_CHANNEL__;if(l){let i=()=>{clearTimeout(o),l.off("storyRendered",i),setTimeout(r,100)};l.on("storyRendered",i)}else clearTimeout(o),setTimeout(r,300)}catch{clearTimeout(o),r()}}),n)}async function Oe(e,n,t=15e3){return await e.evaluate((r,o)=>{let l=window,i=l.__STORYBOOK_PREVIEW__,d=l.__STORYBOOK_ADDONS_CHANNEL__;return!i||!d||typeof i.renderSelection!="function"||typeof i.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(h=>{let s=!1,c=g=>{if(!s){s=!0,clearTimeout(p);try{d.off("storyRendered",u),d.off("storyErrored",a),d.off("storyMissing",a)}catch{}h(g)}},u=g=>{let m=typeof g=="string"?g:g?.storyId||g?.id;(!m||m===r)&&setTimeout(()=>c("ok"),100)},a=()=>c("errored"),p=setTimeout(()=>c("timeout"),o);d.on("storyRendered",u),d.on("storyErrored",a),d.on("storyMissing",a);try{i.selectionStore.setSelection({storyId:r,viewMode:"story"}),i.renderSelection()}catch{c("nav-failed")}})},n,t)}async function Me(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function oe(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(o=>{let l=r.getAttribute(o)??"";return o!=="class"?`${o}=${l}`:`class=${l.split(/\s+/).filter(d=>d&&!d.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 Rt=6,$t=15,Nt=9e4,kt=2e4;function Ft(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:$t}function Lt(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var O=[],se=[];function At(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function ae(){let e=se.shift();e&&e()}function Re(){let e=Date.now(),n=O.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>Nt);if(n.length===0){O.length===0&&ie();return}O=O.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});O.length===0&&ie()}var L=null;function Dt(){L||(L=setInterval(Re,3e4),L.unref?.())}function ie(){L&&(clearInterval(L),L=null)}async function Bt(e,n,t){let r=await e.newPage();try{return await r.setViewport({width:800,height:600,deviceScaleFactor:1}),await r.goto(At(n,t),{waitUntil:"load",timeout:kt}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await X(r),r}catch(o){throw await r.close().catch(()=>{}),o}}async function Ht(e,n,t){for(;;){Re();let r=O.find(o=>o.baseUrl===n&&!o.busy&&o.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(O.length<Rt){let o={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};O.push(o),Dt();try{return o.page=await Bt(e,n,t),o.baseline=await oe(o.page),{entry:o,fresh:!0}}catch{return O=O.filter(l=>l!==o),ae(),null}}await new Promise(o=>se.push(o))}}function k(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Ft())&&(O=O.filter(t=>t!==e),e.page?.close().catch(()=>{})),ae()}async function $e(e,n,t,r){if(!Lt())return{ok:!1,reason:"disabled"};let o=await Ht(e,n,t);if(!o)return{ok:!1,reason:"boot-failed"};let{entry:l,fresh:i}=o,d=l.page;try{if(!i){let s=await Oe(d,t);if(s!=="ok")return k(l,!0),{ok:!1,reason:`switch-${s}`};let c=await Me(d);if(c&&c!==t)return k(l,!0),{ok:!1,reason:"selection-mismatch"};if(l.baseline===null)return k(l,!0),{ok:!1,reason:"baseline-unavailable"};let u=await oe(d);if(u===null)return k(l,!0),{ok:!1,reason:"document-unreadable"};if(u!==l.baseline)return k(l,!0),{ok:!1,reason:"document-drift"};await d.evaluate(()=>document.fonts.ready)}let h=await r(d);return k(l,!1),{ok:!0,value:h,booted:i}}catch(h){return k(l,!0),{ok:!1,reason:`error:${h.message}`}}}async function ce(){ie();let e=O;for(O=[];se.length;)ae();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Be=z.toString(),ue=null,G=null,He=!1;async function Yt(){if(!He){He=!0;try{let e=await Promise.resolve().then(()=>(De(),Ae));ue=e.validateCodeForFile,G=e.formatValidationResult,y.debug("Code validator loaded - fix validation enabled")}catch{y.debug("Code validator not available - skipping fix validation")}}}var Jt="UICOPILOT/APPLY_FIXES",Zt="UICOPILOT/FIX_STARTED",Qt="UICOPILOT/FIX_COMPLETED",en="UICOPILOT/FIX_FAILED",Ve="UICOPILOT/ALL_FIXES_APPLIED",tn="UICOPILOT/RELOAD_REQUIRED",je="UICOPILOT/WORKSPACE_PATH",nn="UICOPILOT/REQUEST_WORKSPACE_PATH",rn="UICOPILOT/DISCOVER_COMPONENT_FILES",ze="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function Ue(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`],l=[`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=[],d=[];for(let m of o)try{let f=await(0,le.glob)(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});f.length>0&&i.push(...f)}catch{}for(let m of l)try{let f=await(0,le.glob)(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});f.length>0&&d.push(...f)}catch{}let h=[...new Set(i)],s=[...new Set(d)],c=m=>{if(m.length===0)return;let f=m.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(f)return f;let w=m.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=m.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||m[0]},u=m=>{if(m.length===0)return;let f=m.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(f.length===0)return m[0];let w=f.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let b=f.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(b)return b;let x=f.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return x||f[0]},a=c(h),p=u(s),g=[...h,...s];return y.debug(`Discovered files for "${e}":`,{cssFile:a,componentFile:p,totalMatches:g.length}),{cssFile:a,componentFile:p,allMatches:[...new Set(g)]}}var on=100;function sn(e){return new Promise(n=>setTimeout(n,e))}async function an(e,n){if(await Yt(),!ue||!G)return y.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=ue(e,n);if(!t.valid){let r=t.errors.map(o=>o.message).join("; ");return y.warn(`Code validation failed for ${n}:`),console.warn(G(t)),{valid:!1,error:r}}return t.warnings.length>0&&(y.warn(`Code validation warnings for ${n}:`),console.warn(G(t))),y.debug(`Validation passed for ${n}`),{valid:!0}}var We=!1;function Ge(e){if(We)return e;We=!0;let n=process.cwd();return y.debug("Apply fixes initialized"),y.debug("Workspace:",n),e.emit(je,{path:n}),e.on(nn,()=>{y.debug("Workspace path requested by browser"),y.debug("Emitting workspace path response:",n),e.emit(je,{path:n})}),e.on(rn,async t=>{let{componentName:r,storyId:o}=t;y.debug(`Discovering files for component: ${r}`);try{let l=await Ue(r,n);e.emit(ze,{componentName:r,storyId:o,...l,workspacePath:n})}catch(l){y.error("File discovery error:",l),e.emit(ze,{componentName:r,storyId:o,error:l.message,allMatches:[]})}}),e.on(Jt,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:o}=t,l=o||n;o?y.debug(`Using storybookRoot from API: ${o}`):y.debug(`Using process.cwd(): ${n}`),y.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let i=new Map;async function d(c){let u=c.targetFileType||"css",a=c.targetFilePath||c.generatedFix?.filePath,p="",g=c.title?.match(/^(\w+)\s/);if(g&&(p=g[1]),!p&&a){let w=a.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(p=w[1])}if(!p)return y.debug(`Could not extract component name, using provided path: ${a}`),a||null;if(!i.has(p)){let w=await Ue(p,l);i.set(p,w)}let m=i.get(p),f=u==="css"?m.cssFile:m.componentFile;return f?(y.debug(`Discovered ${u} path: ${f} (was: ${a})`),f):(y.debug(`No ${u} file discovered, using provided: ${a}`),a||null)}let h=[];for(let c of r){let{generatedFix:u}=c,a=c.targetFilePath||u?.filePath,p=await d(c)||a;y.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:p,providedPath:a!==p?a:"(same)",codeLength:u?.code?.length||0}),e.emit(Zt,{issueId:c.id});try{if(!u||!u.code||!p)throw new Error("Missing AI-generated fix data (code or filePath)");y.debug("Code to write (first 200 chars):",u.code.substring(0,200)),y.debug(`Code length: ${u.code.length} chars`);let g=await an(u.code,p);if(!g.valid)throw new Error(`Code validation failed: ${g.error}. Fix was not applied to prevent breaking the file.`);let m=K.isAbsolute(p)?p:K.join(l,p);y.debug(`Writing to absolute path: ${m}`),await Xe.writeFile(m,u.code,"utf-8"),await sn(on);let f={success:!0,issueId:c.id,filePath:p,timestamp:new Date};e.emit(Qt,{issueId:c.id,result:f}),y.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${p}`),h.push(f)}catch(g){let m=g.message||"Unknown error";e.emit(en,{issueId:c.id,error:m}),y.error(`\u2717 Error: ${m}`),h.push({success:!1,issueId:c.id,error:m,timestamp:new Date})}}let s={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(Ve,{results:h,summary:s}),y.debug(`Completed: ${s.succeeded}/${s.total} fixes applied`),s.succeeded>0&&e.emit(tn,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){y.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 Ke(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(l,i)=>{i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(l,i)=>{try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let s=new URL(l.url||"",`http://${l.headers.host}`).searchParams.get("storyId");if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let u=`http://${l.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Taking screenshot: ${s}`);let a=await te(u,{selector:"#storybook-root > *"});if(!a){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let p=a.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${p}`}))}catch(d){y.error("Screenshot error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(l,i)=>{try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=new URL(l.url||"",`http://${l.headers.host}`),s=h.searchParams.get("storyId");if(!s){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing storyId parameter"}));return}let c=h.searchParams.get("domOnly")==="1",u=l.headers.host||"localhost:6006",a=`http://${u}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Full capture${c?" (domOnly)":""}: ${s}`);let p=null;if(!c&&(p=await te(a,{selector:"#storybook-root > *"}),!p)){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=await Te(),m=h.searchParams.get("warm")==="0",f=null,w="cold";if(!m){let b=`http://${u}`,x=await $e(g,b,s,S=>re(S,Be,s));x.ok?(f=x.value,w=x.booted?"warm-boot":"warm"):y.debug(`Warm capture unavailable (${x.reason}): ${s}`)}if(!f){let b=await g.newPage();try{await b.setCacheEnabled(!1),await b.setViewport({width:800,height:600}),await b.goto(a,{waitUntil:"load",timeout:15e3}),await b.evaluate(()=>document.fonts.ready),await b.waitForSelector("#storybook-root > *",{timeout:1e4}),await X(b),f=await re(b,Be,s)}finally{await b.close()}}y.debug(`Capture path for ${s}: ${w}`),i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:p?`data:image/png;base64,${p.toString("base64")}`:void 0,computedStyles:f.computedStyles,domTree:f.domTree}))}catch(d){y.error("Capture error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(l,i)=>{if(l.method!=="POST"){i.writeHead(405,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"POST required"}));return}try{if(!await W()){i.writeHead(501,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=[];for await(let w of l)h.push(typeof w=="string"?Buffer.from(w):w);let s=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:u,storyId:a}=s;if(!c){i.writeHead(400,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Missing html in body"}));return}let g=`http://${l.headers.host||"localhost:6006"}`;y.debug(`Taking snapshot screenshot for ${a||"unknown"}`);let m=await Ie(c,u||[],g,{storyId:a});if(!m){i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let f=m.toString("base64");i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){y.error("Snapshot screenshot error:",d.message),i.writeHead(500,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{ce().catch(()=>{}).finally(()=>ne().catch(()=>{}))});let r=l=>{ce().catch(()=>{}).then(()=>ne()).catch(()=>{}).finally(()=>{process.kill(process.pid,l)})},o=globalThis;o.__uicopilotShutdownRegistered||(o.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var A={},cn=()=>{if(typeof A<"u"&&A.url){let e=(0,de.fileURLToPath)(A.url),n=(0,N.dirname)(e);return(0,N.join)(n,"manager.mjs")}return(0,N.join)(__dirname,"manager.mjs")},ln=()=>{if(typeof A<"u"&&A.url){let e=(0,de.fileURLToPath)(A.url),n=(0,N.dirname)(e);return(0,N.join)(n,"preview.mjs")}return(0,N.join)(__dirname,"preview.mjs")};function un(e=[]){return[...e,cn()]}function dn(e=[]){return[...e,ln()]}0&&(module.exports={experimental_serverChannel,managerEntries,previewAnnotations,viteFinal});
package/dist/preset.mjs CHANGED
@@ -1,3 +1,3 @@
1
- var Ie=Object.defineProperty;var Te=(e,n)=>()=>(e&&(n=e(e=0)),n);var Pe=(e,n)=>{for(var t in n)Ie(e,t,{get:n[t],enumerable:!0})};var pe={};Pe(pe,{detectFileType:()=>le,formatValidationResult:()=>ot,isValidCode:()=>rt,validateCode:()=>ue,validateCodeForFile:()=>de});function Je(e,n={}){let t=n.minLength??Ye;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 Ze(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 et(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,s="",a=!1;for(let o=0;o<e.length;o++){let u=e[o],d=e[o-1];if((u==='"'||u==="'"||u==="`")&&d!=="\\"){r?u===s&&(r=!1,a=!1):(r=!0,s=u,u==="`"&&(a=!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 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 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:d,message:c}of u)d.test(e)&&t.push({code:"TSX_INCOMPLETE",message:c,severity:"error"});return{errors:t,warnings:r}}function tt(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 le(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 ue(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},s=Je(e,t);s&&r.errors.push(s);let a=Ze(e);a&&r.errors.push(a);let o=Qe(e);o&&r.errors.push(o);let u=et(e);switch(u&&(t.strict?r.errors.push({...u,severity:"error"}):r.warnings.push(u)),n){case"stories":{let{errors:d,warnings:c}=nt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"tsx":case"jsx":{let{errors:d,warnings:c}=ce(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"css":case"scss":case"less":{let{errors:d,warnings:c}=tt(e,t);r.errors.push(...d),r.warnings.push(...c);break}case"ts":case"js":{let{errors:d,warnings:c}=ce(e,t);r.errors.push(...d),r.warnings.push(...c.filter(i=>!i.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function de(e,n,t={}){let r=le(n);return ue(e,r,t)}function rt(e,n,t={}){return de(e,n,t).valid}function ot(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 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 Ue=Object.defineProperty;var We=(e,n)=>()=>(e&&(n=e(e=0)),n);var Xe=(e,n)=>{for(var t in n)Ue(e,t,{get:n[t],enumerable:!0})};var Me={};Xe(Me,{detectFileType:()=>_e,formatValidationResult:()=>Dt,isValidCode:()=>At,validateCode:()=>Pe,validateCodeForFile:()=>Oe});function Rt(e,n={}){let t=n.minLength??Mt;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 $t(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 Nt(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 kt(e){let n={"{":"}","[":"]","(":")"},t=[],r=!1,i="",l=!1;for(let o=0;o<e.length;o++){let d=e[o],h=e[o-1];if((d==='"'||d==="'"||d==="`")&&h!=="\\"){r?d===i&&(r=!1,l=!1):(r=!0,i=d,d==="`"&&(l=!0));continue}if(!r){if(n[d])t.push(n[d]);else if(Object.values(n).includes(d)&&t.pop()!==d)return{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets detected. Found unexpected '${d}'.`,severity:"warning"}}}return t.length>0?{code:"UNBALANCED_BRACES",message:`Unbalanced braces/brackets. Missing: ${t.reverse().join("")}`,severity:"warning"}:null}function ve(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 d=[{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:s}of d)h.test(e)&&t.push({code:"TSX_INCOMPLETE",message:s,severity:"error"});return{errors:t,warnings:r}}function Ft(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 l=(e.match(/\{[^}]+\}/g)||[]).length;return l===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"}),l>0&&l<3&&!n.allowPartial&&r.push({code:"CSS_FEW_RULES",message:`Only ${l} CSS rule(s) found. Might be incomplete.`,severity:"warning"}),{errors:t,warnings:r}}function Lt(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 _e(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 Pe(e,n,t={}){let r={valid:!0,fileType:n,errors:[],warnings:[]},i=Rt(e,t);i&&r.errors.push(i);let l=$t(e);l&&r.errors.push(l);let o=Nt(e);o&&r.errors.push(o);let d=kt(e);switch(d&&(t.strict?r.errors.push({...d,severity:"error"}):r.warnings.push(d)),n){case"stories":{let{errors:h,warnings:s}=Lt(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"tsx":case"jsx":{let{errors:h,warnings:s}=ve(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"css":case"scss":case"less":{let{errors:h,warnings:s}=Ft(e,t);r.errors.push(...h),r.warnings.push(...s);break}case"ts":case"js":{let{errors:h,warnings:s}=ve(e,t);r.errors.push(...h),r.warnings.push(...s.filter(c=>!c.code.includes("JSX")));break}default:break}return r.valid=r.errors.length===0,r}function Oe(e,n,t={}){let r=_e(n);return Pe(e,r,t)}function At(e,n,t={}){return Oe(e,n,t).valid}function Dt(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 Mt,Re=We(()=>{"use strict";Mt=50});import{dirname as Ve,join as X}from"path";import{fileURLToPath as je}from"url";import*as He from"fs/promises";import*as W from"path";import{glob as $e}from"glob";import{existsSync as pe}from"fs";import{createRequire as me}from"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 Ge(){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=`[${G.NAME}]`,y={debug:(...e)=>{Ge()&&console.log(B,...e)},info:(...e)=>{console.log(B,...e)},warn:(...e)=>{console.warn(B,...e)},error:(...e)=>{console.error(B,...e)}};var ct=["flex","inline-flex"],lt=["grid","inline-grid"],_n=[...ct,...lt];function H(e){let r=e.ownerDocument?.defaultView;if(!r)return e.firstElementChild??e;let i=e.getBoundingClientRect(),l=u=>{let a=r.getComputedStyle(u);if(a.position==="fixed"||a.display==="none"||a.visibility==="hidden")return!0;let p=u.getBoundingClientRect();return p.width===0||p.height===0||u.children.length===0&&!(u.textContent??"").trim()},o=u=>{if(i.width===0||i.height===0)return!1;let a=u.getBoundingClientRect();return a.width>=i.width*.9&&a.height>=i.height*.9},d=[],h=u=>{for(let a of Array.from(u.children))a.hasAttribute("data-uicopilot-instance")?d.push(a):h(a)};if(h(e),d.length>1){let u=g=>{let m=[];for(let f=g;f&&f!==e;f=f.parentElement)m.unshift(f);return m},a=d.map(u),p=e;for(let g=0;;g+=1){let m=a[0][g];if(!m||!a.every(f=>f[g]===m))break;p=m}if(p!==e)return p}let s=e;for(let u=0;u<6;u+=1){if(s!==e&&s.hasAttribute("data-uicopilot-instance"))return s;let a=Array.from(s.children).filter(p=>!l(p));if(a.length!==1||s!==e&&!o(s))break;s=a[0]}if(s!==e&&o(s)){let u=Array.from(s.children).filter(a=>!l(a));if(u.length>1&&c(u))return u[0].setAttribute("data-uicopilot-instances",String(u.length)),u[0]}if(s===e)return e.firstElementChild??e;return s;function c(u){let a=g=>{let m=g.className,f=typeof m=="string"?m:"";return`${g.tagName}.${f.split(" ")[0]??""}`},p=a(u[0]);return u.every(g=>a(g)===p)}}var ge=H.toString(),k=null,$=null,he=!1;async function q(){if(he)return!!k;if(he=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return y.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=me(process.cwd()+"/");try{return k=e("puppeteer"),y.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return k=e("puppeteer-core"),y.debug("puppeteer-core loaded from the project \u2014 capture enabled"),!0}catch{}try{return k=me(import.meta.url)("puppeteer-core"),y.debug("puppeteer-core loaded from the addon \u2014 capture enabled"),!0}catch{}return y.debug("No Puppeteer implementation available \u2014 server-side capture disabled"),!1}function mt(){let e=process.env.STORYBOOK_UICOPILOT_CHROME_PATH;if(e){if(pe(e))return e;y.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(i=>!i.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 i of r)if(pe(i))return i}async function ye(){return Y()}var V=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"}},K=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 Y(){if($&&$.connected)return $;let e=mt();if(!e&&!ht())throw new V;let n={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};try{$=await k.launch(n)}catch(t){throw e?new K(e,t):new V}return y.debug("Headless Chrome launched for screenshots"),$}function ht(){try{return typeof k?.executablePath=="function"}catch{return!1}}async function J(e,n){if(!await q())return null;let i=await(await Y()).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(s=>{let c=document.querySelectorAll("style").length,u=0,a=()=>{let p=document.querySelectorAll("style").length;if(p===c){if(u++,u>=3){s(!0);return}}else u=0,c=p;setTimeout(a,100)};setTimeout(a,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(s=>setTimeout(s,500));let l=await i.evaluate(s=>{let c=document.querySelector("#storybook-root");if(!c)return null;let u=window.innerHeight,a=window.innerWidth,p=E=>E.setAttribute("data-uic-drilled",""),g=()=>{let E=document.createElement("style");E.id="uic-drilled-bg-reset",E.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(E),document.body.offsetHeight};try{let T=new Function("return ("+s+")")()(c),C=T?.getBoundingClientRect(),_=!!C&&C.width>=a*.9&&C.height>=u*.9;if(T&&T!==c&&C&&C.width>0&&C.height>0&&!_){for(let P=T.parentElement;P&&P!==c;P=P.parentElement)p(P);return g(),{top:C.top,bottom:C.bottom,left:C.left,right:C.right}}}catch{}let m=1/0,f=0,w=1/0,b=0,x=!1;function S(E){for(let T of Array.from(E.children)){let C=window.getComputedStyle(T);if(C.display==="none"||C.visibility==="hidden"||C.position==="fixed"||C.position==="absolute")continue;let _=T.getBoundingClientRect();if(_.height<=0||_.width<=0)continue;if((_.width>=a*.9||_.height>=u*.9)&&T.children.length>0){T.setAttribute("data-uic-drilled",""),S(T);continue}if(T.children.length===1){let L=C.backgroundColor,R=L==="rgba(0, 0, 0, 0)"||L==="transparent"||L==="",D=C.borderStyle!=="none"&&C.borderWidth!=="0px",v=C.boxShadow!=="none",I=!R||D||v,A=T.children[0].getBoundingClientRect(),ze=A.width>=_.width*.95&&A.height>=_.height*.95;if(!I||ze){T.setAttribute("data-uic-drilled",""),S(T);continue}}m=Math.min(m,_.top),f=Math.max(f,_.bottom),w=Math.min(w,_.left),b=Math.max(b,_.right),x=!0}}return S(c),x?(g(),{top:m,bottom:f,left:w,right:b}):null},ge);await i.evaluate(()=>new Promise(s=>requestAnimationFrame(()=>s())));let o=4,d=l?{x:Math.max(0,l.left-o),y:Math.max(0,l.top-o),width:Math.min(l.right-l.left+o*2,800),height:Math.min(l.bottom-l.top+o*2,600)}:void 0,h=await i.screenshot({type:"png",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(h)}finally{await i.close()}}async function we(e,n,t,r){if(!await q())return null;let o=await(await Y()).newPage();try{await o.setCacheEnabled(!1),await o.setViewport({width:r?.width||800,height:r?.height||600,deviceScaleFactor:1});let d=r?.storyId||"",h=`${t}/iframe.html?viewMode=story&id=${d}&globals=`;await o.goto(h,{waitUntil:"load",timeout:15e3}),await o.waitForSelector("#storybook-root > *",{timeout:1e4}),await o.evaluate(u=>{let a=document.getElementById("storybook-root");a&&(a.innerHTML=u)},e),await o.evaluate(()=>document.fonts.ready),await new Promise(u=>setTimeout(u,500));let s=await o.evaluate(u=>{let a=document.querySelector("#storybook-root");if(!a)return null;let p=window.innerWidth,g=window.innerHeight,m=8;try{let S=new Function("return ("+u+")")()(a),E=S?.getBoundingClientRect(),T=!!E&&E.width>=p*.9&&E.height>=g*.9;if(S&&S!==a&&E&&E.width>0&&E.height>0&&!T)return{x:Math.max(0,E.x-m),y:Math.max(0,E.y-m),width:E.width+m*2,height:E.height+m*2}}catch{}function f(x){let S=x.getBoundingClientRect();if(S.width===0||S.height===0)return null;if(S.width<p*.8&&S.height>0)return S;for(let E of Array.from(x.children)){let T=window.getComputedStyle(E);if(T.position==="fixed"||T.position==="absolute"||T.display==="none"||T.visibility==="hidden")continue;let C=f(E);if(C)return C}return null}let w=f(a);if(w)return{x:Math.max(0,w.x-m),y:Math.max(0,w.y-m),width:w.width+m*2,height:w.height+m*2};let b=a.firstElementChild;if(b){let x=b.getBoundingClientRect();return{x:x.x,y:x.y,width:x.width,height:x.height}}return null},ge);if(!s)throw new Error("Could not determine component bounds from snapshot");let c=await o.screenshot({type:"png",clip:s});return Buffer.from(c)}finally{await o.close()}}async function j(){return q()}async function Z(){$&&(await $.close(),$=null)}function be(e,n){let t=e.getBoundingClientRect(),r=n.getBoundingClientRect();return{x:Math.round(t.left-r.left),y:Math.round(t.top-r.top),w:Math.round(t.width),h:Math.round(t.height)}}function xe(e,n){let t=s=>{let c=Object.keys(s).find(u=>u.startsWith("__reactFiber$"));return c?s[c]:void 0},r=s=>!!s&&s.nodeType===1&&typeof s.getBoundingClientRect=="function",i=s=>s.elementType===e||s.type===e,l=s=>{for(let c=s?.child??null;c;c=c.sibling){if(c.tag===5&&r(c.stateNode)){let a=c.stateNode.getBoundingClientRect();if(a.width>0&&a.height>0)return c.stateNode}let u=l(c);if(u)return u}},o=s=>{for(let c=s.return;c;c=c.return)if(i(c))return!0;return!1},d=new Set,h=[];for(let s of n)for(let c of[s,...Array.from(s.querySelectorAll("*"))])for(let u=t(c)??null;u;u=u.return){if(!i(u)||d.has(u)||(d.add(u),o(u)))continue;let a=l(u);a&&h.push(a)}return h}async function Se(e,n,t,r){let i=e.document;i.querySelectorAll("[data-uicopilot-instance]").forEach(a=>a.removeAttribute("data-uicopilot-instance")),i.querySelectorAll("[data-uicopilot-instance-count]").forEach(a=>a.removeAttribute("data-uicopilot-instance-count"));let l=e.__STORYBOOK_PREVIEW__;if(!l?.storyStoreValue)return 0;let o;try{o=await l.storyStoreValue.loadStory({storyId:n})}catch{return 0}let d=r??i.getElementById("storybook-root")??i.getElementById("root");if(!d||!o.component)return 0;let h=r?[]:Array.from(i.body.children).filter(a=>a!==d&&!a.contains(d)&&a.tagName!=="SCRIPT"),s=[d,...h],c=t(o.component,s);if(c.length===0&&o.subcomponents){let a=Object.values(o.subcomponents).flatMap(p=>p?t(p,s):[]);c=Array.from(new Set(a)).filter(p=>!a.some(g=>g!==p&&g.contains(p))).sort((p,g)=>p.compareDocumentPosition(g)&4?-1:1)}return c.forEach((a,p)=>a.setAttribute("data-uicopilot-instance",String(p+1))),[d,...h].some(a=>[a,...Array.from(a.querySelectorAll("*"))].some(p=>Object.keys(p).some(g=>g.startsWith("__reactFiber$"))))&&d.setAttribute("data-uicopilot-instance-count",String(c.length)),c.length}var gt=be.toString(),yt=xe.toString(),wt=Se.toString(),bt="data-uicopilot-instance";async function Q(e,n,t){return t&&await e.evaluate(async(i,l,o)=>{let d=new Function("return ("+i+")")(),h=new Function("return ("+l+")")();return d(window,o,h)},wt,yt,t),await e.evaluate((i,l,o)=>{let d=new Function("return ("+l+")")(),h=document.getElementById("storybook-root")||document.getElementById("root"),s=null;if(h)try{s=new Function("return ("+i+")")()(h)}catch{s=h.firstElementChild}let c={};if(s){let f=window.getComputedStyle(s);for(let w=0;w<f.length;w++)c[f[w]]=f.getPropertyValue(f[w])}let u={backgroundColor:["transparent","rgba(0, 0, 0, 0)"],border:["none","0px none","0px none rgb(0, 0, 0)"],borderRadius:["0px"],boxShadow:["none"],opacity:["1"]};function a(f){return f.replace(/-([a-z])/g,(w,b)=>b.toUpperCase())}function p(f,w){if(w>4)return null;let b=f.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(b))return null;let x=f.className,S=typeof x=="string"?x:x?.baseVal||"",E=f.id||void 0,T=f.getAttribute("role")||void 0,C;for(let v of Array.from(f.childNodes))if(v.nodeType===3){let I=v.textContent?.trim();if(I){C=I.length>50?I.substring(0,50)+"...":I;break}}let _=b;E?_=`${b}#${E}`:S&&(_=`${b}.${S.split(" ").filter(Boolean).join(".")}`);let P=window.getComputedStyle(f),L=["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"],R={};for(let v of L){let I=P.getPropertyValue(v),M=a(v);I&&!u[M]?.includes(I)&&(R[M]=I)}if(!R.border){let v=["top","right","bottom","left"].filter(I=>parseFloat(P.getPropertyValue(`border-${I}-width`))>0&&P.getPropertyValue(`border-${I}-style`)!=="none");if(v.length>0){let I=v.reduce((M,A)=>parseFloat(P.getPropertyValue(`border-${A}-width`))>parseFloat(P.getPropertyValue(`border-${M}-width`))?A:M);R.border=`${P.getPropertyValue(`border-${I}-width`)} ${P.getPropertyValue(`border-${I}-style`)} ${P.getPropertyValue(`border-${I}-color`)}`,R.borderSides=v.join(" ")}}if(b==="svg"||f.closest("svg"))for(let v of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=f.getAttribute(v);I&&(R[a(v)]=I)}let D=[];for(let v of Array.from(f.children)){let I=window.getComputedStyle(v);if(I.display==="none"||I.visibility==="hidden")continue;let M=p(v,w+1);M&&D.push(M)}return{selector:_,tagName:b,className:S,id:E,role:T,textContent:C,rect:s?d(f,s):void 0,instance:Number(f.getAttribute(o))>0?Number(f.getAttribute(o)):void 0,styles:R,children:D}}let g=s?p(s,0):null,m=document.querySelector("["+o+"-count]");return g&&m&&(g.instanceCount=Number(m.getAttribute(o+"-count"))),{computedStyles:c,domTree:g}},n,gt,bt)}async function z(e,n=5e3){await e.evaluate(t=>new Promise(r=>{let i=setTimeout(r,t);try{let l=window.__STORYBOOK_ADDONS_CHANNEL__;if(l){let o=()=>{clearTimeout(i),l.off("storyRendered",o),setTimeout(r,100)};l.on("storyRendered",o)}else clearTimeout(i),setTimeout(r,300)}catch{clearTimeout(i),r()}}),n)}async function Ee(e,n,t=15e3){return await e.evaluate((r,i)=>{let l=window,o=l.__STORYBOOK_PREVIEW__,d=l.__STORYBOOK_ADDONS_CHANNEL__;return!o||!d||typeof o.renderSelection!="function"||typeof o.selectionStore?.setSelection!="function"?Promise.resolve("no-preview"):new Promise(h=>{let s=!1,c=g=>{if(!s){s=!0,clearTimeout(p);try{d.off("storyRendered",u),d.off("storyErrored",a),d.off("storyMissing",a)}catch{}h(g)}},u=g=>{let m=typeof g=="string"?g:g?.storyId||g?.id;(!m||m===r)&&setTimeout(()=>c("ok"),100)},a=()=>c("errored"),p=setTimeout(()=>c("timeout"),i);d.on("storyRendered",u),d.on("storyErrored",a),d.on("storyMissing",a);try{o.selectionStore.setSelection({storyId:r,viewMode:"story"}),o.renderSelection()}catch{c("nav-failed")}})},n,t)}async function Ce(e){try{return await e.evaluate(()=>window.__STORYBOOK_PREVIEW__?.selectionStore?.selection?.storyId||null)}catch{return null}}async function ee(e){try{return await e.evaluate(()=>{let n=r=>r?r.getAttributeNames().sort().map(i=>{let l=r.getAttribute(i)??"";return i!=="class"?`${i}=${l}`:`class=${l.split(/\s+/).filter(d=>d&&!d.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 xt=6,St=15,Et=9e4,Ct=2e4;function Tt(){let e=Number(process.env.UICOPILOT_WARM_MAX_USES);return Number.isFinite(e)&&e>0?e:St}function It(){return process.env.UICOPILOT_WARM_CAPTURE!=="0"}var O=[],ne=[];function vt(e,n){return`${e}/iframe.html?viewMode=story&id=${n}&globals=`}function re(){let e=ne.shift();e&&e()}function Te(){let e=Date.now(),n=O.filter(t=>!t.busy&&t.page&&e-t.lastUsedAt>Et);if(n.length===0){O.length===0&&te();return}O=O.filter(t=>!n.includes(t));for(let t of n)t.page?.close().catch(()=>{});O.length===0&&te()}var F=null;function _t(){F||(F=setInterval(Te,3e4),F.unref?.())}function te(){F&&(clearInterval(F),F=null)}async function Pt(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:Ct}),await r.evaluate(()=>document.fonts.ready),await r.waitForSelector("#storybook-root > *",{timeout:1e4}),await z(r),r}catch(i){throw await r.close().catch(()=>{}),i}}async function Ot(e,n,t){for(;;){Te();let r=O.find(i=>i.baseUrl===n&&!i.busy&&i.page);if(r)return r.busy=!0,{entry:r,fresh:!1};if(O.length<xt){let i={page:null,baseUrl:n,uses:0,lastUsedAt:Date.now(),busy:!0,baseline:null};O.push(i),_t();try{return i.page=await Pt(e,n,t),i.baseline=await ee(i.page),{entry:i,fresh:!0}}catch{return O=O.filter(l=>l!==i),re(),null}}await new Promise(i=>ne.push(i))}}function N(e,n){e.busy=!1,e.uses++,e.lastUsedAt=Date.now(),(n||e.uses>=Tt())&&(O=O.filter(t=>t!==e),e.page?.close().catch(()=>{})),re()}async function Ie(e,n,t,r){if(!It())return{ok:!1,reason:"disabled"};let i=await Ot(e,n,t);if(!i)return{ok:!1,reason:"boot-failed"};let{entry:l,fresh:o}=i,d=l.page;try{if(!o){let s=await Ee(d,t);if(s!=="ok")return N(l,!0),{ok:!1,reason:`switch-${s}`};let c=await Ce(d);if(c&&c!==t)return N(l,!0),{ok:!1,reason:"selection-mismatch"};if(l.baseline===null)return N(l,!0),{ok:!1,reason:"baseline-unavailable"};let u=await ee(d);if(u===null)return N(l,!0),{ok:!1,reason:"document-unreadable"};if(u!==l.baseline)return N(l,!0),{ok:!1,reason:"document-drift"};await d.evaluate(()=>document.fonts.ready)}let h=await r(d);return N(l,!1),{ok:!0,value:h,booted:o}}catch(h){return N(l,!0),{ok:!1,reason:`error:${h.message}`}}}async function oe(){te();let e=O;for(O=[];ne.length;)re();await Promise.all(e.map(n=>n.page?.close().catch(()=>{})))}var Ne=H.toString(),ie=null,U=null,ke=!1;async function Bt(){if(!ke){ke=!0;try{let e=await Promise.resolve().then(()=>(Re(),Me));ie=e.validateCodeForFile,U=e.formatValidationResult,y.debug("Code validator loaded - fix validation enabled")}catch{y.debug("Code validator not available - skipping fix validation")}}}var Ht="UICOPILOT/APPLY_FIXES",Vt="UICOPILOT/FIX_STARTED",jt="UICOPILOT/FIX_COMPLETED",zt="UICOPILOT/FIX_FAILED",Fe="UICOPILOT/ALL_FIXES_APPLIED",Ut="UICOPILOT/RELOAD_REQUIRED",Le="UICOPILOT/WORKSPACE_PATH",Wt="UICOPILOT/REQUEST_WORKSPACE_PATH",Xt="UICOPILOT/DISCOVER_COMPONENT_FILES",Ae="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function De(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`],l=[`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=[],d=[];for(let m of i)try{let f=await $e(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**"]});f.length>0&&o.push(...f)}catch{}for(let m of l)try{let f=await $e(m,{cwd:n,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});f.length>0&&d.push(...f)}catch{}let h=[...new Set(o)],s=[...new Set(d)],c=m=>{if(m.length===0)return;let f=m.find(x=>x.includes(`/fui-${t}/`)&&x.endsWith(".css"));if(f)return f;let w=m.find(x=>x.toLowerCase().includes(`/${t}/${t}.css`)||x.includes(`/${r}/${r}.css`));if(w)return w;let b=m.find(x=>x.toLowerCase().endsWith(`/${t}.css`)||x.endsWith(`/${r}.css`));return b||m[0]},u=m=>{if(m.length===0)return;let f=m.filter(S=>!S.includes(".stories.")&&!S.includes(".test."));if(f.length===0)return m[0];let w=f.find(S=>S.includes(`/fui-${t}/`)&&(S.endsWith(".tsx")||S.endsWith(".jsx")));if(w)return w;let b=f.find(S=>S.toLowerCase().includes(`/${t}/${t}.tsx`)||S.includes(`/${r}/${r}.tsx`));if(b)return b;let x=f.find(S=>S.toLowerCase().endsWith(`/${t}.tsx`)||S.endsWith(`/${r}.tsx`));return x||f[0]},a=c(h),p=u(s),g=[...h,...s];return y.debug(`Discovered files for "${e}":`,{cssFile:a,componentFile:p,totalMatches:g.length}),{cssFile:a,componentFile:p,allMatches:[...new Set(g)]}}var Gt=100;function Kt(e){return new Promise(n=>setTimeout(n,e))}async function qt(e,n){if(await Bt(),!ie||!U)return y.debug(`Skipping validation (validator not available) for ${n}`),{valid:!0};let t=ie(e,n);if(!t.valid){let r=t.errors.map(i=>i.message).join("; ");return y.warn(`Code validation failed for ${n}:`),console.warn(U(t)),{valid:!1,error:r}}return t.warnings.length>0&&(y.warn(`Code validation warnings for ${n}:`),console.warn(U(t))),y.debug(`Validation passed for ${n}`),{valid:!0}}var Be=!1;function Yt(e){if(Be)return e;Be=!0;let n=process.cwd();return y.debug("Apply fixes initialized"),y.debug("Workspace:",n),e.emit(Le,{path:n}),e.on(Wt,()=>{y.debug("Workspace path requested by browser"),y.debug("Emitting workspace path response:",n),e.emit(Le,{path:n})}),e.on(Xt,async t=>{let{componentName:r,storyId:i}=t;y.debug(`Discovering files for component: ${r}`);try{let l=await De(r,n);e.emit(Ae,{componentName:r,storyId:i,...l,workspacePath:n})}catch(l){y.error("File discovery error:",l),e.emit(Ae,{componentName:r,storyId:i,error:l.message,allMatches:[]})}}),e.on(Ht,t=>{setTimeout(async()=>{try{let{issues:r,storybookRoot:i}=t,l=i||n;i?y.debug(`Using storybookRoot from API: ${i}`):y.debug(`Using process.cwd(): ${n}`),y.debug(`Received APPLY_FIXES for ${r.length} issue(s)`);let o=new Map;async function d(c){let u=c.targetFileType||"css",a=c.targetFilePath||c.generatedFix?.filePath,p="",g=c.title?.match(/^(\w+)\s/);if(g&&(p=g[1]),!p&&a){let w=a.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(p=w[1])}if(!p)return y.debug(`Could not extract component name, using provided path: ${a}`),a||null;if(!o.has(p)){let w=await De(p,l);o.set(p,w)}let m=o.get(p),f=u==="css"?m.cssFile:m.componentFile;return f?(y.debug(`Discovered ${u} path: ${f} (was: ${a})`),f):(y.debug(`No ${u} file discovered, using provided: ${a}`),a||null)}let h=[];for(let c of r){let{generatedFix:u}=c,a=c.targetFilePath||u?.filePath,p=await d(c)||a;y.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:p,providedPath:a!==p?a:"(same)",codeLength:u?.code?.length||0}),e.emit(Vt,{issueId:c.id});try{if(!u||!u.code||!p)throw new Error("Missing AI-generated fix data (code or filePath)");y.debug("Code to write (first 200 chars):",u.code.substring(0,200)),y.debug(`Code length: ${u.code.length} chars`);let g=await qt(u.code,p);if(!g.valid)throw new Error(`Code validation failed: ${g.error}. Fix was not applied to prevent breaking the file.`);let m=W.isAbsolute(p)?p:W.join(l,p);y.debug(`Writing to absolute path: ${m}`),await He.writeFile(m,u.code,"utf-8"),await Kt(Gt);let f={success:!0,issueId:c.id,filePath:p,timestamp:new Date};e.emit(jt,{issueId:c.id,result:f}),y.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${p}`),h.push(f)}catch(g){let m=g.message||"Unknown error";e.emit(zt,{issueId:c.id,error:m}),y.error(`\u2717 Error: ${m}`),h.push({success:!1,issueId:c.id,error:m,timestamp:new Date})}}let s={total:h.length,succeeded:h.filter(c=>c.success).length,failed:h.filter(c=>!c.success).length};e.emit(Fe,{results:h,summary:s}),y.debug(`Completed: ${s.succeeded}/${s.total} fixes applied`),s.succeeded>0&&e.emit(Ut,{message:"Fixes applied. If Storybook crashes due to HMR, please restart it.",filesChanged:h.filter(c=>c.success).map(c=>c.filePath)})}catch(r){y.error("Fatal error during fix application:",r),e.emit(Fe,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Jt(e){let n=process.cwd();return e.plugins=e.plugins||[],e.plugins.push({name:"uicopilot-server-api",configureServer(t){t.middlewares.use("/__uicopilot/health",(l,o)=>{o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({ok:!0,workspacePath:n}))}),t.middlewares.use("/__uicopilot/screenshot",async(l,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 s=new URL(l.url||"",`http://${l.headers.host}`).searchParams.get("storyId");if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let u=`http://${l.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Taking screenshot: ${s}`);let a=await J(u,{selector:"#storybook-root > *"});if(!a){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let p=a.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${p}`}))}catch(d){y.error("Screenshot error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/capture",async(l,o)=>{try{if(!await j()){o.writeHead(501,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Puppeteer not installed"}));return}let h=new URL(l.url||"",`http://${l.headers.host}`),s=h.searchParams.get("storyId");if(!s){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing storyId parameter"}));return}let c=h.searchParams.get("domOnly")==="1",u=l.headers.host||"localhost:6006",a=`http://${u}/iframe.html?viewMode=story&id=${s}&globals=`;y.debug(`Full capture${c?" (domOnly)":""}: ${s}`);let p=null;if(!c&&(p=await J(a,{selector:"#storybook-root > *"}),!p)){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Screenshot capture failed"}));return}let g=await ye(),m=h.searchParams.get("warm")==="0",f=null,w="cold";if(!m){let b=`http://${u}`,x=await Ie(g,b,s,S=>Q(S,Ne,s));x.ok?(f=x.value,w=x.booted?"warm-boot":"warm"):y.debug(`Warm capture unavailable (${x.reason}): ${s}`)}if(!f){let b=await g.newPage();try{await b.setCacheEnabled(!1),await b.setViewport({width:800,height:600}),await b.goto(a,{waitUntil:"load",timeout:15e3}),await b.evaluate(()=>document.fonts.ready),await b.waitForSelector("#storybook-root > *",{timeout:1e4}),await z(b),f=await Q(b,Ne,s)}finally{await b.close()}}y.debug(`Capture path for ${s}: ${w}`),o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:p?`data:image/png;base64,${p.toString("base64")}`:void 0,computedStyles:f.computedStyles,domTree:f.domTree}))}catch(d){y.error("Capture error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.middlewares.use("/__uicopilot/screenshot-snapshot",async(l,o)=>{if(l.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 w of l)h.push(typeof w=="string"?Buffer.from(w):w);let s=JSON.parse(Buffer.concat(h).toString()),{html:c,stylesheetUrls:u,storyId:a}=s;if(!c){o.writeHead(400,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Missing html in body"}));return}let g=`http://${l.headers.host||"localhost:6006"}`;y.debug(`Taking snapshot screenshot for ${a||"unknown"}`);let m=await we(c,u||[],g,{storyId:a});if(!m){o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:"Snapshot screenshot failed"}));return}let f=m.toString("base64");o.writeHead(200,{"Content-Type":"application/json"}),o.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}catch(d){y.error("Snapshot screenshot error:",d.message),o.writeHead(500,{"Content-Type":"application/json"}),o.end(JSON.stringify({error:d.message}))}}),t.httpServer?.on("close",()=>{oe().catch(()=>{}).finally(()=>Z().catch(()=>{}))});let r=l=>{oe().catch(()=>{}).then(()=>Z()).catch(()=>{}).finally(()=>{process.kill(process.pid,l)})},i=globalThis;i.__uicopilotShutdownRegistered||(i.__uicopilotShutdownRegistered=!0,process.once("SIGINT",()=>r("SIGINT")),process.once("SIGTERM",()=>r("SIGTERM")))}}),e}var Zt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=je(import.meta.url),n=Ve(e);return X(n,"manager.mjs")}return X(__dirname,"manager.mjs")},Qt=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=je(import.meta.url),n=Ve(e);return X(n,"preview.mjs")}return X(__dirname,"preview.mjs")};function fi(e=[]){return[...e,Zt()]}function pi(e=[]){return[...e,Qt()]}export{Yt as experimental_serverChannel,fi as managerEntries,pi as previewAnnotations,Jt as viteFinal};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uicopilot/storybook-addon",
3
- "version": "0.18.3",
3
+ "version": "0.20.0",
4
4
  "description": "Catch design drift between Figma and Storybook before it ships.",
5
5
  "homepage": "https://uiparity.com",
6
6
  "keywords": [