@uicopilot/storybook-addon 0.11.0 → 0.12.1

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