@uicopilot/storybook-addon 0.5.26 → 0.5.29

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 $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});
1
+ "use strict";var Le=Object.create;var D=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Oe=Object.prototype.hasOwnProperty;var Re=(e,i)=>()=>(e&&(i=e(e=0)),i);var te=(e,i)=>{for(var t in i)D(e,t,{get:i[t],enumerable:!0})},ie=(e,i,t,s)=>{if(i&&typeof i=="object"||typeof i=="function")for(let n of _e(i))!Oe.call(e,n)&&n!==t&&D(e,n,{get:()=>i[n],enumerable:!(s=$e(i,n))||s.enumerable});return e};var H=(e,i,t)=>(t=e!=null?Le(Me(e)):{},ie(i||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t,e)),Ne=e=>ie(D({},"__esModule",{value:!0}),e);var he={};te(he,{detectFileType:()=>pe,formatValidationResult:()=>st,isValidCode:()=>it,validateCode:()=>fe,validateCodeForFile:()=>me});function Ye(e,i={}){let t=i.minLength??Je;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 Ze(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 Qe(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 ue(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:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,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 pe(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 fe(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=Ze(e);r&&s.errors.push(r);let d=Qe(e);switch(d&&(t.strict?s.errors.push({...d,severity:"error"}):s.warnings.push(d)),i){case"stories":{let{errors:g,warnings:p}=tt(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=ue(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=et(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=ue(e,t);s.errors.push(...g),s.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return s.valid=s.errors.length===0,s}function me(e,i,t={}){let s=pe(i);return fe(e,s,t)}function it(e,i,t={}){return me(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 Je,ge=Re(()=>{"use strict";Je=50});var xt={};te(xt,{experimental_serverChannel:()=>Ie,managerEntries:()=>yt,previewAnnotations:()=>wt,viteFinal:()=>Te});module.exports=Ne(xt);var _=require("path"),Z=require("url");var ve=H(require("fs/promises")),B=H(require("path")),Y=require("glob");var ae=require("fs"),ce=require("module");var W={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function Fe(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var V=`[${W.NAME}]`,l={debug:(...e)=>{Fe()&&console.log(V,...e)},info:(...e)=>{console.log(V,...e)},warn:(...e)=>{console.warn(V,...e)},error:(...e)=>{console.error(V,...e)}};var Ge=["flex","inline-flex"],We=["grid","inline-grid"],Ut=[...Ge,...We];var U=null,$=null,oe=!1;async function X(){if(oe)return!!U;if(oe=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=(0,ce.createRequire)(process.cwd()+"/");try{return U=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return U=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 qe(){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,ae.existsSync)(i))return i}async function le(){if($&&$.connected)return $;let e=qe(),i={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await U.launch(i),l.debug("Headless Chrome launched for screenshots"),$}async function q(e,i){if(!await X())return null;let n=await(await le()).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(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let o=await n.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let E=v.backgroundColor,L=E==="rgba(0, 0, 0, 0)"||E==="transparent"||E==="",O=v.borderStyle!=="none"&&v.borderWidth!=="0px",R=v.boxShadow!=="none",N=!L||O||R,F=y.children[0].getBoundingClientRect(),k=F.width>=T.width*.95&&F.height>=T.height*.95;if(!N||k){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,T.top),f=Math.max(f,T.bottom),x=Math.min(x,T.left),a=Math.max(a,T.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await n.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let r=4,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",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await n.close()}}async function de(e,i,t,s){if(!await X())return null;let r=await(await le()).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 p=await r.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(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(!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 z(){return X()}async function J(){$&&(await $.close(),$=null)}var K=null,j=null,ye=!1;async function rt(){if(!ye){ye=!0;try{let e=await Promise.resolve().then(()=>(ge(),he));K=e.validateCodeForFile,j=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",we="UICOPILOT/ALL_FIXES_APPLIED",lt="UICOPILOT/RELOAD_REQUIRED",xe="UICOPILOT/WORKSPACE_PATH",dt="UICOPILOT/REQUEST_WORKSPACE_PATH",ut="UICOPILOT/DISCOVER_COMPONENT_FILES",Se="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function be(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,Y.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,Y.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)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${s}/${s}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${s}.css`));return b||a[0]},m=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 w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${s}/${s}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${s}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,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(),!K||!j)return l.debug(`Skipping validation (validator not available) for ${i}`),{valid:!0};let t=K(e,i);if(!t.valid){let s=t.errors.map(n=>n.message).join("; ");return l.warn(`Code validation failed for ${i}:`),console.warn(j(t)),{valid:!1,error:s}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${i}:`),console.warn(j(t))),l.debug(`Validation passed for ${i}`),{valid:!0}}var Ce=!1;function Ie(e){if(Ce)return e;Ce=!0;let i=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",i),e.emit(xe,{path:i}),e.on(dt,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",i),e.emit(xe,{path:i})}),e.on(ut,async t=>{let{componentName:s,storyId:n}=t;l.debug(`Discovering files for component: ${s}`);try{let o=await be(s,i);e.emit(Se,{componentName:s,storyId:n,...o,workspacePath:i})}catch(o){l.error("File discovery error:",o),e.emit(Se,{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,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!r.has(f)){let w=await be(f,o);r.set(f,w)}let a=r.get(f),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,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(ot,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await mt(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=B.isAbsolute(f)?f:B.join(o,f);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:f,timestamp:new Date};e.emit(at,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),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 p={total:g.length,succeeded:g.filter(c=>c.success).length,failed:g.filter(c=>!c.success).length};e.emit(we,{results:g,summary:p}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.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(we,{results:[],summary:{total:t.issues?.length||0,succeeded:0,failed:t.issues?.length||0}})}},0)}),e}function Te(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 z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed. Run: npm install puppeteer"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){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=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}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 z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let p=new URL(o.url||"",`http://${o.headers.host}`).searchParams.get("storyId");if(!p){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=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await q(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.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 S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let E=0;E<C.length;E++)S[C[E]]=C.getPropertyValue(C[E])}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 v(C){return C.replace(/-([a-z])/g,(E,L)=>L.toUpperCase())}function T(C,E){if(E>4)return null;let L=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let O=C.className,R=typeof O=="string"?O:O?.baseVal||"",N=C.id||void 0,Q=C.getAttribute("role")||void 0,F;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let I=P.textContent?.trim();if(I){F=I.length>50?I.substring(0,50)+"...":I;break}}let k=L;N?k=`${L}#${N}`:R&&(k=`${L}.${R.split(" ").filter(Boolean).join(".")}`);let Ee=window.getComputedStyle(C),Pe=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],G={};for(let P of Pe){let I=Ee.getPropertyValue(P),A=v(P);I&&!y[A]?.includes(I)&&(G[A]=I)}if(L==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=C.getAttribute(P);I&&(G[v(P)]=I)}let ee=[];for(let P of Array.from(C.children)){let I=window.getComputedStyle(P);if(I.display==="none"||I.visibility==="hidden")continue;let A=T(P,E+1);A&&ee.push(A)}return{selector:k,tagName:L,className:R,id:N,role:Q,textContent:F,styles:G,children:ee}}return{computedStyles:S,domTree:b?T(b,0):null}}),w=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,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 z()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of o)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;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 de(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",()=>{J().catch(()=>{})});let s=o=>{J().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 M={},ht=()=>{if(typeof M<"u"&&M.url){let e=(0,Z.fileURLToPath)(M.url),i=(0,_.dirname)(e);return(0,_.join)(i,"manager.mjs")}return(0,_.join)(__dirname,"manager.mjs")},gt=()=>{if(typeof M<"u"&&M.url){let e=(0,Z.fileURLToPath)(M.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 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};
1
+ var Se=Object.defineProperty;var be=(e,i)=>()=>(e&&(i=e(e=0)),i);var Ce=(e,i)=>{for(var t in i)Se(e,t,{get:i[t],enumerable:!0})};var oe={};Ce(oe,{detectFileType:()=>se,formatValidationResult:()=>Xe,isValidCode:()=>We,validateCode:()=>re,validateCodeForFile:()=>ne});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 ie(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:p}of d)g.test(e)&&t.push({code:"TSX_INCOMPLETE",message:p,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 se(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 re(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:p}=Ge(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"tsx":case"jsx":{let{errors:g,warnings:p}=ie(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"css":case"scss":case"less":{let{errors:g,warnings:p}=Be(e,t);s.errors.push(...g),s.warnings.push(...p);break}case"ts":case"js":{let{errors:g,warnings:p}=ie(e,t);s.errors.push(...g),s.warnings.push(...p.filter(c=>!c.code.includes("JSX")));break}default:break}return s.valid=s.errors.length===0,s}function ne(e,i,t={}){let s=se(i);return re(e,s,t)}function We(e,i,t={}){return ne(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,ae=be(()=>{"use strict";He=50});import{dirname as ge,join as U}from"path";import{fileURLToPath as ye}from"url";import*as he from"fs/promises";import*as V from"path";import{glob as ce}from"glob";import{existsSync as ke}from"fs";import{createRequire as Ae}from"module";var j={NAME:"UI Parity",SHORT:"Parity",DOMAIN:"uiparity.com",MARKETING_URL:"https://uiparity.com",APP_URL:"https://app.uiparity.com",API_URL:"https://api.uiparity.com",SUPPORT_EMAIL:"feedback@uiparity.com",TAGLINE:"Pixel-perfect isn't a feeling. It's a score."};function ve(){if(typeof process<"u"&&process.env)return process.env.UICOPILOT_DEBUG==="1";if(typeof globalThis<"u"&&"localStorage"in globalThis)try{return globalThis.localStorage.getItem("uicopilot_debug")==="1"}catch{return!1}return!1}var k=`[${j.NAME}]`,l={debug:(...e)=>{ve()&&console.log(k,...e)},info:(...e)=>{console.log(k,...e)},warn:(...e)=>{console.warn(k,...e)},error:(...e)=>{console.error(k,...e)}};var Re=["flex","inline-flex"],Ne=["grid","inline-grid"],_t=[...Re,...Ne];var A=null,$=null,Q=!1;async function B(){if(Q)return!!A;if(Q=!0,process.env.STORYBOOK_UICOPILOT_NO_PUPPETEER==="true")return l.debug("Puppeteer disabled via STORYBOOK_UICOPILOT_NO_PUPPETEER flag"),!1;let e=Ae(process.cwd()+"/");try{return A=e("puppeteer"),l.debug("Puppeteer loaded \u2014 server-side screenshots enabled"),!0}catch{}try{return A=e("puppeteer-core"),l.debug("puppeteer-core loaded \u2014 server-side screenshots enabled"),!0}catch{}return l.debug("Puppeteer not found \u2014 install puppeteer for pixel-perfect screenshots"),!1}function 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 ee(){if($&&$.connected)return $;let e=De(),i={headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"],...e?{executablePath:e}:{}};return $=await A.launch(i),l.debug("Headless Chrome launched for screenshots"),$}async function G(e,i){if(!await B())return null;let o=await(await ee()).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(p=>{let c=document.querySelectorAll("style").length,m=0,h=()=>{let f=document.querySelectorAll("style").length;if(f===c){if(m++,m>=3){p(!0);return}}else m=0,c=f;setTimeout(h,100)};setTimeout(h,200)}),{timeout:5e3}).catch(()=>{}),await new Promise(p=>setTimeout(p,500));let n=await o.evaluate(()=>{let p=document.querySelector("#storybook-root");if(!p)return null;let c=window.innerHeight,m=window.innerWidth,h=1/0,f=0,x=1/0,a=0,u=!1;function w(S){for(let y of Array.from(S.children)){let v=window.getComputedStyle(y);if(v.display==="none"||v.visibility==="hidden"||v.position==="fixed"||v.position==="absolute")continue;let T=y.getBoundingClientRect();if(T.height<=0||T.width<=0)continue;if((T.width>=m*.9||T.height>=c*.9)&&y.children.length>0){y.setAttribute("data-uic-drilled",""),w(y);continue}if(y.children.length===1){let E=v.backgroundColor,L=E==="rgba(0, 0, 0, 0)"||E==="transparent"||E==="",_=v.borderStyle!=="none"&&v.borderWidth!=="0px",M=v.boxShadow!=="none",O=!L||_||M,R=y.children[0].getBoundingClientRect(),N=R.width>=T.width*.95&&R.height>=T.height*.95;if(!O||N){y.setAttribute("data-uic-drilled",""),w(y);continue}}h=Math.min(h,T.top),f=Math.max(f,T.bottom),x=Math.min(x,T.left),a=Math.max(a,T.right),u=!0}}if(w(p),!u)return null;let b=document.createElement("style");return b.id="uic-drilled-bg-reset",b.textContent="[data-uic-drilled] { background: transparent !important; border-color: transparent !important; box-shadow: none !important; }",document.head.appendChild(b),document.body.offsetHeight,{top:h,bottom:f,left:x,right:a}});await o.evaluate(()=>new Promise(p=>requestAnimationFrame(()=>p())));let r=4,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",omitBackground:!0,...d?{clip:d}:{fullPage:!1}});return Buffer.from(g)}finally{await o.close()}}async function te(e,i,t,s){if(!await B())return null;let r=await(await ee()).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 p=await r.evaluate(()=>{let m=document.querySelector("#storybook-root");if(!m)return null;let h=window.innerWidth;function f(u){let w=u.getBoundingClientRect();if(w.width===0||w.height===0)return null;if(w.width<h*.8&&w.height>0)return w;for(let b of Array.from(u.children)){let S=window.getComputedStyle(b);if(S.position==="fixed"||S.position==="absolute"||S.display==="none"||S.visibility==="hidden")continue;let y=f(b);if(y)return y}return null}let x=f(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(!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 D(){return B()}async function W(){$&&(await $.close(),$=null)}var X=null,H=null,le=!1;async function qe(){if(!le){le=!0;try{let e=await Promise.resolve().then(()=>(ae(),oe));X=e.validateCodeForFile,H=e.formatValidationResult,l.debug("Code validator loaded - fix validation enabled")}catch{l.debug("Code validator not available - skipping fix validation")}}}var Je="UICOPILOT/APPLY_FIXES",Ye="UICOPILOT/FIX_STARTED",Ke="UICOPILOT/FIX_COMPLETED",Ze="UICOPILOT/FIX_FAILED",de="UICOPILOT/ALL_FIXES_APPLIED",Qe="UICOPILOT/RELOAD_REQUIRED",ue="UICOPILOT/WORKSPACE_PATH",et="UICOPILOT/REQUEST_WORKSPACE_PATH",tt="UICOPILOT/DISCOVER_COMPONENT_FILES",pe="UICOPILOT/COMPONENT_FILES_DISCOVERED";async function fe(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 ce(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 ce(a,{cwd:i,nodir:!0,ignore:["**/node_modules/**","**/dist/**","**/.storybook/**","**/*.stories.*","**/*.test.*"]});u.length>0&&d.push(...u)}catch{}let g=[...new Set(r)],p=[...new Set(d)],c=a=>{if(a.length===0)return;let u=a.find(S=>S.includes(`/fui-${t}/`)&&S.endsWith(".css"));if(u)return u;let w=a.find(S=>S.toLowerCase().includes(`/${t}/${t}.css`)||S.includes(`/${s}/${s}.css`));if(w)return w;let b=a.find(S=>S.toLowerCase().endsWith(`/${t}.css`)||S.endsWith(`/${s}.css`));return b||a[0]},m=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 w=u.find(y=>y.includes(`/fui-${t}/`)&&(y.endsWith(".tsx")||y.endsWith(".jsx")));if(w)return w;let b=u.find(y=>y.toLowerCase().includes(`/${t}/${t}.tsx`)||y.includes(`/${s}/${s}.tsx`));if(b)return b;let S=u.find(y=>y.toLowerCase().endsWith(`/${t}.tsx`)||y.endsWith(`/${s}.tsx`));return S||u[0]},h=c(g),f=m(p),x=[...g,...p];return l.debug(`Discovered files for "${e}":`,{cssFile:h,componentFile:f,totalMatches:x.length}),{cssFile:h,componentFile:f,allMatches:[...new Set(x)]}}var it=100;function st(e){return new Promise(i=>setTimeout(i,e))}async function rt(e,i){if(await qe(),!X||!H)return l.debug(`Skipping validation (validator not available) for ${i}`),{valid:!0};let t=X(e,i);if(!t.valid){let s=t.errors.map(o=>o.message).join("; ");return l.warn(`Code validation failed for ${i}:`),console.warn(H(t)),{valid:!1,error:s}}return t.warnings.length>0&&(l.warn(`Code validation warnings for ${i}:`),console.warn(H(t))),l.debug(`Validation passed for ${i}`),{valid:!0}}var me=!1;function nt(e){if(me)return e;me=!0;let i=process.cwd();return l.debug("Apply fixes initialized"),l.debug("Workspace:",i),e.emit(ue,{path:i}),e.on(et,()=>{l.debug("Workspace path requested by browser"),l.debug("Emitting workspace path response:",i),e.emit(ue,{path:i})}),e.on(tt,async t=>{let{componentName:s,storyId:o}=t;l.debug(`Discovering files for component: ${s}`);try{let n=await fe(s,i);e.emit(pe,{componentName:s,storyId:o,...n,workspacePath:i})}catch(n){l.error("File discovery error:",n),e.emit(pe,{componentName:s,storyId:o,error:n.message,allMatches:[]})}}),e.on(Je,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,f="",x=c.title?.match(/^(\w+)\s/);if(x&&(f=x[1]),!f&&h){let w=h.match(/\/(\w+)\.(?:css|tsx|jsx)$/i);w&&(f=w[1])}if(!f)return l.debug(`Could not extract component name, using provided path: ${h}`),h||null;if(!r.has(f)){let w=await fe(f,n);r.set(f,w)}let a=r.get(f),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,f=await d(c)||h;l.debug("Processing issue:",{id:c.id,type:c.type,targetFileType:c.targetFileType||"css",targetPath:f,providedPath:h!==f?h:"(same)",codeLength:m?.code?.length||0}),e.emit(Ye,{issueId:c.id});try{if(!m||!m.code||!f)throw new Error("Missing AI-generated fix data (code or filePath)");l.debug("Code to write (first 200 chars):",m.code.substring(0,200)),l.debug(`Code length: ${m.code.length} chars`);let x=await rt(m.code,f);if(!x.valid)throw new Error(`Code validation failed: ${x.error}. Fix was not applied to prevent breaking the file.`);let a=V.isAbsolute(f)?f:V.join(n,f);l.debug(`Writing to absolute path: ${a}`),await he.writeFile(a,m.code,"utf-8"),await st(it);let u={success:!0,issueId:c.id,filePath:f,timestamp:new Date};e.emit(Ke,{issueId:c.id,result:u}),l.debug(`\u2713 Applied ${c.targetFileType||"css"} fix to: ${f}`),g.push(u)}catch(x){let a=x.message||"Unknown error";e.emit(Ze,{issueId:c.id,error:a}),l.error(`\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}),l.debug(`Completed: ${p.succeeded}/${p.total} fixes applied`),p.succeeded>0&&e.emit(Qe,{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(de,{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 D()){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 m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Taking screenshot: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${f}`}))}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 D()){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 m=`http://${n.headers.host||"localhost:6006"}/iframe.html?viewMode=story&id=${p}&globals=`;l.debug(`Full capture: ${p}`);let h=await G(m,{selector:"#storybook-root > *"});if(!h){r.writeHead(500,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Screenshot capture failed"}));return}let f;try{f=(await import("puppeteer")).default}catch{f=(await import("puppeteer-core")).default}let x=await f.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 S=setTimeout(b,5e3);try{let y=window.__STORYBOOK_ADDONS_CHANNEL__;if(y){let v=()=>{clearTimeout(S),y.off("storyRendered",v),setTimeout(b,100)};y.on("storyRendered",v)}else clearTimeout(S),setTimeout(b,300)}catch{clearTimeout(S),b()}}));let u=await a.evaluate(()=>{let b=document.querySelector("#storybook-root > *")||document.querySelector("#root > *"),S={};if(b){let C=window.getComputedStyle(b);for(let E=0;E<C.length;E++)S[C[E]]=C.getPropertyValue(C[E])}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 v(C){return C.replace(/-([a-z])/g,(E,L)=>L.toUpperCase())}function T(C,E){if(E>4)return null;let L=C.tagName.toLowerCase();if(["script","style","link","meta","br","hr","noscript"].includes(L))return null;let _=C.className,M=typeof _=="string"?_:_?.baseVal||"",O=C.id||void 0,q=C.getAttribute("role")||void 0,R;for(let P of Array.from(C.childNodes))if(P.nodeType===3){let I=P.textContent?.trim();if(I){R=I.length>50?I.substring(0,50)+"...":I;break}}let N=L;O?N=`${L}#${O}`:M&&(N=`${L}.${M.split(" ").filter(Boolean).join(".")}`);let we=window.getComputedStyle(C),xe=["background-color","border","border-radius","box-shadow","opacity","fill","stroke","stroke-width","font-size","font-family","font-weight","line-height","letter-spacing","color","text-align","display","padding","margin","gap","flex-direction","justify-content","align-items","width","height"],z={};for(let P of xe){let I=we.getPropertyValue(P),F=v(P);I&&!y[F]?.includes(I)&&(z[F]=I)}if(L==="svg"||C.closest("svg"))for(let P of["fill","stroke","stroke-width","viewBox","d","r","cx","cy"]){let I=C.getAttribute(P);I&&(z[v(P)]=I)}let J=[];for(let P of Array.from(C.children)){let I=window.getComputedStyle(P);if(I.display==="none"||I.visibility==="hidden")continue;let F=T(P,E+1);F&&J.push(F)}return{selector:N,tagName:L,className:M,id:O,role:q,textContent:R,styles:z,children:J}}return{computedStyles:S,domTree:b?T(b,0):null}}),w=h.toString("base64");r.writeHead(200,{"Content-Type":"application/json"}),r.end(JSON.stringify({screenshot:`data:image/png;base64,${w}`,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 D()){r.writeHead(501,{"Content-Type":"application/json"}),r.end(JSON.stringify({error:"Puppeteer not installed"}));return}let g=[];for await(let w of n)g.push(typeof w=="string"?Buffer.from(w):w);let p=JSON.parse(Buffer.concat(g).toString()),{html:c,stylesheetUrls:m,storyId:h}=p;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 te(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",()=>{W().catch(()=>{})});let s=n=>{W().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=ye(import.meta.url),i=ge(e);return U(i,"manager.mjs")}return U(__dirname,"manager.mjs")},ct=()=>{if(typeof import.meta<"u"&&import.meta.url){let e=ye(import.meta.url),i=ge(e);return U(i,"preview.mjs")}return U(__dirname,"preview.mjs")};function li(e=[]){return[...e,at()]}function di(e=[]){return[...e,ct()]}export{nt as experimental_serverChannel,li as managerEntries,di 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.26",
3
+ "version": "0.5.29",
4
4
  "description": "Catch design drift between Figma and Storybook before it ships.",
5
5
  "homepage": "https://uiparity.com",
6
6
  "keywords": [