@uicopilot/storybook-addon 0.5.9 → 0.5.10

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