aem-eds-kit 0.4.30 → 0.4.33

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.
Files changed (3) hide show
  1. package/README.md +5 -0
  2. package/dist/bin/eds.js +107 -107
  3. package/package.json +2 -2
package/dist/bin/eds.js CHANGED
@@ -1,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- var hs=Object.defineProperty;var v=(e,t)=>()=>(e&&(t=e(e=0)),t);var L=(e,t)=>{for(var n in t)hs(e,n,{get:t[n],enumerable:!0})};import Wp from"path";import{fileURLToPath as qp}from"url";var f=v(()=>{"use strict"});import D from"chalk";function Tt(e){return q[e]}function ei(e){return e.replace(bs,"").length}function ot(e,t){let n=t-ei(e);return n>0?e+" ".repeat(n):e}function ys(){return D.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function Yo(){return`${ys()} ${D.bold("aem-eds-kit")}`}function ks(){return Array.from({length:vs},()=>_.accent("\u25CF")).join(" ")}function xs(e,t=""){return t?`${Yo()} ${e} ${D.dim(t)}`:`${Yo()} ${e}`}function Qo(e){let t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function $s(e,t,n){let[o,i,a]=Qo(e),[s,d,l]=Qo(t),c=Math.round(o+(s-o)*n),p=Math.round(i+(d-i)*n),m=Math.round(a+(l-a)*n);return`#${[c,p,m].map(u=>u.toString(16).padStart(2,"0")).join("")}`}function Ss(e,t,n){let o=[...e],i=Math.max(n-1,1);return o.map((a,s)=>{if(a===" ")return a;let d=s/i*(t.length-1),l=Math.min(Math.floor(d),t.length-2);return D.hex($s(t[l],t[l+1],d-l))(a)}).join("")}function Ps(){let e=M(Zo);return Zo.map(t=>` ${Ss(t,js,e)}`).join(`
3
- `)}function E(e="AEM Edge Delivery Services"){return`
4
- ${Ps()}
5
-
6
- ${xs(ks(),e)}
7
- `}function S(e,t){let n=_.red("\u258A"),o=t?` ${D.dim(t)}`:"";return`
8
- ${n} ${D.bold(e)}${o}
9
- `}function A(e,t,n,o=0){let i=o?ot(t,o):t,a=n?` ${D.dim(n)}`:"";return` ${q[e]} ${i}${a}`}function j(e,t,n=0){let o=n?ot(e,n):e,i=t?` ${D.dim(t)}`:"";return` ${_.accent("\u2714")} ${o}${i}`}function M(e){return e.reduce((t,n)=>Math.max(t,ei(n)),0)}function O(e,t=_.red){let n=M(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),i=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),a=e.map(s=>`${t("\u2502")} ${ot(s,n)} ${t("\u2502")}`).join(`
2
+ var Ps=Object.defineProperty;var k=(e,t)=>()=>(e&&(t=e(e=0)),t);var O=(e,t)=>{for(var n in t)Ps(e,n,{get:t[n],enumerable:!0})};import sp from"path";import{fileURLToPath as lp}from"url";var f=k(()=>{"use strict"});import L from"chalk";function Rt(e){return W[e]}function ri(e){return e.replace(Cs,"").length}function nt(e,t){let n=t-ri(e);return n>0?e+" ".repeat(n):e}function As(){return L.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function ni(){return`${As()} ${L.bold("aem-eds-kit")}`}function Rs(){return Array.from({length:Ts},()=>U.accent("\u25CF")).join(" ")}function Fs(e,t=""){return t?`${ni()} ${e} ${L.dim(t)}`:`${ni()} ${e}`}function oi(e){let t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function Ds(e,t,n){let[o,i,a]=oi(e),[s,d,l]=oi(t),c=Math.round(o+(s-o)*n),m=Math.round(i+(d-i)*n),p=Math.round(a+(l-a)*n);return`#${[c,m,p].map(u=>u.toString(16).padStart(2,"0")).join("")}`}function Ls(e,t,n){let o=[...e],i=Math.max(n-1,1);return o.map((a,s)=>{if(a===" ")return a;let d=s/i*(t.length-1),l=Math.min(Math.floor(d),t.length-2);return L.hex(Ds(t[l],t[l+1],d-l))(a)}).join("")}function Ns(){let e=I(ii);return ii.map(t=>` ${Ls(t,Os,e)}`).join(`
3
+ `)}function C(e="AEM Edge Delivery Services"){return`
4
+ ${Ns()}
5
+
6
+ ${Fs(Rs(),e)}
7
+ `}function S(e,t){let n=U.red("\u258A"),o=t?` ${L.dim(t)}`:"";return`
8
+ ${n} ${L.bold(e)}${o}
9
+ `}function A(e,t,n,o=0){let i=o?nt(t,o):t,a=n?` ${L.dim(n)}`:"";return` ${W[e]} ${i}${a}`}function j(e,t,n=0){let o=n?nt(e,n):e,i=t?` ${L.dim(t)}`:"";return` ${U.accent("\u2714")} ${o}${i}`}function I(e){return e.reduce((t,n)=>Math.max(t,ri(n)),0)}function N(e,t=U.red){let n=I(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),i=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),a=e.map(s=>`${t("\u2502")} ${nt(s,n)} ${t("\u2502")}`).join(`
10
10
  `);return`${o}
11
11
  ${a}
12
- ${i}`}function fe(e){let t=[];return e.pass&&t.push(`${q.pass} ${e.pass} passed`),e.warn&&t.push(`${q.warn} ${e.warn} ${Es(e.warn,"warning")}`),e.fail&&t.push(`${q.fail} ${e.fail} failed`),e.info&&t.push(`${q.info} ${e.info} info`),t.join(D.dim(" "))}function Es(e,t){return e===1?t:`${t}s`}var _,q,bs,vs,ti,Zo,js,N=v(()=>{"use strict";f();_={red:D.hex("#FA0F00"),ember:D.hex("#FF4B1F"),orange:D.hex("#FF7B00"),blue:D.hex("#2680EB"),accent:D.hex("#ff5a36"),dotOrange:D.hex("#F24E1E"),dotPurple:D.hex("#A259FF"),dotBlue:D.hex("#1ABCFE"),dotGreen:D.hex("#0ACF83"),dotPink:D.hex("#FF7262"),ok:D.hex("#2D9D78"),warn:D.hex("#E68619"),err:D.hex("#D7373F"),info:D.hex("#2680EB")},q={pass:_.ok("\u2713"),warn:_.warn("\u26A0"),fail:_.err("\u2717"),info:_.info("\u2139"),bullet:D.dim("\u2022"),arrow:D.dim("\u21B3"),figma:_.dotPurple("\u25C6")};bs=/\[[0-9;]*m/g;vs=5;ti={prefix:"",style:{highlight:e=>D.hex("#ff5a36").bold(e)}};Zo=["\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588 ","\u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588","\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588"],js=["#ff3b1e","#ff5a36","#ff7d52"]});import Rt from"chalk";function Cs(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in fn?e:"info"}function $e(e){return oi?e==="error":fn[e]>=fn[ni]}var fn,ni,oi,Ft,r,R=v(()=>{"use strict";f();N();fn={debug:0,info:1,warn:2,error:3,silent:4};ni=Cs(),oi=!1,Ft=!1;r={setLevel(e){ni=e},setQuiet(e){oi=e},debug(...e){$e("debug")&&console.error(Rt.gray("[debug]"),...e)},info(...e){$e("info")&&console.error(...e)},logoOnce(e){Ft||(Ft=!0,$e("info")&&console.error(e))},async logoOnceAnimated(e){Ft||(Ft=!0,$e("info")&&console.error(E(e)))},success(...e){$e("info")&&console.error(Rt.green("\u2713"),...e)},warn(...e){$e("warn")&&console.error(Rt.yellow("\u26A0"),...e)},error(...e){$e("error")&&console.error(Rt.red("\u2717"),...e)}}});function _e(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"aem-eds-kit","Content-Type":"application/json"}}function As(e){return`${Ie}/repos/${e}/generate`}async function Dt(e){let t=await fetch(`${Ie}/user`,{headers:_e(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function ii(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{headers:_e(e)});if(o.status===404)return!1;if(o.ok)return!0;throw new Error(`existence check failed: ${o.status} ${await o.text()}`)}async function ri(e,t,n){let o=await fetch(As(t),{method:"POST",headers:_e(e),body:JSON.stringify({owner:n.owner,name:n.name,private:!!n.private,include_all_branches:!1})});if(!o.ok)throw new Error(`create failed: ${o.status} ${await o.text()}`);let i=await o.json();return{fullName:i.full_name,htmlUrl:i.html_url,cloneUrl:i.clone_url}}async function ai(e,t,n,o){await fetch(`${Ie}/repos/${t}/${n}/topics`,{method:"PUT",headers:_e(e),body:JSON.stringify({names:o})})}async function si(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{method:"DELETE",headers:_e(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function ci(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),i=await fetch(`${Ie}/search/repositories?q=${o}&per_page=100`,{headers:_e(e)});if(!i.ok)throw new Error(`search failed: ${i.status}`);return(await i.json()).items.map(s=>s.full_name)}var Ie,li=v(()=>{"use strict";f();Ie="https://api.github.com"});import{existsSync as di}from"fs";import{mkdir as Ts,readFile as Rs,rm as Fs,writeFile as Ds}from"fs/promises";import Ls from"os";import pi from"path";async function ui(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(di(it))try{return JSON.parse(await Rs(it,"utf-8")).token??null}catch{return null}return null}async function gn(e){await Ts(mi,{recursive:!0,mode:448}),await Ds(it,`${JSON.stringify({token:e},null,2)}
13
- `,{mode:384})}async function fi(){di(it)&&await Fs(it)}async function gi(e){let t=await fetch("https://github.com/login/device/code",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Lt,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function hi(e,t,n){let o=Math.max(t,1),i=Date.now()+n*1e3;for(;Date.now()<i;){await new Promise(d=>setTimeout(d,o*1e3));let s=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Lt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(s.access_token)return s.access_token;if(s.error==="slow_down")o+=5;else if(s.error!=="authorization_pending")throw new Error(s.error??"device flow failed")}throw new Error("device flow timed out")}var mi,it,Lt,wi=v(()=>{"use strict";f();mi=pi.join(Ls.homedir(),".eds"),it=pi.join(mi,"github.json"),Lt=process.env.EDS_GITHUB_CLIENT_ID??""});function hn(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function wn(){return"https://github.com/apps/aem-code-sync/installations/new"}function bi(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Ue,rt,yi=v(()=>{"use strict";f();Ue="eds-sandbox",rt={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var H={};L(H,{checkbox:()=>Hs,confirm:()=>Bs,input:()=>Us,select:()=>_s});import{checkbox as Os,confirm as Ns,input as Ms,select as Is}from"@inquirer/prompts";function Ot(e){let t={...ti,...e.theme??{}};return{...e,theme:t}}var _s,Us,Bs,Hs,G=v(()=>{"use strict";f();N();_s=(e,t)=>Is(Ot(e),t),Us=(e,t)=>Ms(Ot(e),t),Bs=(e,t)=>Ns(Ot(e),t),Hs=(e,t)=>Os(Ot(e),t)});import{z as F}from"zod";var gm,bn,vi,hm,Se,Be=v(()=>{"use strict";f();gm=F.object({fileKey:F.string().min(1),nodeId:F.string().optional(),fileName:F.string().optional()}),bn=F.object({agent:F.enum(["claude","cursor","codex"]).optional(),model:F.string().optional(),figma:F.object({mcpEndpoint:F.string().url().optional(),token:F.string().optional()}).optional(),admin:F.object({org:F.string().optional(),site:F.string().optional(),ref:F.string().default("main")}).optional()}),vi=F.object({root:F.string(),hasFstab:F.boolean(),hasBlocks:F.boolean(),hasHeadHtml:F.boolean()}),hm=F.object({figmaFileKey:F.string(),figmaNodeId:F.string().optional(),lastSyncedAt:F.string().datetime(),promptVersion:F.string(),agentUsed:F.string().optional(),breakpoints:F.array(F.object({width:F.number(),label:F.string().optional(),source:F.enum(["figma","default"]).optional()})).optional()}),Se=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as at}from"fs";import ge from"path";function P(e=process.cwd()){let t=ge.resolve(e),{root:n}=ge.parse(t);for(;t!==n;){if(ki.some(o=>at(ge.join(t,o))))return t;t=ge.dirname(t)}if(ki.some(o=>at(ge.join(n,o))))return n}function xi(e){return vi.parse({root:e,hasFstab:at(ge.join(e,"fstab.yaml")),hasBlocks:at(ge.join(e,"blocks")),hasHeadHtml:at(ge.join(e,"head.html"))})}var ki,B=v(()=>{"use strict";f();Be();ki=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Gs}from"fs";import{mkdir as zs,writeFile as Ws}from"fs/promises";import $i from"path";async function Nt(e){let t=$i.join(e,".github","workflows","eds.yml");return Gs(t)?{path:Si,created:!1}:(await zs($i.dirname(t),{recursive:!0}),await Ws(t,Js),{path:Si,created:!0})}var Si,Js,yn=v(()=>{"use strict";f();Si=".github/workflows/eds.yml",Js=`name: EDS checks
12
+ ${i}`}function ge(e){let t=[];return e.pass&&t.push(`${W.pass} ${e.pass} passed`),e.warn&&t.push(`${W.warn} ${e.warn} ${Ms(e.warn,"warning")}`),e.fail&&t.push(`${W.fail} ${e.fail} failed`),e.info&&t.push(`${W.info} ${e.info} info`),t.join(L.dim(" "))}function Ms(e,t){return e===1?t:`${t}s`}var U,W,Cs,Ts,ai,ii,Os,M=k(()=>{"use strict";f();U={red:L.hex("#FA0F00"),ember:L.hex("#FF4B1F"),orange:L.hex("#FF7B00"),blue:L.hex("#2680EB"),accent:L.hex("#ff5a36"),dotOrange:L.hex("#F24E1E"),dotPurple:L.hex("#A259FF"),dotBlue:L.hex("#1ABCFE"),dotGreen:L.hex("#0ACF83"),dotPink:L.hex("#FF7262"),ok:L.hex("#2D9D78"),warn:L.hex("#E68619"),err:L.hex("#D7373F"),info:L.hex("#2680EB")},W={pass:U.ok("\u2713"),warn:U.warn("\u26A0"),fail:U.err("\u2717"),info:U.info("\u2139"),bullet:L.dim("\u2022"),arrow:L.dim("\u21B3"),figma:U.dotPurple("\u25C6")};Cs=/\[[0-9;]*m/g;Ts=5;ai={prefix:"",style:{highlight:e=>L.hex("#ff5a36").bold(e)}};ii=["\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588 ","\u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588","\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588"],Os=["#ff3b1e","#ff5a36","#ff7d52"]});import Ft from"chalk";function Is(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in gn?e:"info"}function je(e){return ci?e==="error":gn[e]>=gn[si]}var gn,si,ci,Dt,r,R=k(()=>{"use strict";f();M();gn={debug:0,info:1,warn:2,error:3,silent:4};si=Is(),ci=!1,Dt=!1;r={setLevel(e){si=e},setQuiet(e){ci=e},debug(...e){je("debug")&&console.error(Ft.gray("[debug]"),...e)},info(...e){je("info")&&console.error(...e)},logoOnce(e){Dt||(Dt=!0,je("info")&&console.error(e))},async logoOnceAnimated(e){Dt||(Dt=!0,je("info")&&console.error(C(e)))},success(...e){je("info")&&console.error(Ft.green("\u2713"),...e)},warn(...e){je("warn")&&console.error(Ft.yellow("\u26A0"),...e)},error(...e){je("error")&&console.error(Ft.red("\u2717"),...e)}}});function _e(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"aem-eds-kit","Content-Type":"application/json"}}function _s(e){return`${Ie}/repos/${e}/generate`}async function Lt(e){let t=await fetch(`${Ie}/user`,{headers:_e(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function li(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{headers:_e(e)});if(o.status===404)return!1;if(o.ok)return!0;throw new Error(`existence check failed: ${o.status} ${await o.text()}`)}async function di(e,t,n){let o=await fetch(_s(t),{method:"POST",headers:_e(e),body:JSON.stringify({owner:n.owner,name:n.name,private:!!n.private,include_all_branches:!1})});if(!o.ok)throw new Error(`create failed: ${o.status} ${await o.text()}`);let i=await o.json();return{fullName:i.full_name,htmlUrl:i.html_url,cloneUrl:i.clone_url}}async function mi(e,t,n,o){await fetch(`${Ie}/repos/${t}/${n}/topics`,{method:"PUT",headers:_e(e),body:JSON.stringify({names:o})})}async function pi(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{method:"DELETE",headers:_e(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function ui(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),i=await fetch(`${Ie}/search/repositories?q=${o}&per_page=100`,{headers:_e(e)});if(!i.ok)throw new Error(`search failed: ${i.status}`);return(await i.json()).items.map(s=>s.full_name)}var Ie,fi=k(()=>{"use strict";f();Ie="https://api.github.com"});import{existsSync as gi}from"fs";import{mkdir as Us,readFile as Bs,rm as Hs,writeFile as Gs}from"fs/promises";import zs from"os";import hi from"path";async function bi(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(gi(ot))try{return JSON.parse(await Bs(ot,"utf-8")).token??null}catch{return null}return null}async function hn(e){await Us(wi,{recursive:!0,mode:448}),await Gs(ot,`${JSON.stringify({token:e},null,2)}
13
+ `,{mode:384})}async function yi(){gi(ot)&&await Hs(ot)}async function vi(e){let t=await fetch("https://github.com/login/device/code",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Ot,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function ki(e,t,n){let o=Math.max(t,1),i=Date.now()+n*1e3;for(;Date.now()<i;){await new Promise(d=>setTimeout(d,o*1e3));let s=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Ot,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(s.access_token)return s.access_token;if(s.error==="slow_down")o+=5;else if(s.error!=="authorization_pending")throw new Error(s.error??"device flow failed")}throw new Error("device flow timed out")}var wi,ot,Ot,xi=k(()=>{"use strict";f();wi=hi.join(zs.homedir(),".eds"),ot=hi.join(wi,"github.json"),Ot=process.env.EDS_GITHUB_CLIENT_ID??""});function wn(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function bn(){return"https://github.com/apps/aem-code-sync/installations/new"}function $i(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Ue,it,Si=k(()=>{"use strict";f();Ue="eds-sandbox",it={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var H={};O(H,{checkbox:()=>Qs,confirm:()=>Ys,input:()=>Vs,select:()=>Xs});import{checkbox as Ws,confirm as Js,input as qs,select as Ks}from"@inquirer/prompts";function Nt(e){let t={...ai,...e.theme??{}};return{...e,theme:t}}var Xs,Vs,Ys,Qs,G=k(()=>{"use strict";f();M();Xs=(e,t)=>Ks(Nt(e),t),Vs=(e,t)=>qs(Nt(e),t),Ys=(e,t)=>Js(Nt(e),t),Qs=(e,t)=>Ws(Nt(e),t)});import{z as F}from"zod";var Rp,yn,ji,Fp,Pe,Be=k(()=>{"use strict";f();Rp=F.object({fileKey:F.string().min(1),nodeId:F.string().optional(),fileName:F.string().optional()}),yn=F.object({agent:F.enum(["claude","cursor","codex"]).optional(),model:F.string().optional(),figma:F.object({mcpEndpoint:F.string().url().optional(),token:F.string().optional()}).optional(),admin:F.object({org:F.string().optional(),site:F.string().optional(),ref:F.string().default("main")}).optional()}),ji=F.object({root:F.string(),hasFstab:F.boolean(),hasBlocks:F.boolean(),hasHeadHtml:F.boolean()}),Fp=F.object({figmaFileKey:F.string(),figmaNodeId:F.string().optional(),lastSyncedAt:F.string().datetime(),promptVersion:F.string(),agentUsed:F.string().optional(),breakpoints:F.array(F.object({width:F.number(),label:F.string().optional(),source:F.enum(["figma","default"]).optional()})).optional()}),Pe=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as rt}from"fs";import he from"path";function P(e=process.cwd()){let t=he.resolve(e),{root:n}=he.parse(t);for(;t!==n;){if(Pi.some(o=>rt(he.join(t,o))))return t;t=he.dirname(t)}if(Pi.some(o=>rt(he.join(n,o))))return n}function Ei(e){return ji.parse({root:e,hasFstab:rt(he.join(e,"fstab.yaml")),hasBlocks:rt(he.join(e,"blocks")),hasHeadHtml:rt(he.join(e,"head.html"))})}var Pi,z=k(()=>{"use strict";f();Be();Pi=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Zs}from"fs";import{mkdir as ec,writeFile as tc}from"fs/promises";import Ci from"path";async function Mt(e){let t=Ci.join(e,".github","workflows","eds.yml");return Zs(t)?{path:Ai,created:!1}:(await ec(Ci.dirname(t),{recursive:!0}),await tc(t,nc),{path:Ai,created:!0})}var Ai,nc,vn=k(()=>{"use strict";f();Ai=".github/workflows/eds.yml",nc=`name: EDS checks
14
14
 
15
15
  # Generated by aem-eds-kit (\`eds scaffold ci\`). Runs the project's own
16
16
  # lint/build plus the eds audits as a gatekeeper on every PR and push to main.
@@ -53,18 +53,18 @@ jobs:
53
53
  run: npx --yes aem-eds-kit@latest audit loading
54
54
  - name: Security & exploit scan
55
55
  run: npx --yes aem-eds-kit@latest audit security
56
- `});import{existsSync as ji}from"fs";import{readFile as qs,writeFile as Pi}from"fs/promises";import Ei from"path";function Ks(e={}){let t=e.open??"/",n=e.port??3007,o=e.pagesUrl??"";return`AEM_OPEN=${t}
56
+ `});import{existsSync as Ti}from"fs";import{readFile as oc,writeFile as Ri}from"fs/promises";import Fi from"path";function ic(e={}){let t=e.open??"/",n=e.port??3007,o=e.pagesUrl??"";return`AEM_OPEN=${t}
57
57
  AEM_PORT=${n}
58
58
  AEM_PAGES_URL=${o}
59
- `}async function Xs(e){let t=Ei.join(e,".gitignore"),n="";if(ji(t)&&(n=await qs(t,"utf-8")),n.split(/\r?\n/).some(i=>i.trim()===".env"))return!1;let o=n&&!n.endsWith(`
59
+ `}async function rc(e){let t=Fi.join(e,".gitignore"),n="";if(Ti(t)&&(n=await oc(t,"utf-8")),n.split(/\r?\n/).some(i=>i.trim()===".env"))return!1;let o=n&&!n.endsWith(`
60
60
  `)?`
61
- `:"";return await Pi(t,`${n}${o}.env
62
- `),!0}async function Mt(e,t={}){let n=Ei.join(e,".env"),o=!ji(n);o&&await Pi(n,Ks(t));let i=await Xs(e);return{path:".env",created:o,gitignoreUpdated:i}}var vn=v(()=>{"use strict";f()});import{writeFile as Ci}from"fs/promises";import Ai from"path";function It(e){return e!=="ue"}function Ti(e,t){return`https://content.da.live/${e}/${t}/`}function Vs(e){return`mountpoints:
61
+ `:"";return await Ri(t,`${n}${o}.env
62
+ `),!0}async function It(e,t={}){let n=Fi.join(e,".env"),o=!Ti(n);o&&await Ri(n,ic(t));let i=await rc(e);return{path:".env",created:o,gitignoreUpdated:i}}var kn=k(()=>{"use strict";f()});import{writeFile as Di}from"fs/promises";import Li from"path";function _t(e){return e!=="ue"}function Oi(e,t){return`https://content.da.live/${e}/${t}/`}function ac(e){return`mountpoints:
63
63
  /: ${e}
64
- `}async function Ri(e,t){return await Ci(Ai.join(e,"fstab.yaml"),Vs(t)),"fstab.yaml"}function Ys(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
65
- `}async function Fi(e,t){return await Ci(Ai.join(e,"paths.json"),Ys(t)),"paths.json"}var je,Di=v(()=>{"use strict";f();je={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as Qs}from"fs";import{writeFile as Zs}from"fs/promises";import ec from"path";function nc(){return`${JSON.stringify(tc,null,2)}
66
- `}async function _t(e){let t=ec.join(e,"xwalk.json");return Qs(t)?{path:"xwalk.json",created:!1}:(await Zs(t,nc()),{path:"xwalk.json",created:!0})}var tc,kn=v(()=>{"use strict";f();tc={public:{xwalk:{"multi-field":{enabled:!0}}}}});function He(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function Ge(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function Li({host:e,path:t="/",org:n}){let o=e.replace(/^https?:\/\//,"").replace(/\/+$/,""),i=t.startsWith("/")?t:`/${t}`;return`https://experience.adobe.com/#/${n?`@${n}/`:""}aem/editor/canvas/${o}${i}`}var Ut=v(()=>{"use strict";f()});function st(e){return`${JSON.stringify(e,null,2)}
67
- `}function $n(e){return Pe.find(t=>t.id===e)}var xn,Oi,Ni,Pe,Sn=v(()=>{"use strict";f();xn=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),Oi=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),Ni=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),Pe=[{id:"hero",title:"Hero",js:`// Block: hero
64
+ `}async function Ni(e,t){return await Di(Li.join(e,"fstab.yaml"),ac(t)),"fstab.yaml"}function sc(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
65
+ `}async function Mi(e,t){return await Di(Li.join(e,"paths.json"),sc(t)),"paths.json"}var Ee,Ii=k(()=>{"use strict";f();Ee={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as cc}from"fs";import{writeFile as lc}from"fs/promises";import dc from"path";function pc(){return`${JSON.stringify(mc,null,2)}
66
+ `}async function Ut(e){let t=dc.join(e,"xwalk.json");return cc(t)?{path:"xwalk.json",created:!1}:(await lc(t,pc()),{path:"xwalk.json",created:!0})}var mc,xn=k(()=>{"use strict";f();mc={public:{xwalk:{"multi-field":{enabled:!0}}}}});function He(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function Ge(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function _i({host:e,path:t="/",org:n}){let o=e.replace(/^https?:\/\//,"").replace(/\/+$/,""),i=t.startsWith("/")?t:`/${t}`;return`https://experience.adobe.com/#/${n?`@${n}/`:""}aem/editor/canvas/${o}${i}`}var Bt=k(()=>{"use strict";f()});function at(e){return`${JSON.stringify(e,null,2)}
67
+ `}function Sn(e){return Ce.find(t=>t.id===e)}var $n,Ui,Bi,Ce,jn=k(()=>{"use strict";f();$n=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),Ui=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),Bi=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),Ce=[{id:"hero",title:"Hero",js:`// Block: hero
68
68
  export default function decorate(block) {
69
69
  block.classList.add('hero');
70
70
  const picture = block.querySelector('picture');
@@ -93,7 +93,7 @@ export default function decorate(block) {
93
93
  margin: 0 auto;
94
94
  padding: 0 var(--spacing-m, 16px);
95
95
  }
96
- `,model:st({definitions:[xn("Hero","hero","hero")],models:[{id:"hero",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"}]}],filters:[]})},{id:"cards",title:"Cards",js:`// Block: cards
96
+ `,model:at({definitions:[$n("Hero","hero","hero")],models:[{id:"hero",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"}]}],filters:[]})},{id:"cards",title:"Cards",js:`// Block: cards
97
97
  export default function decorate(block) {
98
98
  const ul = document.createElement('ul');
99
99
  [...block.children].forEach((row) => {
@@ -132,7 +132,7 @@ export default function decorate(block) {
132
132
  .cards .cards-card-body {
133
133
  padding: var(--spacing-m, 16px);
134
134
  }
135
- `,model:st({definitions:[Oi("Cards","cards","cards"),Ni("Card","card","card")],models:[{id:"card",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"},{component:"aem-content",name:"link",label:"Link"}]}],filters:[{id:"cards",components:["card"]}]})},{id:"columns",title:"Columns",js:`// Block: columns
135
+ `,model:at({definitions:[Ui("Cards","cards","cards"),Bi("Card","card","card")],models:[{id:"card",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"},{component:"aem-content",name:"link",label:"Link"}]}],filters:[{id:"cards",components:["card"]}]})},{id:"columns",title:"Columns",js:`// Block: columns
136
136
  export default function decorate(block) {
137
137
  const cols = [...block.firstElementChild.children];
138
138
  block.classList.add(\`columns-\${cols.length}-cols\`);
@@ -159,7 +159,7 @@ export default function decorate(block) {
159
159
  }
160
160
 
161
161
  .columns img { width: 100%; height: auto; }
162
- `,model:st({definitions:[xn("Columns","columns","columns")],models:[{id:"columns",fields:[{component:"richtext",valueType:"string",name:"content",value:"",label:"Content"}]}],filters:[]})},{id:"accordion",title:"Accordion",js:`// Block: accordion
162
+ `,model:at({definitions:[$n("Columns","columns","columns")],models:[{id:"columns",fields:[{component:"richtext",valueType:"string",name:"content",value:"",label:"Content"}]}],filters:[]})},{id:"accordion",title:"Accordion",js:`// Block: accordion
163
163
  export default function decorate(block) {
164
164
  [...block.children].forEach((row) => {
165
165
  const [label, body] = row.children;
@@ -192,7 +192,7 @@ export default function decorate(block) {
192
192
  .accordion .accordion-item-body {
193
193
  padding-bottom: var(--spacing-m, 16px);
194
194
  }
195
- `,model:st({definitions:[Oi("Accordion","accordion","accordion"),Ni("Accordion Item","accordion-item","accordion-item")],models:[{id:"accordion-item",fields:[{component:"text",valueType:"string",name:"label",label:"Label"},{component:"richtext",valueType:"string",name:"body",value:"",label:"Body"}]}],filters:[{id:"accordion",components:["accordion-item"]}]})},{id:"embed",title:"Embed",js:`// Block: embed
195
+ `,model:at({definitions:[Ui("Accordion","accordion","accordion"),Bi("Accordion Item","accordion-item","accordion-item")],models:[{id:"accordion-item",fields:[{component:"text",valueType:"string",name:"label",label:"Label"},{component:"richtext",valueType:"string",name:"body",value:"",label:"Body"}]}],filters:[{id:"accordion",components:["accordion-item"]}]})},{id:"embed",title:"Embed",js:`// Block: embed
196
196
  export default function decorate(block) {
197
197
  const link = block.querySelector('a');
198
198
  const url = link?.href;
@@ -221,12 +221,12 @@ export default function decorate(block) {
221
221
  height: 100%;
222
222
  border: 0;
223
223
  }
224
- `,model:st({definitions:[xn("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as oc}from"fs";import{mkdir as ic,writeFile as rc}from"fs/promises";import Mi from"path";function _i(e){return ct.find(t=>t.id===e)}function Ui(e){let t=new Set,n=o=>{if(t.has(o))return;let i=_i(o);if(i){for(let a of i.deps??[])n(a);t.add(o)}};for(let o of e)n(o);return ct.filter(o=>t.has(o.id)).map(o=>o.id)}function ac(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
224
+ `,model:at({definitions:[$n("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as uc}from"fs";import{mkdir as fc,writeFile as gc}from"fs/promises";import Hi from"path";function zi(e){return st.find(t=>t.id===e)}function Wi(e){let t=new Set,n=o=>{if(t.has(o))return;let i=zi(o);if(i){for(let a of i.deps??[])n(a);t.add(o)}};for(let o of e)n(o);return st.filter(o=>t.has(o.id)).map(o=>o.id)}function hc(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
225
225
 
226
- ${Ui(e).map(o=>_i(o)).filter(o=>!!o).map(o=>o.code).join(`
226
+ ${Wi(e).map(o=>zi(o)).filter(o=>!!o).map(o=>o.code).join(`
227
227
 
228
228
  `)}
229
- `}async function Bi(e,t=jn){let n=Ui(t),o=Mi.join(e,"scripts","utils.js");return oc(o)?{path:Ii,created:!1,helpers:n}:(await ic(Mi.dirname(o),{recursive:!0}),await rc(o,ac(t)),{path:Ii,created:!0,helpers:n})}var Ii,ct,jn,Hi=v(()=>{"use strict";f();Ii="scripts/utils.js",ct=[{id:"getMetadata",label:"getMetadata (read a page meta value)",code:`/**
229
+ `}async function Ji(e,t=Pn){let n=Wi(t),o=Hi.join(e,"scripts","utils.js");return uc(o)?{path:Gi,created:!1,helpers:n}:(await fc(Hi.dirname(o),{recursive:!0}),await gc(o,hc(t)),{path:Gi,created:!0,helpers:n})}var Gi,st,Pn,qi=k(()=>{"use strict";f();Gi="scripts/utils.js",st=[{id:"getMetadata",label:"getMetadata (read a page meta value)",code:`/**
230
230
  * Reads a page metadata value by name (meta[name] or meta[property]).
231
231
  * @param {string} name The metadata name.
232
232
  * @returns {string} The value, or an empty string.
@@ -323,8 +323,8 @@ export function isUEPreview() {
323
323
  */
324
324
  export function isUE() {
325
325
  return isUEEdit() || isUEPreview();
326
- }`}],jn=ct.map(e=>e.id)});function sc(){return[{component:"tab",name:"basics",label:"Basics"},{component:"text",valueType:"string",name:"text",label:"Text (single line)"},{component:"textarea",valueType:"string",name:"textarea",label:"Textarea (multi-line)"},{component:"richtext",valueType:"string",name:"richtext",value:"",label:"Rich text"},{component:"number",valueType:"number",name:"number",label:"Number"},{component:"boolean",valueType:"boolean",name:"boolean",value:!1,label:"Boolean"},{component:"date-time",valueType:"date",name:"date",label:"Date / time"},{component:"tab",name:"selection",label:"Selection"},{component:"select",valueType:"string",name:"select",label:"Select",value:"a",options:[{name:"Option A",value:"a"},{name:"Option B",value:"b"}]},{component:"radio-group",valueType:"string",name:"radio",label:"Radio group",value:"x",options:[{name:"X",value:"x"},{name:"Y",value:"y"}]},{component:"multiselect",valueType:"string",name:"classes",label:"Multiselect (CSS classes)",options:[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"}]},{component:"checkbox-group",valueType:"string[]",name:"toggles",label:"Checkbox group",options:[{name:"Show title",value:"show-title"},{name:"Show image",value:"show-image"}]},{component:"tab",name:"media",label:"Media & content"},{component:"reference",valueType:"string",name:"image",label:"Image (DAM asset)"},{component:"text",valueType:"string",name:"imageAlt",label:"Image alt"},{component:"aem-content",name:"link",label:"Link (page / URL)"},{component:"aem-content-fragment",name:"contentFragment",label:"Content Fragment"},{component:"aem-experience-fragment",name:"experienceFragment",label:"Experience Fragment"},{component:"aem-tag",valueType:"string",name:"tags",label:"Tags"},{component:"tab",name:"repeatable",label:"Multifield"},{component:"container",name:"items",label:"Items (repeatable)",multi:!0,collapsible:!0,fields:[{component:"text",valueType:"string",name:"itemTitle",label:"Title"},{component:"richtext",valueType:"string",name:"itemText",value:"",label:"Text"},{component:"aem-content",name:"itemLink",label:"Link"}]}]}function Pn(){let e={definitions:[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],models:[{id:"field-reference",fields:sc()}],filters:[]};return`${JSON.stringify(e,null,2)}
327
- `}function En(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function qi(e,t,n){let o=e?.groups?[...e.groups]:[],i=(a,s,d)=>{let l=o.find(c=>c.id===a);l||(l={id:a,title:s,components:[]},o.push(l)),l.components=En(l.components,d)};return i("default","Default Content",t),i("blocks","Blocks",n),{groups:o}}function lt(e,t){let n=e?[...e]:[],o=n.find(i=>i.id==="section");return o||(o={id:"section",components:["text","image","button","title"]},n.push(o)),o.components=[...new Set([...o.components,...t])],n}var Gi,zi,Wi,Ji,Cn=v(()=>{"use strict";f();Gi=[{title:"Text",id:"text",plugins:{xwalk:{page:{resourceType:"core/franklin/components/text/v1/text",template:{text:"<p>Text</p>"}}}}},{title:"Image",id:"image",plugins:{xwalk:{page:{resourceType:"core/franklin/components/image/v1/image",template:{image:"",imageAlt:""}}}}},{title:"Button",id:"button",plugins:{xwalk:{page:{resourceType:"core/franklin/components/button/v1/button",template:{text:"Button",href:"",type:""}}}}},{title:"Title",id:"title",plugins:{xwalk:{page:{resourceType:"core/franklin/components/title/v1/title",template:{title:"Title",type:"h2"}}}}}],zi=[{id:"title",fields:[{component:"text",valueType:"string",name:"title",label:"Title"},{component:"select",valueType:"string",name:"type",label:"Type",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}]}]},{id:"image",fields:[{component:"reference",valueType:"string",name:"image",label:"Image",multi:!1},{component:"text",valueType:"string",name:"imageAlt",label:"Alt Text"}]},{id:"button",fields:[{component:"text",valueType:"string",name:"text",label:"Text"},{component:"aem-content",name:"href",label:"Link"},{component:"select",valueType:"string",name:"type",label:"Type",options:[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}]}]}];Wi=`// Block: field-reference
326
+ }`}],Pn=st.map(e=>e.id)});function wc(){return[{component:"tab",name:"basics",label:"Basics"},{component:"text",valueType:"string",name:"text",label:"Text (single line)"},{component:"textarea",valueType:"string",name:"textarea",label:"Textarea (multi-line)"},{component:"richtext",valueType:"string",name:"richtext",value:"",label:"Rich text"},{component:"number",valueType:"number",name:"number",label:"Number"},{component:"boolean",valueType:"boolean",name:"boolean",value:!1,label:"Boolean"},{component:"date-time",valueType:"date",name:"date",label:"Date / time"},{component:"tab",name:"selection",label:"Selection"},{component:"select",valueType:"string",name:"select",label:"Select",value:"a",options:[{name:"Option A",value:"a"},{name:"Option B",value:"b"}]},{component:"radio-group",valueType:"string",name:"radio",label:"Radio group",value:"x",options:[{name:"X",value:"x"},{name:"Y",value:"y"}]},{component:"multiselect",valueType:"string",name:"classes",label:"Multiselect (CSS classes)",options:[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"}]},{component:"checkbox-group",valueType:"string[]",name:"toggles",label:"Checkbox group",options:[{name:"Show title",value:"show-title"},{name:"Show image",value:"show-image"}]},{component:"tab",name:"media",label:"Media & content"},{component:"reference",valueType:"string",name:"image",label:"Image (DAM asset)"},{component:"text",valueType:"string",name:"imageAlt",label:"Image alt"},{component:"aem-content",name:"link",label:"Link (page / URL)"},{component:"aem-content-fragment",name:"contentFragment",label:"Content Fragment"},{component:"aem-experience-fragment",name:"experienceFragment",label:"Experience Fragment"},{component:"aem-tag",valueType:"string",name:"tags",label:"Tags"},{component:"tab",name:"repeatable",label:"Multifield"},{component:"container",name:"items",label:"Items (repeatable)",multi:!0,collapsible:!0,fields:[{component:"text",valueType:"string",name:"itemTitle",label:"Title"},{component:"richtext",valueType:"string",name:"itemText",value:"",label:"Text"},{component:"aem-content",name:"itemLink",label:"Link"}]}]}function En(){let e={definitions:[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],models:[{id:"field-reference",fields:wc()}],filters:[]};return`${JSON.stringify(e,null,2)}
327
+ `}function Cn(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function Qi(e,t,n){let o=e?.groups?[...e.groups]:[],i=(a,s,d)=>{let l=o.find(c=>c.id===a);l||(l={id:a,title:s,components:[]},o.push(l)),l.components=Cn(l.components,d)};return i("default","Default Content",t),i("blocks","Blocks",n),{groups:o}}function ct(e,t){let n=e?[...e]:[],o=n.find(i=>i.id==="section");return o||(o={id:"section",components:["text","image","button","title"]},n.push(o)),o.components=[...new Set([...o.components,...t])],n}var Ki,Xi,Vi,Yi,An=k(()=>{"use strict";f();Ki=[{title:"Text",id:"text",plugins:{xwalk:{page:{resourceType:"core/franklin/components/text/v1/text",template:{text:"<p>Text</p>"}}}}},{title:"Image",id:"image",plugins:{xwalk:{page:{resourceType:"core/franklin/components/image/v1/image",template:{image:"",imageAlt:""}}}}},{title:"Button",id:"button",plugins:{xwalk:{page:{resourceType:"core/franklin/components/button/v1/button",template:{text:"Button",href:"",type:""}}}}},{title:"Title",id:"title",plugins:{xwalk:{page:{resourceType:"core/franklin/components/title/v1/title",template:{title:"Title",type:"h2"}}}}}],Xi=[{id:"title",fields:[{component:"text",valueType:"string",name:"title",label:"Title"},{component:"select",valueType:"string",name:"type",label:"Type",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}]}]},{id:"image",fields:[{component:"reference",valueType:"string",name:"image",label:"Image",multi:!1},{component:"text",valueType:"string",name:"imageAlt",label:"Alt Text"}]},{id:"button",fields:[{component:"text",valueType:"string",name:"text",label:"Text"},{component:"aem-content",name:"href",label:"Link"},{component:"select",valueType:"string",name:"type",label:"Type",options:[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}]}]}];Vi=`// Block: field-reference
328
328
  // A living reference of every Universal Editor field type (see _field-reference.json).
329
329
  // Authors use it to see what's available; delete it before launch.
330
330
  export default function decorate(block) {
@@ -333,29 +333,29 @@ export default function decorate(block) {
333
333
  // are what you drop and edit.
334
334
  block.classList.add('field-reference');
335
335
  }
336
- `,Ji=`/* Block: field-reference */
336
+ `,Yi=`/* Block: field-reference */
337
337
  .field-reference {
338
338
  display: grid;
339
339
  gap: var(--spacing-m, 16px);
340
340
  padding: var(--spacing-l, 32px) 0;
341
341
  }
342
- `});var le={};L(le,{scaffoldBlocks:()=>Vi,scaffoldCi:()=>Yi,scaffoldEnv:()=>Zi,scaffoldHelpers:()=>Qi,scaffoldInteractive:()=>lc,scaffoldUe:()=>Gt,scaffoldXwalk:()=>er});import{existsSync as Ki}from"fs";import{mkdir as Xi,readFile as cc,writeFile as Ee}from"fs/promises";import ne from"path";async function Bt(e){if(!Ki(e))return null;try{return JSON.parse(await cc(e,"utf-8"))}catch{return null}}async function Ht(e,t){await Ee(e,`${JSON.stringify(t,null,2)}
343
- `)}async function Gt(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - Universal Editor"));let t=[],n=ne.join(e,"blocks","field-reference");await Xi(n,{recursive:!0}),await Ee(ne.join(n,"field-reference.js"),Wi),await Ee(ne.join(n,"field-reference.css"),Ji),await Ee(ne.join(n,"_field-reference.json"),Pn()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=ne.join(e,"component-definition.json"),i=ne.join(e,"component-models.json"),a=ne.join(e,"component-filters.json"),s=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],d=qi(await Bt(o),Gi,s);await Ht(o,d),t.push("component-definition.json (default content + field-reference)");let l=await Bt(i)??[],c=JSON.parse(Pn()).models[0],p=En(l,[...zi,c]);await Ht(i,p),t.push("component-models.json (title / image / button / field-reference)");let m=lt(await Bt(a),["field-reference"]);await Ht(a,m),t.push("component-filters.json (section filter)"),r.info(S("Created / merged"));let u=t.map(w=>w.split(" ")[0]),g=M(u);for(let w of t){let[y,...h]=w.split(" ");r.info(j(y,h.join(" ").replace(/^\((.*)\)$/,"$1"),g))}r.info(""),r.info(O(["Universal Editor scaffold ready"]))}async function Vi(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(c=>$n(c.trim())).filter(c=>!!c);let l=e.filter(c=>!$n(c.trim()));l.length&&r.warn(`Unknown block(s): ${l.join(", ")}. Available: ${Pe.map(c=>c.id).join(", ")}`)}else n=Pe;let o=[],i=[];for(let l of n){let c=ne.join(t,"blocks",l.id);if(Ki(c)){i.push(l.id);continue}await Xi(c,{recursive:!0}),await Ee(ne.join(c,`${l.id}.js`),l.js),await Ee(ne.join(c,`${l.id}.css`),l.css),await Ee(ne.join(c,`_${l.id}.json`),l.model),o.push(l.id)}let a=ne.join(t,"component-filters.json"),s=lt(await Bt(a),n.map(l=>l.id));await Ht(a,s),r.info(S("Blocks"));let d=M([...o,...i,"component-filters"]);for(let l of o)r.info(j(l,"created",d));for(let l of i)r.info(A("warn",l,"already exists \u2014 skipped",d));r.info(""),r.info(O([`${o.length} block(s) scaffolded + registered`]))}async function Yi(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - CI workflow"));let t=await Nt(e);r.info(S("GitHub Actions")),t.created?r.info(j(t.path,"doctor + audit loading + audit security + lint/build")):r.info(A("warn",t.path,"already exists - skipped")),r.info(""),r.info(O([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function Qi(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:i}=await Promise.resolve().then(()=>(G(),H));n=await i({message:"Which helpers?",choices:ct.map(a=>({name:a.label,value:a.id,checked:!0}))})}else n=jn;if(!n.length){r.info("Nothing selected.");return}let o=await Bi(t,n);r.info(S("Helpers")),o.created?r.info(j(o.path,o.helpers.join(", "))):r.info(A("warn",o.path,"already exists - skipped")),r.info(""),r.info(O([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function Zi(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:s}=await import("execa"),d=await s("git",["remote","get-url","origin"],{cwd:t}),l=He(d.stdout.trim());n=l?`https://${Ge(l.owner,l.repo)}`:""}catch{n=""}let o=e.open??"/",i=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:s}=await Promise.resolve().then(()=>(G(),H));o=await s({message:"AEM_OPEN (path opened on start)",default:o}),i=await s({message:"AEM_PORT",default:String(i)}),n=await s({message:"AEM_PAGES_URL (content origin)",default:n})}let a=await Mt(t,{open:o,port:i,pagesUrl:n});r.info(S(".env")),a.created?r.info(j(a.path,`AEM_OPEN=${o} AEM_PORT=${i}`)):r.info(A("warn",a.path,"already exists - left untouched")),a.gitignoreUpdated&&r.info(j(".gitignore","added .env")),r.info(""),r.info(O([a.created?".env ready for `aem up`":".env left untouched"]))}async function er(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Scaffold - xwalk.json"));let t=await _t(e);r.info(S("xwalk.json")),t.created?r.info(j(t.path,"multi-field enabled")):r.info(A("warn",t.path,"already exists - left untouched")),r.info(""),r.info(O([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function lc(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(E("Scaffold"));let n=await e({message:"What do you want to scaffold?",choices:[{name:"Universal Editor config + field-reference (all 17 field types)",value:"ue"},{name:"Standard blocks (hero, cards, columns, accordion, embed)",value:"blocks"},{name:"GitHub Actions CI (doctor + audits + lint/build)",value:"ci"},{name:"Helper functions (scripts/utils.js)",value:"helpers"},{name:"Local-dev .env (aem up: port / open / pages URL)",value:"env"},{name:"xwalk.json (enable Universal Editor multi-field)",value:"xwalk"},{name:"UE config + standard blocks",value:"both"}]});if(n==="env")return Zi();if(n==="xwalk")return er();if((n==="ue"||n==="both")&&await Gt(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:Pe.map(i=>({name:i.title,value:i.id,checked:!0}))});await Vi(o)}n==="ci"&&await Yi(),n==="helpers"&&await Qi()}var ae=v(()=>{"use strict";f();R();B();Sn();yn();vn();Hi();Cn();kn();Ut();N()});var Wt={};L(Wt,{initProject:()=>fc});import{existsSync as Tn}from"fs";import{readFile as Rn,writeFile as tr}from"fs/promises";import zt from"path";import An from"chalk";async function dc(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=He(n.stdout.trim());return o?`https://${Ge(o.owner,o.repo)}`:""}catch{return""}}async function pc(e,t){let n=zt.join(e,"package.json");if(!Tn(n))return!1;try{let o=JSON.parse(await Rn(n,"utf-8"));return o.name=t,await tr(n,`${JSON.stringify(o,null,2)}
344
- `),!0}catch{return!1}}async function mc(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let i=zt.join(e,o);if(Tn(i))try{let a=await Rn(i,"utf-8"),s=a.replace(/aem-boilerplate/gi,t);s!==a&&(await tr(i,s),n.push(o))}catch{}}return n}async function uc(e){let{confirm:t}=await Promise.resolve().then(()=>(G(),H)),n=[{title:"Install the AEM Code Sync GitHub app",url:"https://github.com/apps/aem-code-sync/installations/new",note:"Connects your repo to the Edge Delivery pipeline (preview/publish)."}];e==="gdrive"&&n.push({title:"Share your content folder",note:"Share the Google Drive folder with the AEM service and set it as the mountpoint."}),e==="sharepoint"&&n.push({title:"Share your content folder",note:"Grant the SharePoint/OneDrive folder to the AEM service account."}),e==="da"&&n.push({title:"Author in DA",url:"https://da.live",note:"Create documents at da.live."}),e==="ue"&&n.push({title:"Open the Universal Editor",url:"https://experience.adobe.com",note:"Author in-context once the repo is connected to AEM."}),n.push({title:"Install the AEM Sidekick extension",url:"https://chromewebstore.google.com/detail/aem-sidekick/igkmdomcgoebiipaifhmpfjhbjccggml",note:"Preview and publish from the browser."}),n.push({title:"Run the local dev server",note:"npm install, then `aem up` (from @adobe/aem-cli)."}),r.info(S("Next steps (outside the repo)"));for(let o=0;o<n.length;o++){let i=n[o];r.info(` ${_.accent(String(o+1))} ${An.bold(i.title)}`),i.url&&r.info(` ${An.cyan(i.url)}`),r.info(` ${An.dim(i.note)}`),await t({message:" Done / skip?",default:!0})}}async function fc(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found). Clone an EDS boilerplate first, then run this from its root."),process.exitCode=1;return}await r.logoOnceAnimated("Project setup");let{input:n,select:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!e.yes,s=zt.basename(t),d=zt.join(t,"package.json");if(Tn(d))try{s=JSON.parse(await Rn(d,"utf-8")).name||s}catch{}let l=e.name&&dt(e.name)||dt(await n({message:"1/4 Project name",default:dt(s),validate:y=>!!dt(y)||"Use letters, numbers and dashes"})),c=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:je.ue,value:"ue"},{name:je.da,value:"da"},{name:je.gdrive,value:"gdrive"},{name:je.sharepoint,value:"sharepoint"}]}),p=e.mountpoint;if(It(c)&&!p)if(c==="da"&&(e.org||a)){let y=e.org??await n({message:" DA org",validate:$=>!!$.trim()||"Required"}),h=e.site??(a?await n({message:" DA site",default:l}):l);p=Ti(y.trim(),dt(h))}else c!=="da"&&a&&(p=(await n({message:` ${c==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:h=>/^https?:\/\//.test(h.trim())||"Paste the folder URL"})).trim());let m=e.ci??(a?await i({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);r.info(S("Summary"));let u=M(["name","authoring","mountpoint","ci"]);if(r.info(j("name",l,u)),r.info(j("authoring",je[c],u)),p?r.info(j("mountpoint",p,u)):It(c)&&r.info(j("mountpoint","(skipped - set it in fstab.yaml later)",u)),r.info(j("ci",m?"yes":"no",u)),r.info(""),a&&!await i({message:"Apply this setup?",default:!0})){r.info("Cancelled.");return}let g=[];await pc(t,l)&&g.push("package.json (name)");for(let y of await mc(t,l))g.push(`${y} (renamed)`);if(It(c)&&p&&g.push(await Ri(t,p)),c==="ue"&&(await Gt(),g.push(await Fi(t,l))),m){let y=await Nt(t);g.push(y.created?y.path:`${y.path} (exists, skipped)`)}if(e.env!==!1){let y=await Mt(t,{pagesUrl:await dc(t)});g.push(y.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&c==="ue"){let y=await _t(t);g.push(y.created?`${y.path} (UE multi-field)`:`${y.path} (exists, skipped)`)}r.info(S("Configured"));let w=M(g.map(y=>y.split(" ")[0]));for(let y of g){let[h,...$]=y.split(" ");r.info(j(h,$.join(" ").replace(/^\((.*)\)$/,"$1"),w))}r.info(""),a&&await uc(c),r.info(O([`"${l}" set up for ${je[c]}`]))}var dt,Jt=v(()=>{"use strict";f();R();B();yn();vn();Di();kn();Ut();N();ae();dt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var Ce={};L(Ce,{sandboxList:()=>kc,sandboxLogin:()=>bc,sandboxLogout:()=>yc,sandboxNew:()=>vc,sandboxRm:()=>xc});import gc from"path";import Z from"chalk";async function de(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function Fn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await de(t,[e],{stdio:"ignore"})}catch{}}async function hc(){try{return await de("gh",["auth","status"]),await de("gh",["api","user","-q",".login"])}catch{return null}}async function Dn(){let e=await ui();if(e)try{return{mode:"api",token:e,login:await Dt(e)}}catch{}let t=await hc();return t?{mode:"gh",login:t}:null}async function wc(e,t,n){if(e.mode==="api")return ii(e.token,t,n);try{return await de("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function Ln(){r.error("Not authenticated with GitHub."),r.info(" Run `eds sandbox login` to authorize GitHub, or install + `gh auth login`."),process.exitCode=1}async function bc(){await r.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(G(),H));if(Lt){let n=await gi(["repo","delete_repo"]);r.info(S("Authorize GitHub")),r.info(j("code",n.user_code)),r.info(j("open",n.verification_uri)),r.info(""),await Fn(n.verification_uri),r.info(Z.dim(" Waiting for you to authorize in the browser..."));try{let o=await hi(n.device_code,n.interval,n.expires_in);await gn(o),r.success(`Authorized as ${await Dt(o)}.`)}catch(o){r.error(`Device flow failed: ${o.message}`),process.exitCode=1}return}r.info(S("Authorize GitHub (least-privilege token)")),r.info(" Create a fine-grained token limited to your sandboxes only:"),r.info(` ${Z.cyan("https://github.com/settings/personal-access-tokens/new")}`),r.info(Z.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),r.info(Z.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),r.info(Z.dim(" or Only select repositories to manage existing ones")),r.info(Z.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),r.info(Z.dim(" Metadata = Read. Set a short expiry.")),r.info(Z.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),r.info(""),await(await Promise.resolve().then(()=>(G(),H))).confirm({message:"Open the token page?",default:!0})&&await Fn("https://github.com/settings/personal-access-tokens/new");let t=(await e({message:"Paste the token",validate:n=>!!n.trim()||"Required"})).trim();try{let n=await Dt(t);await gn(t),r.success(`Authorized as ${n}.`)}catch{r.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function yc(){await fi(),r.success("Signed out (stored GitHub token removed).")}async function vc(e,t={}){let n=await Dn();if(!n)return Ln();await r.logoOnceAnimated("Sandbox");let o=!t.yes,{select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=t.boilerplate;s||(t.ue?s=rt.ue:o?s=await i({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:rt.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:rt.ue}]}):s=rt.document);let d=t.private??!1;t.private===void 0&&o&&(d=await i({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let l=t.org??n.login;if(await wc(n,l,e)){r.error(`A repository ${l}/${e} already exists - refusing to touch it.`),r.info(Z.dim(" Pick another name, or remove it first (e.g. `eds sandbox rm` for a sandbox).")),process.exitCode=1;return}r.info(S("Creating sandbox",`${l}/${e} \xB7 ${s}`));try{if(n.mode==="api"){let c=await ri(n.token,s,{owner:l,name:e,private:d});await ai(n.token,l,e,[Ue]),r.info(Z.dim(" Cloning...")),await de("git",["clone",c.cloneUrl,e],{stdio:"inherit"})}else{let c=t.org?`${t.org}/${e}`:e;await de("gh",bi(c,{template:s,private:d,clone:!0}),{stdio:"inherit"});try{await de("gh",["repo","edit",`${l}/${e}`,"--add-topic",Ue])}catch{}}}catch(c){r.error(`Create failed: ${c.message}`),process.exitCode=1;return}if(r.info(""),r.info(S("Sandbox ready")),r.info(j("repo",`https://github.com/${l}/${e}`)),r.info(j("preview",hn(l,e))),r.info(""),o){if(await a({message:"Open the AEM Code Sync install page now?",default:!0})&&await Fn(wn()),await a({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let c=process.cwd();try{process.chdir(gc.join(c,e));let{initProject:p}=await Promise.resolve().then(()=>(Jt(),Wt));await p({})}finally{process.chdir(c)}}}else r.info(Z.dim(` Install AEM Code Sync: ${wn()}`)),r.info(Z.dim(` Configure authoring: cd ${e} && eds init`));r.info(""),r.info(O([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function kc(){let e=await Dn();if(!e)return Ln();let t=[];try{if(e.mode==="api")t=await ci(e.token,e.login,Ue);else{let o=await de("gh",["repo","list","--topic",Ue,"--limit","100","--json","nameWithOwner","-q",".[].nameWithOwner"]);t=o?o.split(`
345
- `).filter(Boolean):[]}}catch(o){r.error(`List failed: ${o.message}`),process.exitCode=1;return}if(r.info(S("Sandboxes",`${t.length} tagged ${Ue}`)),t.length===0){r.info(Z.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=M(t);for(let o of t){let[i,a]=o.split("/");r.info(j(o,hn(i,a),n))}}async function xc(e,t={}){let n=await Dn();if(!n)return Ln();let o=t.org??n.login,i=`${o}/${e}`;if(!t.yes){let{confirm:a}=await Promise.resolve().then(()=>(G(),H));if(!await a({message:`Permanently delete ${i}? This cannot be undone.`,default:!1})){r.info("Cancelled.");return}}try{n.mode==="api"?await si(n.token,o,e):await de("gh",["repo","delete",i,"--yes"])}catch(a){r.error(`Delete failed: ${a.message}`),r.info(Z.dim(" Deleting needs the delete_repo scope (re-run `eds sandbox login`, or `gh auth refresh -s delete_repo`).")),process.exitCode=1;return}r.info(S("Deleted")),r.info(j(i,"removed"))}var Ae=v(()=>{"use strict";f();R();li();wi();yi();N()});import{existsSync as $c}from"fs";import{readFile as Sc}from"fs/promises";import jc from"path";import{parse as Pc}from"yaml";async function nr(e){let t=jc.join(e,"fstab.yaml");if($c(t))try{let o=(Pc(await Sc(t,"utf-8"))??{}).mountpoints?.["/"],i=typeof o=="string"?o:o?.url??"",a=i.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return a?{model:"da",org:a[1],site:a[2],mountpoint:i}:/drive\.google\.com/.test(i)?{model:"gdrive",mountpoint:i}:/sharepoint\.com|-my\.sharepoint/.test(i)?{model:"sharepoint",mountpoint:i}:{model:"document",mountpoint:i}}catch{}return{model:"ue"}}var or=v(()=>{"use strict";f()});function Ec(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function ir(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function rr(e,t,n,o,i){let a=Ec(e,t,n),s=new FormData;s.append("data",new Blob([o],{type:"text/html"}),"content.html");let d={};i&&(d.Authorization=`Bearer ${i}`);let l=await fetch(a,{method:"POST",body:s,headers:d});if(!l.ok)throw new Error(`DA push failed: ${l.status} ${l.statusText}`);return a}var ar=v(()=>{"use strict";f()});function Cc(e){return` <div class="${e}">
342
+ `});var me={};O(me,{scaffoldBlocks:()=>tr,scaffoldCi:()=>nr,scaffoldEnv:()=>ir,scaffoldHelpers:()=>or,scaffoldInteractive:()=>yc,scaffoldUe:()=>zt,scaffoldXwalk:()=>rr});import{existsSync as Zi}from"fs";import{mkdir as er,readFile as bc,writeFile as Ae}from"fs/promises";import oe from"path";async function Ht(e){if(!Zi(e))return null;try{return JSON.parse(await bc(e,"utf-8"))}catch{return null}}async function Gt(e,t){await Ae(e,`${JSON.stringify(t,null,2)}
343
+ `)}async function zt(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - Universal Editor"));let t=[],n=oe.join(e,"blocks","field-reference");await er(n,{recursive:!0}),await Ae(oe.join(n,"field-reference.js"),Vi),await Ae(oe.join(n,"field-reference.css"),Yi),await Ae(oe.join(n,"_field-reference.json"),En()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=oe.join(e,"component-definition.json"),i=oe.join(e,"component-models.json"),a=oe.join(e,"component-filters.json"),s=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],d=Qi(await Ht(o),Ki,s);await Gt(o,d),t.push("component-definition.json (default content + field-reference)");let l=await Ht(i)??[],c=JSON.parse(En()).models[0],m=Cn(l,[...Xi,c]);await Gt(i,m),t.push("component-models.json (title / image / button / field-reference)");let p=ct(await Ht(a),["field-reference"]);await Gt(a,p),t.push("component-filters.json (section filter)"),r.info(S("Created / merged"));let u=t.map(h=>h.split(" ")[0]),g=I(u);for(let h of t){let[b,...w]=h.split(" ");r.info(j(b,w.join(" ").replace(/^\((.*)\)$/,"$1"),g))}r.info(""),r.info(N(["Universal Editor scaffold ready"]))}async function tr(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(c=>Sn(c.trim())).filter(c=>!!c);let l=e.filter(c=>!Sn(c.trim()));l.length&&r.warn(`Unknown block(s): ${l.join(", ")}. Available: ${Ce.map(c=>c.id).join(", ")}`)}else n=Ce;let o=[],i=[];for(let l of n){let c=oe.join(t,"blocks",l.id);if(Zi(c)){i.push(l.id);continue}await er(c,{recursive:!0}),await Ae(oe.join(c,`${l.id}.js`),l.js),await Ae(oe.join(c,`${l.id}.css`),l.css),await Ae(oe.join(c,`_${l.id}.json`),l.model),o.push(l.id)}let a=oe.join(t,"component-filters.json"),s=ct(await Ht(a),n.map(l=>l.id));await Gt(a,s),r.info(S("Blocks"));let d=I([...o,...i,"component-filters"]);for(let l of o)r.info(j(l,"created",d));for(let l of i)r.info(A("warn",l,"already exists \u2014 skipped",d));r.info(""),r.info(N([`${o.length} block(s) scaffolded + registered`]))}async function nr(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - CI workflow"));let t=await Mt(e);r.info(S("GitHub Actions")),t.created?r.info(j(t.path,"doctor + audit loading + audit security + lint/build")):r.info(A("warn",t.path,"already exists - skipped")),r.info(""),r.info(N([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function or(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:i}=await Promise.resolve().then(()=>(G(),H));n=await i({message:"Which helpers?",choices:st.map(a=>({name:a.label,value:a.id,checked:!0}))})}else n=Pn;if(!n.length){r.info("Nothing selected.");return}let o=await Ji(t,n);r.info(S("Helpers")),o.created?r.info(j(o.path,o.helpers.join(", "))):r.info(A("warn",o.path,"already exists - skipped")),r.info(""),r.info(N([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function ir(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:s}=await import("execa"),d=await s("git",["remote","get-url","origin"],{cwd:t}),l=He(d.stdout.trim());n=l?`https://${Ge(l.owner,l.repo)}`:""}catch{n=""}let o=e.open??"/",i=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:s}=await Promise.resolve().then(()=>(G(),H));o=await s({message:"AEM_OPEN (path opened on start)",default:o}),i=await s({message:"AEM_PORT",default:String(i)}),n=await s({message:"AEM_PAGES_URL (content origin)",default:n})}let a=await It(t,{open:o,port:i,pagesUrl:n});r.info(S(".env")),a.created?r.info(j(a.path,`AEM_OPEN=${o} AEM_PORT=${i}`)):r.info(A("warn",a.path,"already exists - left untouched")),a.gitignoreUpdated&&r.info(j(".gitignore","added .env")),r.info(""),r.info(N([a.created?".env ready for `aem up`":".env left untouched"]))}async function rr(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - xwalk.json"));let t=await Ut(e);r.info(S("xwalk.json")),t.created?r.info(j(t.path,"multi-field enabled")):r.info(A("warn",t.path,"already exists - left untouched")),r.info(""),r.info(N([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function yc(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(C("Scaffold"));let n=await e({message:"What do you want to scaffold?",choices:[{name:"Universal Editor config + field-reference (all 17 field types)",value:"ue"},{name:"Standard blocks (hero, cards, columns, accordion, embed)",value:"blocks"},{name:"GitHub Actions CI (doctor + audits + lint/build)",value:"ci"},{name:"Helper functions (scripts/utils.js)",value:"helpers"},{name:"Local-dev .env (aem up: port / open / pages URL)",value:"env"},{name:"xwalk.json (enable Universal Editor multi-field)",value:"xwalk"},{name:"UE config + standard blocks",value:"both"}]});if(n==="env")return ir();if(n==="xwalk")return rr();if((n==="ue"||n==="both")&&await zt(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:Ce.map(i=>({name:i.title,value:i.id,checked:!0}))});await tr(o)}n==="ci"&&await nr(),n==="helpers"&&await or()}var ce=k(()=>{"use strict";f();R();z();jn();vn();kn();qi();An();xn();Bt();M()});var Jt={};O(Jt,{initProject:()=>Sc});import{existsSync as Rn}from"fs";import{readFile as Fn,writeFile as ar}from"fs/promises";import Wt from"path";import Tn from"chalk";async function vc(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=He(n.stdout.trim());return o?`https://${Ge(o.owner,o.repo)}`:""}catch{return""}}async function kc(e,t){let n=Wt.join(e,"package.json");if(!Rn(n))return!1;try{let o=JSON.parse(await Fn(n,"utf-8"));return o.name=t,await ar(n,`${JSON.stringify(o,null,2)}
344
+ `),!0}catch{return!1}}async function xc(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let i=Wt.join(e,o);if(Rn(i))try{let a=await Fn(i,"utf-8"),s=a.replace(/aem-boilerplate/gi,t);s!==a&&(await ar(i,s),n.push(o))}catch{}}return n}async function $c(e){let{confirm:t}=await Promise.resolve().then(()=>(G(),H)),n=[{title:"Install the AEM Code Sync GitHub app",url:"https://github.com/apps/aem-code-sync/installations/new",note:"Connects your repo to the Edge Delivery pipeline (preview/publish)."}];e==="gdrive"&&n.push({title:"Share your content folder",note:"Share the Google Drive folder with the AEM service and set it as the mountpoint."}),e==="sharepoint"&&n.push({title:"Share your content folder",note:"Grant the SharePoint/OneDrive folder to the AEM service account."}),e==="da"&&n.push({title:"Author in DA",url:"https://da.live",note:"Create documents at da.live."}),e==="ue"&&n.push({title:"Open the Universal Editor",url:"https://experience.adobe.com",note:"Author in-context once the repo is connected to AEM."}),n.push({title:"Install the AEM Sidekick extension",url:"https://chromewebstore.google.com/detail/aem-sidekick/igkmdomcgoebiipaifhmpfjhbjccggml",note:"Preview and publish from the browser."}),n.push({title:"Run the local dev server",note:"npm install, then `aem up` (from @adobe/aem-cli)."}),r.info(S("Next steps (outside the repo)"));for(let o=0;o<n.length;o++){let i=n[o];r.info(` ${U.accent(String(o+1))} ${Tn.bold(i.title)}`),i.url&&r.info(` ${Tn.cyan(i.url)}`),r.info(` ${Tn.dim(i.note)}`),await t({message:" Done / skip?",default:!0})}}async function Sc(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found). Clone an EDS boilerplate first, then run this from its root."),process.exitCode=1;return}await r.logoOnceAnimated("Project setup");let{input:n,select:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!e.yes,s=Wt.basename(t),d=Wt.join(t,"package.json");if(Rn(d))try{s=JSON.parse(await Fn(d,"utf-8")).name||s}catch{}let l=e.name&&lt(e.name)||lt(await n({message:"1/4 Project name",default:lt(s),validate:b=>!!lt(b)||"Use letters, numbers and dashes"})),c=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:Ee.ue,value:"ue"},{name:Ee.da,value:"da"},{name:Ee.gdrive,value:"gdrive"},{name:Ee.sharepoint,value:"sharepoint"}]}),m=e.mountpoint;if(_t(c)&&!m)if(c==="da"&&(e.org||a)){let b=e.org??await n({message:" DA org",validate:y=>!!y.trim()||"Required"}),w=e.site??(a?await n({message:" DA site",default:l}):l);m=Oi(b.trim(),lt(w))}else c!=="da"&&a&&(m=(await n({message:` ${c==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:w=>/^https?:\/\//.test(w.trim())||"Paste the folder URL"})).trim());let p=e.ci??(a?await i({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);r.info(S("Summary"));let u=I(["name","authoring","mountpoint","ci"]);if(r.info(j("name",l,u)),r.info(j("authoring",Ee[c],u)),m?r.info(j("mountpoint",m,u)):_t(c)&&r.info(j("mountpoint","(skipped - set it in fstab.yaml later)",u)),r.info(j("ci",p?"yes":"no",u)),r.info(""),a&&!await i({message:"Apply this setup?",default:!0})){r.info("Cancelled.");return}let g=[];await kc(t,l)&&g.push("package.json (name)");for(let b of await xc(t,l))g.push(`${b} (renamed)`);if(_t(c)&&m&&g.push(await Ni(t,m)),c==="ue"&&(await zt(),g.push(await Mi(t,l))),p){let b=await Mt(t);g.push(b.created?b.path:`${b.path} (exists, skipped)`)}if(e.env!==!1){let b=await It(t,{pagesUrl:await vc(t)});g.push(b.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&c==="ue"){let b=await Ut(t);g.push(b.created?`${b.path} (UE multi-field)`:`${b.path} (exists, skipped)`)}r.info(S("Configured"));let h=I(g.map(b=>b.split(" ")[0]));for(let b of g){let[w,...y]=b.split(" ");r.info(j(w,y.join(" ").replace(/^\((.*)\)$/,"$1"),h))}r.info(""),a&&await $c(c),r.info(N([`"${l}" set up for ${Ee[c]}`]))}var lt,qt=k(()=>{"use strict";f();R();z();vn();kn();Ii();xn();Bt();M();ce();lt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var Te={};O(Te,{sandboxList:()=>Rc,sandboxLogin:()=>Cc,sandboxLogout:()=>Ac,sandboxNew:()=>Tc,sandboxRm:()=>Fc});import jc from"path";import ee from"chalk";async function pe(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function Dn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await pe(t,[e],{stdio:"ignore"})}catch{}}async function Pc(){try{return await pe("gh",["auth","status"]),await pe("gh",["api","user","-q",".login"])}catch{return null}}async function Ln(){let e=await bi();if(e)try{return{mode:"api",token:e,login:await Lt(e)}}catch{}let t=await Pc();return t?{mode:"gh",login:t}:null}async function Ec(e,t,n){if(e.mode==="api")return li(e.token,t,n);try{return await pe("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function On(){r.error("Not authenticated with GitHub."),r.info(" Run `eds sandbox login` to authorize GitHub, or install + `gh auth login`."),process.exitCode=1}async function Cc(){await r.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(G(),H));if(Ot){let n=await vi(["repo","delete_repo"]);r.info(S("Authorize GitHub")),r.info(j("code",n.user_code)),r.info(j("open",n.verification_uri)),r.info(""),await Dn(n.verification_uri),r.info(ee.dim(" Waiting for you to authorize in the browser..."));try{let o=await ki(n.device_code,n.interval,n.expires_in);await hn(o),r.success(`Authorized as ${await Lt(o)}.`)}catch(o){r.error(`Device flow failed: ${o.message}`),process.exitCode=1}return}r.info(S("Authorize GitHub (least-privilege token)")),r.info(" Create a fine-grained token limited to your sandboxes only:"),r.info(` ${ee.cyan("https://github.com/settings/personal-access-tokens/new")}`),r.info(ee.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),r.info(ee.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),r.info(ee.dim(" or Only select repositories to manage existing ones")),r.info(ee.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),r.info(ee.dim(" Metadata = Read. Set a short expiry.")),r.info(ee.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),r.info(""),await(await Promise.resolve().then(()=>(G(),H))).confirm({message:"Open the token page?",default:!0})&&await Dn("https://github.com/settings/personal-access-tokens/new");let t=(await e({message:"Paste the token",validate:n=>!!n.trim()||"Required"})).trim();try{let n=await Lt(t);await hn(t),r.success(`Authorized as ${n}.`)}catch{r.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function Ac(){await yi(),r.success("Signed out (stored GitHub token removed).")}async function Tc(e,t={}){let n=await Ln();if(!n)return On();await r.logoOnceAnimated("Sandbox");let o=!t.yes,{select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=t.boilerplate;s||(t.ue?s=it.ue:o?s=await i({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:it.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:it.ue}]}):s=it.document);let d=t.private??!1;t.private===void 0&&o&&(d=await i({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let l=t.org??n.login;if(await Ec(n,l,e)){r.error(`A repository ${l}/${e} already exists - refusing to touch it.`),r.info(ee.dim(" Pick another name, or remove it first (e.g. `eds sandbox rm` for a sandbox).")),process.exitCode=1;return}r.info(S("Creating sandbox",`${l}/${e} \xB7 ${s}`));try{if(n.mode==="api"){let c=await di(n.token,s,{owner:l,name:e,private:d});await mi(n.token,l,e,[Ue]),r.info(ee.dim(" Cloning...")),await pe("git",["clone",c.cloneUrl,e],{stdio:"inherit"})}else{let c=t.org?`${t.org}/${e}`:e;await pe("gh",$i(c,{template:s,private:d,clone:!0}),{stdio:"inherit"});try{await pe("gh",["repo","edit",`${l}/${e}`,"--add-topic",Ue])}catch{}}}catch(c){r.error(`Create failed: ${c.message}`),process.exitCode=1;return}if(r.info(""),r.info(S("Sandbox ready")),r.info(j("repo",`https://github.com/${l}/${e}`)),r.info(j("preview",wn(l,e))),r.info(""),o){if(await a({message:"Open the AEM Code Sync install page now?",default:!0})&&await Dn(bn()),await a({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let c=process.cwd();try{process.chdir(jc.join(c,e));let{initProject:m}=await Promise.resolve().then(()=>(qt(),Jt));await m({})}finally{process.chdir(c)}}}else r.info(ee.dim(` Install AEM Code Sync: ${bn()}`)),r.info(ee.dim(` Configure authoring: cd ${e} && eds init`));r.info(""),r.info(N([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function Rc(){let e=await Ln();if(!e)return On();let t=[];try{if(e.mode==="api")t=await ui(e.token,e.login,Ue);else{let o=await pe("gh",["repo","list","--topic",Ue,"--limit","100","--json","nameWithOwner","-q",".[].nameWithOwner"]);t=o?o.split(`
345
+ `).filter(Boolean):[]}}catch(o){r.error(`List failed: ${o.message}`),process.exitCode=1;return}if(r.info(S("Sandboxes",`${t.length} tagged ${Ue}`)),t.length===0){r.info(ee.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=I(t);for(let o of t){let[i,a]=o.split("/");r.info(j(o,wn(i,a),n))}}async function Fc(e,t={}){let n=await Ln();if(!n)return On();let o=t.org??n.login,i=`${o}/${e}`;if(!t.yes){let{confirm:a}=await Promise.resolve().then(()=>(G(),H));if(!await a({message:`Permanently delete ${i}? This cannot be undone.`,default:!1})){r.info("Cancelled.");return}}try{n.mode==="api"?await pi(n.token,o,e):await pe("gh",["repo","delete",i,"--yes"])}catch(a){r.error(`Delete failed: ${a.message}`),r.info(ee.dim(" Deleting needs the delete_repo scope (re-run `eds sandbox login`, or `gh auth refresh -s delete_repo`).")),process.exitCode=1;return}r.info(S("Deleted")),r.info(j(i,"removed"))}var Re=k(()=>{"use strict";f();R();fi();xi();Si();M()});import{existsSync as Dc}from"fs";import{readFile as Lc}from"fs/promises";import Oc from"path";import{parse as Nc}from"yaml";async function sr(e){let t=Oc.join(e,"fstab.yaml");if(Dc(t))try{let o=(Nc(await Lc(t,"utf-8"))??{}).mountpoints?.["/"],i=typeof o=="string"?o:o?.url??"",a=i.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return a?{model:"da",org:a[1],site:a[2],mountpoint:i}:/drive\.google\.com/.test(i)?{model:"gdrive",mountpoint:i}:/sharepoint\.com|-my\.sharepoint/.test(i)?{model:"sharepoint",mountpoint:i}:{model:"document",mountpoint:i}}catch{}return{model:"ue"}}var cr=k(()=>{"use strict";f()});function Mc(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function lr(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function dr(e,t,n,o,i){let a=Mc(e,t,n),s=new FormData;s.append("data",new Blob([o],{type:"text/html"}),"content.html");let d={};i&&(d.Authorization=`Bearer ${i}`);let l=await fetch(a,{method:"POST",body:s,headers:d});if(!l.ok)throw new Error(`DA push failed: ${l.status} ${l.statusText}`);return a}var mr=k(()=>{"use strict";f()});function Ic(e){return` <div class="${e}">
346
346
  <div>
347
347
  <div>${e} content</div>
348
348
  </div>
349
- </div>`}function Ac(e){let t=[` <div><div>Title</div><div>${e.title}</div></div>`,` <div><div>Description</div><div>${e.description??""}</div></div>`];return e.area&&t.push(` <div><div>Template</div><div>${e.area}</div></div>`),` <div class="metadata">
349
+ </div>`}function _c(e){let t=[` <div><div>Title</div><div>${e.title}</div></div>`,` <div><div>Description</div><div>${e.description??""}</div></div>`];return e.area&&t.push(` <div><div>Template</div><div>${e.area}</div></div>`),` <div class="metadata">
350
350
  ${t.join(`
351
351
  `)}
352
- </div>`}function sr(e){let t=e.blocks??[],n=` <div>
352
+ </div>`}function pr(e){let t=e.blocks??[],n=` <div>
353
353
  <h1>${e.title}</h1>
354
354
  <p>${e.description??"Intro copy goes here."}</p>
355
355
  </div>`,o=t.map(a=>` <div>
356
- ${Cc(a)}
356
+ ${Ic(a)}
357
357
  </div>`),i=` <div>
358
- ${Ac(e)}
358
+ ${_c(e)}
359
359
  </div>`;return`<body>
360
360
  <header></header>
361
361
  <main>
@@ -364,13 +364,13 @@ ${[n,...o,i].join(`
364
364
  </main>
365
365
  <footer></footer>
366
366
  </body>
367
- `}var cr=v(()=>{"use strict";f()});import{existsSync as Tc}from"fs";import{readFile as Rc}from"fs/promises";import Fc from"path";function Dc(e){if(e.value!==void 0)return e.value;switch(e.valueType){case"boolean":return!1;case"number":return 0;case"string[]":return[];default:return""}}async function Lc(e,t){let n=Fc.join(e,"blocks",t,`_${t}.json`);if(!Tc(n))return{};try{let o=JSON.parse(await Rc(n,"utf-8")),i=Array.isArray(o.models)?o.models:[],s=(i.find(l=>l.id===t)??i[0])?.fields??[],d={};for(let l of s)l.component!=="tab"&&(d[l.name]=l.component==="container"?[]:Dc(l));return d}catch{return{}}}async function lr(e,t){let n=[];for(let i of t.blocks)n.push({name:i,model:i,fields:await Lc(e,i)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
368
- `}var dr=v(()=>{"use strict";f()});var Mn={};L(Mn,{templateNew:()=>Bc});import{existsSync as Nn}from"fs";import{mkdir as Oc,readFile as pr,readdir as Nc,writeFile as On}from"fs/promises";import he from"path";import pt from"chalk";async function Ic(e){let t=he.join(e,"blocks");return Nn(t)?(await Nc(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function _c(e){let t=he.join(e,".edsrc.json");if(!Nn(t))return{};try{return JSON.parse(await pr(t,"utf-8")).admin??{}}catch{return{}}}async function Uc(e,t){if(!t.length)return!1;let n=he.join(e,"component-filters.json"),o=null;if(Nn(n))try{o=JSON.parse(await pr(n,"utf-8"))}catch{o=null}let i=lt(o,t);return await On(n,`${JSON.stringify(i,null,2)}
369
- `),!0}async function Bc(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Page template");let{input:o,select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=!t.yes,d=await nr(n),l=t.authoring??d.model,c=Mc(e),p=t.title??(s?await o({message:"Page title",default:e}):e),m=t.description??(s?await o({message:"Description (optional)"}):""),u=t.path??`/templates/${c}`,g=t.blocks;if(!g&&s){let $=await Ic(n),b=$.length?$:Pe.map(z=>z.id),T=[],Q=!0;for(;Q;){let z=await i({message:`Add a block in order (${T.length} so far)`,choices:[...b.map(ue=>({name:ue,value:ue})),{name:T.length?"- done -":"- done (empty page) -",value:"__done"}]});z==="__done"?Q=!1:T.push(z)}g=T}let w=g??[],y=sr({title:p,description:m||void 0,blocks:w,area:t.area}),h=he.join("templates",`${c}.html`);if(await Oc(he.join(n,"templates"),{recursive:!0}),await On(he.join(n,h),y),r.info(S("Page template",`${u} \xB7 ${l}`)),r.info(j(h,`${w.length} block(s) + metadata`)),l==="da"){let $=await _c(n),b=t.org??$.org??d.org,T=t.site??$.site??d.site;if(t.push??(s?await a({message:"Push to DA (da.live)?",default:!0}):!0))if(!b||!T)r.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await rr(b,T,u,y,process.env.DA_TOKEN),r.info(j("pushed to DA",ir(b,T,u)))}catch(z){r.error(`DA push failed: ${z.message}`),r.info(pt.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(l==="gdrive"||l==="sharepoint"){let $=l==="gdrive"?"a Google Doc":"a Word doc";r.info(""),r.info(pt.dim(` Document model: import ${h} into ${$} in your mounted folder,`)),r.info(pt.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(l==="ue"){let $=he.join("templates",`${c}.json`);await On(he.join(n,$),await lr(n,{title:p,name:c,blocks:w})),r.info(j($,`initial content (${w.length} component(s), in order)`)),await Uc(n,w)&&r.info(j("component-filters.json","seeded blocks allowed in Universal Editor")),r.info(""),r.info(pt.dim(" Universal Editor: use the template JSON as the page's initial content, then")),r.info(pt.dim(" author it in the Universal Editor (wire the repo to AEM)."))}r.info(""),r.info(O([`"${c}" template (${l}) - preview with \`eds preview ${u}\``]))}var Mc,In=v(()=>{"use strict";f();R();B();Sn();Cn();or();ar();cr();dr();N();Mc=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as qt}from"fs";import{readFile as mr,readdir as ur}from"fs/promises";import Te from"path";async function Hc(e){let t=[],n=async o=>{for(let i of await ur(o,{withFileTypes:!0})){let a=Te.join(o,i.name);i.isDirectory()?await n(a):t.push(a)}};return qt(e)&&await n(e),t}async function fr(e){if(!qt(e))return null;let t=await ur(e,{withFileTypes:!0}),n=t.find(i=>i.isDirectory()&&/clientlib/i.test(i.name));return n?Te.join(e,n.name):t.some(i=>i.isFile()&&i.name.endsWith(".css"))?e:null}async function gr(e){let t=await Hc(e),n=t.filter(s=>/\.(less|scss|sass)$/i.test(s)).map(s=>Te.relative(e,s)),o,i=Te.join(e,"css.txt");if(qt(i)){let s=(await mr(i,"utf-8")).split(`
370
- `).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let p=c.match(/^#base\s*=\s*(.+)$/);p?d=Te.join(e,p[1].trim()):c.startsWith("#")||l.push(c)}o=l.map(c=>Te.join(d,c)).filter(c=>qt(c)&&c.endsWith(".css"))}else o=t.filter(s=>s.endsWith(".css"));let a=[];for(let s of o)a.push(await mr(s,"utf-8"));return{css:a.join(`
367
+ `}var ur=k(()=>{"use strict";f()});import{existsSync as Uc}from"fs";import{readFile as Bc}from"fs/promises";import Hc from"path";function Gc(e){if(e.value!==void 0)return e.value;switch(e.valueType){case"boolean":return!1;case"number":return 0;case"string[]":return[];default:return""}}async function zc(e,t){let n=Hc.join(e,"blocks",t,`_${t}.json`);if(!Uc(n))return{};try{let o=JSON.parse(await Bc(n,"utf-8")),i=Array.isArray(o.models)?o.models:[],s=(i.find(l=>l.id===t)??i[0])?.fields??[],d={};for(let l of s)l.component!=="tab"&&(d[l.name]=l.component==="container"?[]:Gc(l));return d}catch{return{}}}async function fr(e,t){let n=[];for(let i of t.blocks)n.push({name:i,model:i,fields:await zc(e,i)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
368
+ `}var gr=k(()=>{"use strict";f()});var In={};O(In,{templateNew:()=>Yc});import{existsSync as Mn}from"fs";import{mkdir as Wc,readFile as hr,readdir as Jc,writeFile as Nn}from"fs/promises";import we from"path";import dt from"chalk";async function Kc(e){let t=we.join(e,"blocks");return Mn(t)?(await Jc(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function Xc(e){let t=we.join(e,".edsrc.json");if(!Mn(t))return{};try{return JSON.parse(await hr(t,"utf-8")).admin??{}}catch{return{}}}async function Vc(e,t){if(!t.length)return!1;let n=we.join(e,"component-filters.json"),o=null;if(Mn(n))try{o=JSON.parse(await hr(n,"utf-8"))}catch{o=null}let i=ct(o,t);return await Nn(n,`${JSON.stringify(i,null,2)}
369
+ `),!0}async function Yc(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Page template");let{input:o,select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=!t.yes,d=await sr(n),l=t.authoring??d.model,c=qc(e),m=t.title??(s?await o({message:"Page title",default:e}):e),p=t.description??(s?await o({message:"Description (optional)"}):""),u=t.path??`/templates/${c}`,g=t.blocks;if(!g&&s){let y=await Kc(n),v=y.length?y:Ce.map(J=>J.id),T=[],K=!0;for(;K;){let J=await i({message:`Add a block in order (${T.length} so far)`,choices:[...v.map(Se=>({name:Se,value:Se})),{name:T.length?"- done -":"- done (empty page) -",value:"__done"}]});J==="__done"?K=!1:T.push(J)}g=T}let h=g??[],b=pr({title:m,description:p||void 0,blocks:h,area:t.area}),w=we.join("templates",`${c}.html`);if(await Wc(we.join(n,"templates"),{recursive:!0}),await Nn(we.join(n,w),b),r.info(S("Page template",`${u} \xB7 ${l}`)),r.info(j(w,`${h.length} block(s) + metadata`)),l==="da"){let y=await Xc(n),v=t.org??y.org??d.org,T=t.site??y.site??d.site;if(t.push??(s?await a({message:"Push to DA (da.live)?",default:!0}):!0))if(!v||!T)r.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await dr(v,T,u,b,process.env.DA_TOKEN),r.info(j("pushed to DA",lr(v,T,u)))}catch(J){r.error(`DA push failed: ${J.message}`),r.info(dt.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(l==="gdrive"||l==="sharepoint"){let y=l==="gdrive"?"a Google Doc":"a Word doc";r.info(""),r.info(dt.dim(` Document model: import ${w} into ${y} in your mounted folder,`)),r.info(dt.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(l==="ue"){let y=we.join("templates",`${c}.json`);await Nn(we.join(n,y),await fr(n,{title:m,name:c,blocks:h})),r.info(j(y,`initial content (${h.length} component(s), in order)`)),await Vc(n,h)&&r.info(j("component-filters.json","seeded blocks allowed in Universal Editor")),r.info(""),r.info(dt.dim(" Universal Editor: use the template JSON as the page's initial content, then")),r.info(dt.dim(" author it in the Universal Editor (wire the repo to AEM)."))}r.info(""),r.info(N([`"${c}" template (${l}) - preview with \`eds preview ${u}\``]))}var qc,_n=k(()=>{"use strict";f();R();z();jn();An();cr();mr();ur();gr();M();qc=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as Kt}from"fs";import{readFile as wr,readdir as br}from"fs/promises";import Fe from"path";async function Qc(e){let t=[],n=async o=>{for(let i of await br(o,{withFileTypes:!0})){let a=Fe.join(o,i.name);i.isDirectory()?await n(a):t.push(a)}};return Kt(e)&&await n(e),t}async function yr(e){if(!Kt(e))return null;let t=await br(e,{withFileTypes:!0}),n=t.find(i=>i.isDirectory()&&/clientlib/i.test(i.name));return n?Fe.join(e,n.name):t.some(i=>i.isFile()&&i.name.endsWith(".css"))?e:null}async function vr(e){let t=await Qc(e),n=t.filter(s=>/\.(less|scss|sass)$/i.test(s)).map(s=>Fe.relative(e,s)),o,i=Fe.join(e,"css.txt");if(Kt(i)){let s=(await wr(i,"utf-8")).split(`
370
+ `).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let m=c.match(/^#base\s*=\s*(.+)$/);m?d=Fe.join(e,m[1].trim()):c.startsWith("#")||l.push(c)}o=l.map(c=>Fe.join(d,c)).filter(c=>Kt(c)&&c.endsWith(".css"))}else o=t.filter(s=>s.endsWith(".css"));let a=[];for(let s of o)a.push(await wr(s,"utf-8"));return{css:a.join(`
371
371
 
372
- `),files:o.map(s=>Te.relative(e,s)),preprocessed:n}}var hr=v(()=>{"use strict";f()});import{XMLParser as Gc}from"fast-xml-parser";function mt(e){return Object.keys(e).find(t=>t!==":@")??""}function we(e){let t=mt(e),n=e[t];return Array.isArray(n)?n:[]}function zc(e){return e[":@"]??{}}function Wc(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function V(e,t){return Wc(zc(e)[`@_${t}`])}function Jc(e,t){let n=V(t,"multiple")==="true"||V(t,"multiple")==="{Boolean}true";return e.endsWith("/form/textfield")?"text":e.endsWith("/form/textarea")?"textarea":e.includes("/richtext")?"richtext":e.endsWith("/form/numberfield")?"number":e.endsWith("/form/checkbox")?"boolean":e.endsWith("/form/radiogroup")?"radio-group":e.endsWith("/form/select")?n?"multiselect":"select":e.endsWith("/form/datepicker")?"date-time":e.endsWith("/form/pathfield")||e.endsWith("/form/pathbrowser")?"aem-content":e.includes("/fileupload")||e.endsWith("/form/fileupload")?"reference":e.includes("tagfield")||e.includes("tagpicker")||e.includes("tagbrowser")?"aem-tag":e.includes("contentfragment")?"aem-content-fragment":e.includes("experiencefragment")?"aem-experience-fragment":null}function qc(e){return e.includes("/foundation/container")||e.includes("/foundation/fixedcolumns")||e.includes("/foundation/well")||e.includes("/foundation/tabs")||e.includes("/foundation/form/fieldset")||e.includes("/foundation/accordion")}function Kc(e){switch(e){case"number":return"number";case"boolean":return"boolean";case"date-time":return"date";case"checkbox-group":return"string[]";case"aem-content":case"aem-content-fragment":case"aem-experience-fragment":return;default:return"string"}}function _n(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function Xc(e){let t=we(e).find(n=>mt(n)==="items");return t?we(t).map(n=>{let o=V(n,"value")??"";return{name:V(n,"text")??V(n,"jcr:title")??o,value:o}}):[]}function Kt(e,t,n,o){for(let i of e){let a=V(i,"sling:resourceType")??"";if(a.endsWith("/foundation/tabs")){let d=we(i).find(l=>mt(l)==="items");for(let l of d?we(d):[]){let c=V(l,"jcr:title");t.push({component:"tab",name:_n(void 0,mt(l)),label:c}),Kt(we(l),t,n,o)}continue}if(a.endsWith("/form/multifield")){let d=[];Kt(we(i),d,n,o);let l=_n(V(i,"name"),`items${o.i++}`);t.push({component:"container",name:l,label:V(i,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:d});continue}let s=a?Jc(a,i):null;if(s){let d=_n(V(i,"name"),`field${o.i++}`),l={component:s,name:d},c=Kc(s);c&&(l.valueType=c);let p=V(i,"fieldLabel")??V(i,"text");if(p&&(l.label=p),s==="select"||s==="radio-group"||s==="multiselect"){let u=Xc(i);u.length&&(l.options=u)}let m=V(i,"value")??(s==="boolean"?V(i,"checked"):void 0);m!==void 0&&m!==""&&(l.value=s==="boolean"?m==="true":m),t.push(l);continue}a&&V(i,"name")&&!qc(a)&&n.add(a),Kt(we(i),t,n,o)}}function wr(e){let o=new Gc({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e).find(s=>mt(s)==="jcr:root"),i=[],a=new Set;return o&&Kt(we(o),i,a,{i:1}),{fields:i,unmapped:[...a]}}var br=v(()=>{"use strict";f()});import{existsSync as yr}from"fs";import{readFile as vr}from"fs/promises";import Xt from"path";import{XMLParser as Vc}from"fast-xml-parser";function Un(e){return[Xt.join(e,"_cq_dialog",".content.xml"),Xt.join(e,"_cq_dialog.xml"),Xt.join(e,"cq:dialog",".content.xml")].find(n=>yr(n))??null}async function kr(e){let t=Xt.join(e,".content.xml");if(yr(t))try{let a=(new Vc({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(await vr(t,"utf-8"))["jcr:root"]??{})["@_jcr:title"];return typeof a=="string"?a.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function xr(e){let t=Un(e);return t?wr(await vr(t,"utf-8")):null}function $r(e,t,n){return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:n}],filters:[]},null,2)}
373
- `}function Sr(e,t){let o=t.some(i=>i.component==="container"&&i.multi)?` // This block was migrated from a classic AEM component with a multifield.
372
+ `),files:o.map(s=>Fe.relative(e,s)),preprocessed:n}}var kr=k(()=>{"use strict";f()});import{XMLParser as Zc}from"fast-xml-parser";function mt(e){return Object.keys(e).find(t=>t!==":@")??""}function be(e){let t=mt(e),n=e[t];return Array.isArray(n)?n:[]}function el(e){return e[":@"]??{}}function tl(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function Q(e,t){return tl(el(e)[`@_${t}`])}function nl(e,t){let n=Q(t,"multiple")==="true"||Q(t,"multiple")==="{Boolean}true";return e.endsWith("/form/textfield")?"text":e.endsWith("/form/textarea")?"textarea":e.includes("/richtext")?"richtext":e.endsWith("/form/numberfield")?"number":e.endsWith("/form/checkbox")?"boolean":e.endsWith("/form/radiogroup")?"radio-group":e.endsWith("/form/select")?n?"multiselect":"select":e.endsWith("/form/datepicker")?"date-time":e.endsWith("/form/pathfield")||e.endsWith("/form/pathbrowser")?"aem-content":e.includes("/fileupload")||e.endsWith("/form/fileupload")?"reference":e.includes("tagfield")||e.includes("tagpicker")||e.includes("tagbrowser")?"aem-tag":e.includes("contentfragment")?"aem-content-fragment":e.includes("experiencefragment")?"aem-experience-fragment":null}function ol(e){return e.includes("/foundation/container")||e.includes("/foundation/fixedcolumns")||e.includes("/foundation/well")||e.includes("/foundation/tabs")||e.includes("/foundation/form/fieldset")||e.includes("/foundation/accordion")}function il(e){switch(e){case"number":return"number";case"boolean":return"boolean";case"date-time":return"date";case"checkbox-group":return"string[]";case"aem-content":case"aem-content-fragment":case"aem-experience-fragment":return;default:return"string"}}function Un(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function rl(e){let t=be(e).find(n=>mt(n)==="items");return t?be(t).map(n=>{let o=Q(n,"value")??"";return{name:Q(n,"text")??Q(n,"jcr:title")??o,value:o}}):[]}function Xt(e,t,n,o){for(let i of e){let a=Q(i,"sling:resourceType")??"";if(a.endsWith("/foundation/tabs")){let d=be(i).find(l=>mt(l)==="items");for(let l of d?be(d):[]){let c=Q(l,"jcr:title");t.push({component:"tab",name:Un(void 0,mt(l)),label:c}),Xt(be(l),t,n,o)}continue}if(a.endsWith("/form/multifield")){let d=[];Xt(be(i),d,n,o);let l=Un(Q(i,"name"),`items${o.i++}`);t.push({component:"container",name:l,label:Q(i,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:d});continue}let s=a?nl(a,i):null;if(s){let d=Un(Q(i,"name"),`field${o.i++}`),l={component:s,name:d},c=il(s);c&&(l.valueType=c);let m=Q(i,"fieldLabel")??Q(i,"text");if(m&&(l.label=m),s==="select"||s==="radio-group"||s==="multiselect"){let u=rl(i);u.length&&(l.options=u)}let p=Q(i,"value")??(s==="boolean"?Q(i,"checked"):void 0);p!==void 0&&p!==""&&(l.value=s==="boolean"?p==="true":p),t.push(l);continue}a&&Q(i,"name")&&!ol(a)&&n.add(a),Xt(be(i),t,n,o)}}function xr(e){let o=new Zc({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e).find(s=>mt(s)==="jcr:root"),i=[],a=new Set;return o&&Xt(be(o),i,a,{i:1}),{fields:i,unmapped:[...a]}}var $r=k(()=>{"use strict";f()});import{existsSync as Sr}from"fs";import{readFile as jr}from"fs/promises";import Vt from"path";import{XMLParser as al}from"fast-xml-parser";function Bn(e){return[Vt.join(e,"_cq_dialog",".content.xml"),Vt.join(e,"_cq_dialog.xml"),Vt.join(e,"cq:dialog",".content.xml")].find(n=>Sr(n))??null}async function Pr(e){let t=Vt.join(e,".content.xml");if(Sr(t))try{let a=(new al({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(await jr(t,"utf-8"))["jcr:root"]??{})["@_jcr:title"];return typeof a=="string"?a.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function Er(e){let t=Bn(e);return t?xr(await jr(t,"utf-8")):null}function Cr(e,t,n){return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:n}],filters:[]},null,2)}
373
+ `}function Ar(e,t){let o=t.some(i=>i.component==="container"&&i.multi)?` // This block was migrated from a classic AEM component with a multifield.
374
374
  // Each child row is one repeated item - enhance them here.
375
375
  [...block.children].forEach((row) => {
376
376
  row.classList.add('${e}-item');
@@ -382,25 +382,25 @@ export default function decorate(block) {
382
382
  block.classList.add('${e}');
383
383
  ${o}
384
384
  }
385
- `}function jr(e){return`/* Block: ${e} */
385
+ `}function Tr(e){return`/* Block: ${e} */
386
386
  /* Migrated from a classic AEM component. Bring the component's styles here */
387
387
  /* (from its clientlib or the rendered page) and keep them scoped to the block. */
388
388
  .${e} {
389
389
  }
390
- `}var Pr=v(()=>{"use strict";f();br()});function Yc(e,t,n){let o=[` // --- ${Cr} ---`];return n.click&&o.push(` ${t}.addEventListener('click', (ev) => {`," const el = ev.target.closest('a, button');"," if (!el) return;",` trackEvent({ event: 'block_click', block: '${e}', label: el.dataset.track || el.textContent.trim() });`," });"),n.submit&&o.push(` ${t}.addEventListener('submit', () => {`,` trackEvent({ event: 'form_submit', block: '${e}' });`," });"),o.join(`
391
- `)}function Ar(e,t,n){if(e.includes(Cr))return{js:e,changed:!1,reason:"already instrumented"};if(!n.click&&!n.submit)return{js:e,changed:!1,reason:"no events selected"};let o=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!o||o.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let i=o[1]||"block",a=e;if(!a.includes("scripts/analytics.js")){let c=[...a.matchAll(/^import .*$/gm)];if(c.length){let p=c[c.length-1],m=(p.index??0)+p[0].length;a=`${a.slice(0,m)}
392
- ${Er}${a.slice(m)}`}else a=`${Er}
390
+ `}var Rr=k(()=>{"use strict";f();$r()});function sl(e,t,n){let o=[` // --- ${Dr} ---`];return n.click&&o.push(` ${t}.addEventListener('click', (ev) => {`," const el = ev.target.closest('a, button');"," if (!el) return;",` trackEvent({ event: 'block_click', block: '${e}', label: el.dataset.track || el.textContent.trim() });`," });"),n.submit&&o.push(` ${t}.addEventListener('submit', () => {`,` trackEvent({ event: 'form_submit', block: '${e}' });`," });"),o.join(`
391
+ `)}function Lr(e,t,n){if(e.includes(Dr))return{js:e,changed:!1,reason:"already instrumented"};if(!n.click&&!n.submit)return{js:e,changed:!1,reason:"no events selected"};let o=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!o||o.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let i=o[1]||"block",a=e;if(!a.includes("scripts/analytics.js")){let c=[...a.matchAll(/^import .*$/gm)];if(c.length){let m=c[c.length-1],p=(m.index??0)+m[0].length;a=`${a.slice(0,p)}
392
+ ${Fr}${a.slice(p)}`}else a=`${Fr}
393
393
 
394
- ${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=Yc(t,i,n);return a=`${a.slice(0,d)}
394
+ ${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=sl(t,i,n);return a=`${a.slice(0,d)}
395
395
  ${l}
396
- ${a.slice(d)}`,{js:a,changed:!0}}var Cr,Er,Tr=v(()=>{"use strict";f();Cr="analytics (eds track)",Er="import { trackEvent } from '../../scripts/analytics.js';"});var ut={};L(ut,{trackBlock:()=>tl});import{existsSync as Rr}from"fs";import{readFile as Qc,writeFile as Zc}from"fs/promises";import Fr from"path";import el from"chalk";async function tl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Track block"));let o=Fr.join(n,"blocks",e,`${e}.js`);if(!Rr(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i={click:t.click!==!1,submit:t.submit!==!1},a=Ar(await Qc(o,"utf-8"),e,i);if(!a.changed){r.warn(`Not instrumented: ${a.reason}.`);return}await Zc(o,a.js),r.info(S("Instrumented"));let s=[i.click?"block_click":null,i.submit?"form_submit":null].filter(Boolean);r.info(j(`blocks/${e}/${e}.js`,s.join(" + "))),Rr(Fr.join(n,"scripts","analytics.js"))||(r.info(""),r.warn("scripts/analytics.js is missing - run `eds integrate gtm` to create it.")),r.info(""),r.info(el.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var ft=v(()=>{"use strict";f();R();B();Tr();N()});var Gn={};L(Gn,{migrateComponent:()=>il});import{existsSync as Bn}from"fs";import{mkdir as nl,writeFile as Hn}from"fs/promises";import Re from"path";function ol(e,t,n){return`/* Block: ${e} */
396
+ ${a.slice(d)}`,{js:a,changed:!0}}var Dr,Fr,Or=k(()=>{"use strict";f();Dr="analytics (eds track)",Fr="import { trackEvent } from '../../scripts/analytics.js';"});var pt={};O(pt,{trackBlock:()=>ml});import{existsSync as Nr}from"fs";import{readFile as cl,writeFile as ll}from"fs/promises";import Mr from"path";import dl from"chalk";async function ml(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Track block"));let o=Mr.join(n,"blocks",e,`${e}.js`);if(!Nr(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i={click:t.click!==!1,submit:t.submit!==!1},a=Lr(await cl(o,"utf-8"),e,i);if(!a.changed){r.warn(`Not instrumented: ${a.reason}.`);return}await ll(o,a.js),r.info(S("Instrumented"));let s=[i.click?"block_click":null,i.submit?"form_submit":null].filter(Boolean);r.info(j(`blocks/${e}/${e}.js`,s.join(" + "))),Nr(Mr.join(n,"scripts","analytics.js"))||(r.info(""),r.warn("scripts/analytics.js is missing - run `eds integrate gtm` to create it.")),r.info(""),r.info(dl.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var ut=k(()=>{"use strict";f();R();z();Or();M()});var zn={};O(zn,{migrateComponent:()=>fl});import{existsSync as Hn}from"fs";import{mkdir as pl,writeFile as Gn}from"fs/promises";import De from"path";function ul(e,t,n){return`/* Block: ${e} */
397
397
  /* Migrated from the component clientlib: ${n.join(", ")}. */
398
398
  /* TODO: review selectors and scope them under .${e} (and port any LESS/SCSS). */
399
399
 
400
400
  ${t.trim()}
401
- `}function Dr(e,t=0){let n=[];for(let o of e){let i=" ".repeat(t);if(o.component==="tab")n.push(`${i}${_.blue("\u25B8")} ${o.label??o.name}`);else{let a=o.options?.length?` (${o.options.length} options)`:"",s=o.multi?" \xB7multi":"",d=o.label?`- ${o.label}`:"";n.push(`${i}${_.accent(o.component)}${s} ${o.name}${a} ${d}`),o.fields?.length&&n.push(...Dr(o.fields,t+1))}}return n}function Lr(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=Lr(n.fields)));return t}async function il(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Migrate component");let{input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!t.yes,s=e;if(!s&&a&&(s=await o({message:"Path to the classic component folder",validate:$=>Bn($.trim())||"Folder not found"})),!s){r.error("Provide the path to the classic component folder."),process.exitCode=1;return}if(s=Re.resolve(s.trim()),!Un(s)){r.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${s}.`),process.exitCode=1;return}let d=await xr(s);if(!d||d.fields.length===0){r.warn("Dialog found but no mappable fields were detected."),d?.unmapped.length&&r.info(`Unmapped resourceTypes: ${d.unmapped.join(", ")}`),process.exitCode=1;return}let l=await kr(s)??Re.basename(s),c=t.name&&Vt(t.name)||Vt(a?await o({message:"Block name",default:Vt(l)}):l);r.info(S("Mapped fields",`${Lr(d.fields)} from dialog`));for(let $ of Dr(d.fields))r.info(` ${$}`);if(d.unmapped.length&&(r.info(""),r.warn(`Skipped (unrecognised): ${d.unmapped.join(", ")}`)),r.info(""),a&&!await i({message:`Generate block "${c}"?`,default:!0})){r.info("Cancelled.");return}let p=Re.join(n,"blocks",c);if(Bn(p)){r.error(`Block "${c}" already exists at blocks/${c}. Use --name to pick another.`),process.exitCode=1;return}let m=t.clientlib?Re.resolve(t.clientlib.trim()):await fr(s),u=jr(c),g="empty - add styles from clientlib / rendered CSS",w=[];if(m&&Bn(m)){let $=await gr(m);$.css.trim()&&(u=ol(c,$.css,$.files),g=`from clientlib (${$.files.length} file(s)) - review & scope`),w=$.preprocessed}await nl(p,{recursive:!0}),await Hn(Re.join(p,`${c}.js`),Sr(c,d.fields)),await Hn(Re.join(p,`${c}.css`),u),await Hn(Re.join(p,`_${c}.json`),$r(c,l,d.fields)),r.info(S("Created"));let y=[`${c}.js`,`${c}.css`,`_${c}.json`],h=M(y);if(r.info(j(`${c}.js`,"decorator stub (port HTL logic)",h)),r.info(j(`${c}.css`,g,h)),r.info(j(`_${c}.json`,"Universal Editor model",h)),w.length&&(r.info(""),r.warn(`LESS/SCSS found (needs a build, not copied): ${w.join(", ")}`)),r.info(""),a&&await i({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:b}=await Promise.resolve().then(()=>(ft(),ut));await b(c,{})}r.info(O([`"${c}" migrated. Next: add CSS, then \`eds block preview ${c}\``]))}var Vt,zn=v(()=>{"use strict";f();R();hr();Pr();B();N();Vt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function X(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var K,Or=v(()=>{"use strict";f();K={text:(e,t)=>({component:"text",valueType:"string",name:e,label:t}),textarea:(e,t)=>({component:"textarea",valueType:"string",name:e,label:t}),richtext:(e,t)=>({component:"richtext",valueType:"string",name:e,value:"",label:t}),number:(e,t)=>({component:"number",valueType:"number",name:e,label:t}),boolean:(e,t,n=!1)=>({component:"boolean",valueType:"boolean",name:e,value:n,label:t}),dateTime:(e,t)=>({component:"date-time",valueType:"date",name:e,label:t}),select:(e,t,n,o)=>({component:"select",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),multiselect:(e,t,n)=>({component:"multiselect",valueType:"string",name:e,label:t,options:n}),radioGroup:(e,t,n,o)=>({component:"radio-group",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),checkboxGroup:(e,t,n)=>({component:"checkbox-group",valueType:"string[]",name:e,label:t,options:n}),reference:(e,t)=>({component:"reference",valueType:"string",name:e,label:t}),aemContent:(e,t)=>({component:"aem-content",name:e,label:t}),aemContentFragment:(e,t)=>({component:"aem-content-fragment",name:e,label:t}),aemExperienceFragment:(e,t)=>({component:"aem-experience-fragment",name:e,label:t}),aemTag:(e,t)=>({component:"aem-tag",valueType:"string",name:e,label:t}),tab:(e,t)=>({component:"tab",name:e,label:t}),container:(e,t,n,o=!0)=>({component:"container",name:e,label:t,multi:!0,collapsible:o,fields:n})}});function Kn(e){return ze.find(t=>t.id===e)}var rl,al,sl,cl,Nr,Mr,Wn,Ir,Jn,qn,ll,dl,pl,ml,ul,ze,Xn=v(()=>{"use strict";f();Or();rl=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],al=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],sl=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],cl=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],Nr=(e="")=>[K.text(X(e,"title"),"Title"),K.select(X(e,"titleType"),"Heading level",rl,"h2")],Mr=(e="")=>[K.text(X(e,"eyebrow"),"Eyebrow")],Wn=(e="")=>[K.reference(X(e,"image"),"Image"),K.text(X(e,"imageAlt"),"Alt text")],Ir=(e="")=>[K.richtext(X(e,"text"),"Text")],Jn=(e="")=>[K.text(X(e,"linkText"),"Link text"),K.aemContent(X(e,"link"),"Link"),K.select(X(e,"linkTarget"),"Open in",al,"_self")],qn=(e="")=>[...Jn(e),K.select(X(e,"ctaStyle"),"Style",sl,"")],ll=(e="")=>[K.container(X(e,"ctas")||"ctas","Buttons",qn())],dl=(e="")=>[K.multiselect(X(e,"classes"),"Styles",cl)],pl=(e="")=>[K.aemContent(X(e,"url"),"URL (video / embed)")],ml=(e="")=>[...Wn(e),...Mr(e),...Nr(e),...Ir(e),...qn(e)],ul=(e="")=>[...Wn(e),K.text(X(e,"title"),"Title"),K.richtext(X(e,"description"),"Description"),...Jn(e)],ze=[{id:"heading",label:"Heading (title + level)",build:Nr},{id:"eyebrow",label:"Eyebrow (kicker line)",build:Mr},{id:"image",label:"Image (reference + alt)",build:Wn},{id:"richtext",label:"Rich text body",build:Ir},{id:"link",label:"Link (text + url + target)",build:Jn},{id:"cta",label:"CTA (link + style)",build:qn},{id:"cta-group",label:"CTA group (repeatable buttons)",build:ll},{id:"classes",label:"Section styles (CSS modifiers)",build:dl},{id:"embed",label:"Embed / video (URL)",build:pl},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:ml},{id:"card",label:"Card (image + title + description + link)",build:ul}]});var Qn={};L(Qn,{modelAdd:()=>hl});import{existsSync as Vn}from"fs";import{readFile as fl,writeFile as gl}from"fs/promises";import Yn from"path";async function hl(e,t,n={}){let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Model - add partials"));let{select:i,checkbox:a}=await Promise.resolve().then(()=>(G(),H)),s=!n.yes,d=e;if(!d&&s){let{readdir:b}=await import("fs/promises"),T=Yn.join(o,"blocks"),Q=Vn(T)?(await b(T,{withFileTypes:!0})).filter(z=>z.isDirectory()&&Vn(Yn.join(T,z.name,`_${z.name}.json`))).map(z=>z.name):[];if(Q.length===0){r.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}d=await i({message:"Which block's model?",choices:Q.map(z=>({name:z,value:z}))})}if(!d){r.error("Provide a block name."),process.exitCode=1;return}let l=Yn.join(o,"blocks",d,`_${d}.json`);if(!Vn(l)){r.error(`No model at blocks/${d}/_${d}.json. Create the block first.`),process.exitCode=1;return}let c=t;c.length===0&&s&&(c=await a({message:"Which partials to add?",choices:ze.map(b=>({name:b.label,value:b.id}))}));let p=c.map(b=>Kn(b.trim())).filter(b=>!!b),m=c.filter(b=>!Kn(b.trim()));if(m.length&&r.warn(`Unknown partial(s): ${m.join(", ")}. Available: ${ze.map(b=>b.id).join(", ")}`),p.length===0){r.info("Nothing to add.");return}let u;try{u=JSON.parse(await fl(l,"utf-8"))}catch{r.error(`Could not parse ${l}.`),process.exitCode=1;return}let g=Array.isArray(u.models)?u.models:[],w=g.find(b=>b.id===d)??g[0];if(!w){r.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}w.fields=Array.isArray(w.fields)?w.fields:[];let y=new Set(w.fields.map(b=>b.name)),h=[],$=[];for(let b of p)for(let T of b.build()){if(y.has(T.name)){$.push(T.name);continue}y.add(T.name),w.fields.push(T),h.push(T.name)}await gl(l,`${JSON.stringify(u,null,2)}
402
- `),r.info(S("Model updated",`blocks/${d}/_${d}.json`)),r.info(j("partials",p.map(b=>b.id).join(", "))),r.info(j("fields added",h.length?h.join(", "):"(none)")),$.length&&r.info(A("warn","skipped (exists)",$.join(", "))),r.info(""),r.info(O([`${h.length} field(s) added to "${d}"`]))}var Zn=v(()=>{"use strict";f();R();Xn();B();N()});function Ur(e){return Yt.find(t=>t.id.toLowerCase()===e.toLowerCase())}function Br(e,t){if(e.includes(_r))return{js:e,changed:!1,reason:"already has JSON-LD"};let n=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!n||n.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let o=n[1]||"block",i=n.index+n[0].length,a=`
403
- // --- ${_r}: ${t.id}) ---
401
+ `}function Ir(e,t=0){let n=[];for(let o of e){let i=" ".repeat(t);if(o.component==="tab")n.push(`${i}${U.blue("\u25B8")} ${o.label??o.name}`);else{let a=o.options?.length?` (${o.options.length} options)`:"",s=o.multi?" \xB7multi":"",d=o.label?`- ${o.label}`:"";n.push(`${i}${U.accent(o.component)}${s} ${o.name}${a} ${d}`),o.fields?.length&&n.push(...Ir(o.fields,t+1))}}return n}function _r(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=_r(n.fields)));return t}async function fl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Migrate component");let{input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!t.yes,s=e;if(!s&&a&&(s=await o({message:"Path to the classic component folder",validate:y=>Hn(y.trim())||"Folder not found"})),!s){r.error("Provide the path to the classic component folder."),process.exitCode=1;return}if(s=De.resolve(s.trim()),!Bn(s)){r.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${s}.`),process.exitCode=1;return}let d=await Er(s);if(!d||d.fields.length===0){r.warn("Dialog found but no mappable fields were detected."),d?.unmapped.length&&r.info(`Unmapped resourceTypes: ${d.unmapped.join(", ")}`),process.exitCode=1;return}let l=await Pr(s)??De.basename(s),c=t.name&&Yt(t.name)||Yt(a?await o({message:"Block name",default:Yt(l)}):l);r.info(S("Mapped fields",`${_r(d.fields)} from dialog`));for(let y of Ir(d.fields))r.info(` ${y}`);if(d.unmapped.length&&(r.info(""),r.warn(`Skipped (unrecognised): ${d.unmapped.join(", ")}`)),r.info(""),a&&!await i({message:`Generate block "${c}"?`,default:!0})){r.info("Cancelled.");return}let m=De.join(n,"blocks",c);if(Hn(m)){r.error(`Block "${c}" already exists at blocks/${c}. Use --name to pick another.`),process.exitCode=1;return}let p=t.clientlib?De.resolve(t.clientlib.trim()):await yr(s),u=Tr(c),g="empty - add styles from clientlib / rendered CSS",h=[];if(p&&Hn(p)){let y=await vr(p);y.css.trim()&&(u=ul(c,y.css,y.files),g=`from clientlib (${y.files.length} file(s)) - review & scope`),h=y.preprocessed}await pl(m,{recursive:!0}),await Gn(De.join(m,`${c}.js`),Ar(c,d.fields)),await Gn(De.join(m,`${c}.css`),u),await Gn(De.join(m,`_${c}.json`),Cr(c,l,d.fields)),r.info(S("Created"));let b=[`${c}.js`,`${c}.css`,`_${c}.json`],w=I(b);if(r.info(j(`${c}.js`,"decorator stub (port HTL logic)",w)),r.info(j(`${c}.css`,g,w)),r.info(j(`_${c}.json`,"Universal Editor model",w)),h.length&&(r.info(""),r.warn(`LESS/SCSS found (needs a build, not copied): ${h.join(", ")}`)),r.info(""),a&&await i({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:v}=await Promise.resolve().then(()=>(ut(),pt));await v(c,{})}r.info(N([`"${c}" migrated. Next: add CSS, then \`eds block preview ${c}\``]))}var Yt,Wn=k(()=>{"use strict";f();R();kr();Rr();z();M();Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function V(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var X,Ur=k(()=>{"use strict";f();X={text:(e,t)=>({component:"text",valueType:"string",name:e,label:t}),textarea:(e,t)=>({component:"textarea",valueType:"string",name:e,label:t}),richtext:(e,t)=>({component:"richtext",valueType:"string",name:e,value:"",label:t}),number:(e,t)=>({component:"number",valueType:"number",name:e,label:t}),boolean:(e,t,n=!1)=>({component:"boolean",valueType:"boolean",name:e,value:n,label:t}),dateTime:(e,t)=>({component:"date-time",valueType:"date",name:e,label:t}),select:(e,t,n,o)=>({component:"select",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),multiselect:(e,t,n)=>({component:"multiselect",valueType:"string",name:e,label:t,options:n}),radioGroup:(e,t,n,o)=>({component:"radio-group",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),checkboxGroup:(e,t,n)=>({component:"checkbox-group",valueType:"string[]",name:e,label:t,options:n}),reference:(e,t)=>({component:"reference",valueType:"string",name:e,label:t}),aemContent:(e,t)=>({component:"aem-content",name:e,label:t}),aemContentFragment:(e,t)=>({component:"aem-content-fragment",name:e,label:t}),aemExperienceFragment:(e,t)=>({component:"aem-experience-fragment",name:e,label:t}),aemTag:(e,t)=>({component:"aem-tag",valueType:"string",name:e,label:t}),tab:(e,t)=>({component:"tab",name:e,label:t}),container:(e,t,n,o=!0)=>({component:"container",name:e,label:t,multi:!0,collapsible:o,fields:n})}});function Xn(e){return ze.find(t=>t.id===e)}var gl,hl,wl,bl,Br,Hr,Jn,Gr,qn,Kn,yl,vl,kl,xl,$l,ze,Vn=k(()=>{"use strict";f();Ur();gl=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],hl=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],wl=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],bl=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],Br=(e="")=>[X.text(V(e,"title"),"Title"),X.select(V(e,"titleType"),"Heading level",gl,"h2")],Hr=(e="")=>[X.text(V(e,"eyebrow"),"Eyebrow")],Jn=(e="")=>[X.reference(V(e,"image"),"Image"),X.text(V(e,"imageAlt"),"Alt text")],Gr=(e="")=>[X.richtext(V(e,"text"),"Text")],qn=(e="")=>[X.text(V(e,"linkText"),"Link text"),X.aemContent(V(e,"link"),"Link"),X.select(V(e,"linkTarget"),"Open in",hl,"_self")],Kn=(e="")=>[...qn(e),X.select(V(e,"ctaStyle"),"Style",wl,"")],yl=(e="")=>[X.container(V(e,"ctas")||"ctas","Buttons",Kn())],vl=(e="")=>[X.multiselect(V(e,"classes"),"Styles",bl)],kl=(e="")=>[X.aemContent(V(e,"url"),"URL (video / embed)")],xl=(e="")=>[...Jn(e),...Hr(e),...Br(e),...Gr(e),...Kn(e)],$l=(e="")=>[...Jn(e),X.text(V(e,"title"),"Title"),X.richtext(V(e,"description"),"Description"),...qn(e)],ze=[{id:"heading",label:"Heading (title + level)",build:Br},{id:"eyebrow",label:"Eyebrow (kicker line)",build:Hr},{id:"image",label:"Image (reference + alt)",build:Jn},{id:"richtext",label:"Rich text body",build:Gr},{id:"link",label:"Link (text + url + target)",build:qn},{id:"cta",label:"CTA (link + style)",build:Kn},{id:"cta-group",label:"CTA group (repeatable buttons)",build:yl},{id:"classes",label:"Section styles (CSS modifiers)",build:vl},{id:"embed",label:"Embed / video (URL)",build:kl},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:xl},{id:"card",label:"Card (image + title + description + link)",build:$l}]});var Zn={};O(Zn,{modelAdd:()=>Pl});import{existsSync as Yn}from"fs";import{readFile as Sl,writeFile as jl}from"fs/promises";import Qn from"path";async function Pl(e,t,n={}){let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Model - add partials"));let{select:i,checkbox:a}=await Promise.resolve().then(()=>(G(),H)),s=!n.yes,d=e;if(!d&&s){let{readdir:v}=await import("fs/promises"),T=Qn.join(o,"blocks"),K=Yn(T)?(await v(T,{withFileTypes:!0})).filter(J=>J.isDirectory()&&Yn(Qn.join(T,J.name,`_${J.name}.json`))).map(J=>J.name):[];if(K.length===0){r.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}d=await i({message:"Which block's model?",choices:K.map(J=>({name:J,value:J}))})}if(!d){r.error("Provide a block name."),process.exitCode=1;return}let l=Qn.join(o,"blocks",d,`_${d}.json`);if(!Yn(l)){r.error(`No model at blocks/${d}/_${d}.json. Create the block first.`),process.exitCode=1;return}let c=t;c.length===0&&s&&(c=await a({message:"Which partials to add?",choices:ze.map(v=>({name:v.label,value:v.id}))}));let m=c.map(v=>Xn(v.trim())).filter(v=>!!v),p=c.filter(v=>!Xn(v.trim()));if(p.length&&r.warn(`Unknown partial(s): ${p.join(", ")}. Available: ${ze.map(v=>v.id).join(", ")}`),m.length===0){r.info("Nothing to add.");return}let u;try{u=JSON.parse(await Sl(l,"utf-8"))}catch{r.error(`Could not parse ${l}.`),process.exitCode=1;return}let g=Array.isArray(u.models)?u.models:[],h=g.find(v=>v.id===d)??g[0];if(!h){r.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}h.fields=Array.isArray(h.fields)?h.fields:[];let b=new Set(h.fields.map(v=>v.name)),w=[],y=[];for(let v of m)for(let T of v.build()){if(b.has(T.name)){y.push(T.name);continue}b.add(T.name),h.fields.push(T),w.push(T.name)}await jl(l,`${JSON.stringify(u,null,2)}
402
+ `),r.info(S("Model updated",`blocks/${d}/_${d}.json`)),r.info(j("partials",m.map(v=>v.id).join(", "))),r.info(j("fields added",w.length?w.join(", "):"(none)")),y.length&&r.info(A("warn","skipped (exists)",y.join(", "))),r.info(""),r.info(N([`${w.length} field(s) added to "${d}"`]))}var eo=k(()=>{"use strict";f();R();Vn();z();M()});function Wr(e){return Qt.find(t=>t.id.toLowerCase()===e.toLowerCase())}function Jr(e,t){if(e.includes(zr))return{js:e,changed:!1,reason:"already has JSON-LD"};let n=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!n||n.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let o=n[1]||"block",i=n.index+n[0].length,a=`
403
+ // --- ${zr}: ${t.id}) ---
404
404
  {
405
405
  const root = ${o};
406
406
  const ld = ${t.object};
@@ -409,7 +409,7 @@ ${t.trim()}
409
409
  ldScript.textContent = JSON.stringify(ld);
410
410
  document.head.append(ldScript);
411
411
  }
412
- `;return{js:`${e.slice(0,i)}${a}${e.slice(i)}`,changed:!0}}var _r,Yt,Hr=v(()=>{"use strict";f();_r="json-ld (eds schema",Yt=[{id:"Article",label:"Article / BlogPosting",object:`{
412
+ `;return{js:`${e.slice(0,i)}${a}${e.slice(i)}`,changed:!0}}var zr,Qt,qr=k(()=>{"use strict";f();zr="json-ld (eds schema",Qt=[{id:"Article",label:"Article / BlogPosting",object:`{
413
413
  '@context': 'https://schema.org',
414
414
  '@type': 'Article',
415
415
  headline: root.querySelector('h1, h2, h3')?.textContent?.trim() || document.title,
@@ -488,16 +488,16 @@ ${t.trim()}
488
488
  position: i + 1,
489
489
  text: li.textContent?.trim(),
490
490
  })),
491
- }`}]});var eo={};L(eo,{schemaBlock:()=>xl});import{existsSync as wl}from"fs";import{readFile as bl,writeFile as yl}from"fs/promises";import vl from"path";import kl from"chalk";async function xl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Schema - JSON-LD"));let o=vl.join(n,"blocks",e,`${e}.js`);if(!wl(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i=t.type;if(!i&&!t.yes){let{select:d}=await Promise.resolve().then(()=>(G(),H));i=await d({message:"Which schema.org type?",choices:Yt.map(l=>({name:`${l.id} - ${l.label}`,value:l.id}))})}let a=i?Ur(i):void 0;if(!a){r.error(`Unknown schema type "${i}". Options: ${Yt.map(d=>d.id).join(", ")}`),process.exitCode=1;return}let s=Br(await bl(o,"utf-8"),a);if(!s.changed){r.warn(`Not added: ${s.reason}.`);return}await yl(o,s.js),r.info(S("JSON-LD added")),r.info(j(`blocks/${e}/${e}.js`,`${a.id} (${a.label})`)),r.info(""),r.info(kl.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var to=v(()=>{"use strict";f();R();B();Hr();N()});function Sl(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname=["']([^"']+)["']/i)?.[1]===t)return n.match(/\bcontent=["']([^"']*)["']/i)?.[1]??"";return null}function Gr(e){return Sl(e,$l)!==null}function zr(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function Wr(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(i=>{let a=i.hasModelFile||n.has(i.name);return{name:i.name,editable:a,reason:a?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var no,$l,Jr=v(()=>{"use strict";f();no=["component-definition.json","component-models.json","component-filters.json"],$l="urn:adobe:aue:system:aemconnection"});var wt={};L(wt,{ueCheck:()=>Tl,ueOpen:()=>Rl});import{existsSync as ht}from"fs";import{readFile as qr,readdir as jl}from"fs/promises";import gt from"path";import Qt from"chalk";async function Pl(e){if(!ht(e))return null;try{return JSON.parse(await qr(e,"utf-8"))}catch{return null}}async function El(e){let t=gt.join(e,"blocks");return ht(t)?(await jl(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:ht(gt.join(t,o.name,`_${o.name}.json`))})):[]}async function Cl(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore"})}catch{}}async function Al(e){try{let{execa:t}=await import("execa");return(await t("git",["remote","get-url","origin"],{cwd:e})).stdout.trim()||null}catch{return null}}async function Tl(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Universal Editor - readiness"));let t={};for(let m of no)t[m]=ht(gt.join(e,m));let n=await Pl(gt.join(e,"component-models.json")),o=await El(e),{isUeProject:i,blocks:a}=Wr({configPresent:t,blocks:o,modelIds:zr(n)});r.info(S("Universal Editor config"));let s=[...no],d=M(s);for(let m of s)r.info(A(t[m]?"pass":"fail",m,void 0,d));if(!i){r.info(""),r.warn("This doesn't look like a Universal Editor (crosswalk) project - run `eds scaffold ue` first."),process.exitCode=1;return}let l=gt.join(e,"head.html");if(ht(l)){let m=Gr(await qr(l,"utf-8"));r.info(A(m?"pass":"info","head.html",m?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(r.info(S("Blocks",`${a.length} found`)),a.length===0)r.info(Qt.dim(" No blocks yet."));else{let m=M(a.map(u=>u.name));for(let u of a)r.info(A(u.editable?"pass":"warn",u.name,u.reason,m))}let c=a.filter(m=>m.editable).length,p=a.length-c;r.info(""),r.info(fe({pass:c,warn:p})),r.info(Qt.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Rl(e,t={}){let n=P()??process.cwd(),o=e??t.path??"/",i=t.url;if(!i){let s=await Al(n),d=s?He(s):null;if(!d){r.error("Couldn't determine the preview host from git."),r.info(Qt.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}i=Ge(d.owner,d.repo,t.ref??"main")}let a=Li({host:i,path:o,org:t.org});r.info(S("Universal Editor")),r.info(j("page",`${i}${o.startsWith("/")?"":"/"}${o}`)),r.info(j("open",a)),t.open!==!1?await Cl(a):r.info(Qt.dim(" (use without --no-open to launch the browser)"))}var bt=v(()=>{"use strict";f();R();B();Jr();Ut();N()});var io={};L(io,{createBlock:()=>Ol,ueModelFor:()=>Xr});import{existsSync as Fl}from"fs";import{mkdir as Dl,writeFile as oo}from"fs/promises";import yt from"path";import Kr from"chalk";function Ll(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Xr(e){let t=Ll(e);return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:[{component:"text",name:"title",label:"Title",valueType:"string"},{component:"select",name:"titleType",label:"Title Type",valueType:"string",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"}]},{component:"richtext",name:"text",value:"",label:"Text",valueType:"string"}]}],filters:[]},null,2)}
492
- `}async function Ol(e,t={}){if(!Se.test(e)){r.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}let o=yt.join(n,"blocks",e);if(Fl(o)){r.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await Dl(o,{recursive:!0});let i=`export default function decorate(block) {
491
+ }`}]});var to={};O(to,{schemaBlock:()=>Fl});import{existsSync as El}from"fs";import{readFile as Cl,writeFile as Al}from"fs/promises";import Tl from"path";import Rl from"chalk";async function Fl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Schema - JSON-LD"));let o=Tl.join(n,"blocks",e,`${e}.js`);if(!El(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i=t.type;if(!i&&!t.yes){let{select:d}=await Promise.resolve().then(()=>(G(),H));i=await d({message:"Which schema.org type?",choices:Qt.map(l=>({name:`${l.id} - ${l.label}`,value:l.id}))})}let a=i?Wr(i):void 0;if(!a){r.error(`Unknown schema type "${i}". Options: ${Qt.map(d=>d.id).join(", ")}`),process.exitCode=1;return}let s=Jr(await Cl(o,"utf-8"),a);if(!s.changed){r.warn(`Not added: ${s.reason}.`);return}await Al(o,s.js),r.info(S("JSON-LD added")),r.info(j(`blocks/${e}/${e}.js`,`${a.id} (${a.label})`)),r.info(""),r.info(Rl.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var no=k(()=>{"use strict";f();R();z();qr();M()});function Ll(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname=["']([^"']+)["']/i)?.[1]===t)return n.match(/\bcontent=["']([^"']*)["']/i)?.[1]??"";return null}function Kr(e){return Ll(e,Dl)!==null}function Xr(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function Vr(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(i=>{let a=i.hasModelFile||n.has(i.name);return{name:i.name,editable:a,reason:a?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var oo,Dl,Yr=k(()=>{"use strict";f();oo=["component-definition.json","component-models.json","component-filters.json"],Dl="urn:adobe:aue:system:aemconnection"});var ht={};O(ht,{ueCheck:()=>Ul,ueOpen:()=>Bl});import{existsSync as gt}from"fs";import{readFile as Qr,readdir as Ol}from"fs/promises";import ft from"path";import Zt from"chalk";async function Nl(e){if(!gt(e))return null;try{return JSON.parse(await Qr(e,"utf-8"))}catch{return null}}async function Ml(e){let t=ft.join(e,"blocks");return gt(t)?(await Ol(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:gt(ft.join(t,o.name,`_${o.name}.json`))})):[]}async function Il(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore"})}catch{}}async function _l(e){try{let{execa:t}=await import("execa");return(await t("git",["remote","get-url","origin"],{cwd:e})).stdout.trim()||null}catch{return null}}async function Ul(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Universal Editor - readiness"));let t={};for(let p of oo)t[p]=gt(ft.join(e,p));let n=await Nl(ft.join(e,"component-models.json")),o=await Ml(e),{isUeProject:i,blocks:a}=Vr({configPresent:t,blocks:o,modelIds:Xr(n)});r.info(S("Universal Editor config"));let s=[...oo],d=I(s);for(let p of s)r.info(A(t[p]?"pass":"fail",p,void 0,d));if(!i){r.info(""),r.warn("This doesn't look like a Universal Editor (crosswalk) project - run `eds scaffold ue` first."),process.exitCode=1;return}let l=ft.join(e,"head.html");if(gt(l)){let p=Kr(await Qr(l,"utf-8"));r.info(A(p?"pass":"info","head.html",p?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(r.info(S("Blocks",`${a.length} found`)),a.length===0)r.info(Zt.dim(" No blocks yet."));else{let p=I(a.map(u=>u.name));for(let u of a)r.info(A(u.editable?"pass":"warn",u.name,u.reason,p))}let c=a.filter(p=>p.editable).length,m=a.length-c;r.info(""),r.info(ge({pass:c,warn:m})),r.info(Zt.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Bl(e,t={}){let n=P()??process.cwd(),o=e??t.path??"/",i=t.url;if(!i){let s=await _l(n),d=s?He(s):null;if(!d){r.error("Couldn't determine the preview host from git."),r.info(Zt.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}i=Ge(d.owner,d.repo,t.ref??"main")}let a=_i({host:i,path:o,org:t.org});r.info(S("Universal Editor")),r.info(j("page",`${i}${o.startsWith("/")?"":"/"}${o}`)),r.info(j("open",a)),t.open!==!1?await Il(a):r.info(Zt.dim(" (use without --no-open to launch the browser)"))}var wt=k(()=>{"use strict";f();R();z();Yr();Bt();M()});var ro={};O(ro,{createBlock:()=>Wl,ueModelFor:()=>ea});import{existsSync as Hl}from"fs";import{mkdir as Gl,writeFile as io}from"fs/promises";import bt from"path";import Zr from"chalk";function zl(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ea(e){let t=zl(e);return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:[{component:"text",name:"title",label:"Title",valueType:"string"},{component:"select",name:"titleType",label:"Title Type",valueType:"string",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"}]},{component:"richtext",name:"text",value:"",label:"Text",valueType:"string"}]}],filters:[]},null,2)}
492
+ `}async function Wl(e,t={}){if(!Pe.test(e)){r.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}let o=bt.join(n,"blocks",e);if(Hl(o)){r.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await Gl(o,{recursive:!0});let i=`export default function decorate(block) {
493
493
  // TODO: implement ${e} block
494
494
  }
495
495
  `,a=`.${e} {
496
496
  /* TODO: style ${e} block */
497
497
  }
498
- `;await oo(yt.join(o,`${e}.js`),i),await oo(yt.join(o,`${e}.css`),a);let s=t.ueModel!==!1;s&&await oo(yt.join(o,`_${e}.json`),Xr(e)),r.success(`Block "${e}" created at ${Kr.cyan(yt.relative(n,o))}${s?Kr.dim(" (+ Universal Editor model)"):""}`)}var ro=v(()=>{"use strict";f();R();B();Be()});import{existsSync as Zt}from"fs";import{readFile as Nl}from"fs/promises";import{homedir as We}from"os";import Je from"path";async function so(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function Vr(e){if(!e||typeof e!="object")return;let t=e,n=t.mcpServers;if(n&&typeof n=="object"){for(let o of Object.keys(n))if(o.toLowerCase().includes("figma"))return o}for(let o of Object.values(t)){let i=Vr(o);if(i)return i}}async function co(e){for(let t of e)try{if(!Zt(t))continue;let n=await Nl(t,"utf-8");try{let o=Vr(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function Yr(e){if(e){let t=ao.find(n=>n.type===e);if(t){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}r.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of ao){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);return{type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function en(){let e=[];for(let t of ao){let n=await so(t.binary);if(n){let o=await co(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:Zt(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var ao,lo=v(()=>{"use strict";f();R();ao=[{type:"claude",binary:"claude",configDir:Je.join(We(),".claude"),mcpConfigPaths:[Je.join(We(),".claude","plugins.json"),Je.join(We(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Je.join(We(),".cursor"),mcpConfigPaths:[Je.join(We(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Je.join(We(),".codex"),mcpConfigPaths:[]}]});import{mkdir as Ml,readFile as Il,writeFile as _l}from"fs/promises";import{tmpdir as Ul}from"os";import vt from"path";import Bl from"readline";import ee from"chalk";async function po(e,t){let n=t?vt.join(t,"tmp"):Ul(),o=vt.join(n,"eds-cli");await Ml(o,{recursive:!0});let i=`from-design-${Date.now()}.md`,a=vt.join(o,i);return await _l(a,e,"utf-8"),a}async function mo(e,t,n,o){let{execa:i}=await import("execa"),a=await Il(t,"utf-8");try{switch(e.type){case"claude":{r.info(`Running Claude Code ${ee.dim("- live log:")}`);let s=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],d=[...new Set(s.map(p=>`mcp__${p}`)),"Edit","Write","Read"].join(","),c=i("claude",["-p",a,"--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",d],{cwd:n,buffer:!1,stdio:["ignore","pipe","inherit"]});await Gl(c,n);break}case"cursor":{r.info("Running Cursor agent..."),await i("cursor",["--prompt",a],{cwd:n,stdio:"inherit"});break}case"codex":{r.info("Running Codex..."),await i("codex",[a],{cwd:n,stdio:"inherit"});break}}return!0}catch(s){let d=s instanceof Error?s.message:String(s);return r.error(`Agent ${e.type} failed: ${d}`),!1}}function Hl(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function Gl(e,t){let n=(await import("ora")).default,o=Date.now(),i=()=>`${Math.round((Date.now()-o)/1e3)}s`,a=n({text:`thinking ${ee.dim(i())}`,color:"yellow"}).start(),s="thinking",d=setInterval(()=>{a.text=`${s} ${ee.dim(i())}`},300),l=new Map,c=m=>{a.stop(),r.info(` ${m}`),a.start()},p;try{if(e.stdout){let m=Bl.createInterface({input:e.stdout});for await(let u of m){let g=u.trim();if(!g)continue;let w;try{w=JSON.parse(g)}catch{continue}let y=Array.isArray(w.message?.content)?w.message.content:[];if(w.type==="assistant"){for(let h of y)if(h.type==="text"&&"text"in h){let $=h.text.trim().split(`
499
- `)[0].slice(0,100);$&&c(ee.dim($))}else if(h.type==="tool_use"&&"name"in h){let $="id"in h&&h.id?h.id:`${Math.random()}`;l.set($,{label:zl(h.name,h.input,t),start:Date.now()}),s=Hl(h.name)}}else if(w.type==="user"){for(let h of y)if(h.type==="tool_result"&&"tool_use_id"in h&&h.tool_use_id){let $=l.get(h.tool_use_id);if($){let b=`${((Date.now()-$.start)/1e3).toFixed(1)}s`,T="is_error"in h&&h.is_error?` ${ee.red("failed")}`:"";c(`${$.label} ${ee.dim(b)}${T}`),l.delete(h.tool_use_id)}}}else if(w.type==="result"){let h=typeof w.duration_ms=="number"?`${(w.duration_ms/1e3).toFixed(1)}s`:"",$=typeof w.total_cost_usd=="number"?`$${w.total_cost_usd.toFixed(3)}`:"";p=[h,$].filter(Boolean).join(" \xB7 ")||"done"}}}for(let m of l.values())c(`${m.label} ${ee.dim("\u2026")}`);clearInterval(d),p?a.succeed(`${_.accent("agent finished")} ${ee.dim(p)}`):a.stop()}catch(m){throw clearInterval(d),a.stop(),m}await e}function zl(e,t,n){let o=i=>{let a=t?.[i];return typeof a!="string"?"":a.startsWith(n)?vt.relative(n,a):vt.basename(a)};if(e.includes("figma")){let i=e.split("__").pop()??e;return`${q.figma} ${ee.bold(i)} ${ee.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${_.accent("\u270E")} ${ee.cyan(o("file_path"))}`;case"Read":return ee.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let i=typeof t?.command=="string"?t.command.split(`
500
- `)[0].slice(0,70):"";return ee.dim(`$ ${i}`)}default:return`${_.blue("\u2192")} ${e}`}}var Qr=v(()=>{"use strict";f();R();N()});import{existsSync as Wl}from"fs";import{readFile as Jl}from"fs/promises";import{homedir as ql}from"os";import uo from"path";async function Zr(e){try{let t=await Jl(e,"utf-8");return JSON.parse(t)}catch{return}}async function se(e){let t=await Zr(fo),n=e?await Zr(uo.join(e,Kl)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},i=bn.safeParse(o);return i.success?i.data:(r.debug("Config validation issues:",i.error.flatten()),bn.parse({}))}function ta(){return ea}function go(){return fo}function ho(){return Wl(fo)}var ea,fo,Kl,be=v(()=>{"use strict";f();R();Be();ea=uo.join(ql(),".eds"),fo=uo.join(ea,"config.json"),Kl=".edsrc.json"});function na(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Xl(e,t="figma"){return e?e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0).map(n=>({width:n,label:na(n),source:t})):[]}function oa(e,t){let n=Xl(e,"figma");return n.length?n:Vl(t)}function Vl(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let i=Number(o?.width);if(!Number.isFinite(i)||i<=0||t.has(i))continue;t.add(i);let a=o.source;n.push({width:i,label:na(i),source:a==="figma"?"figma":"default"})}return n}var ia=v(()=>{"use strict";f()});async function Yl(){try{return(await import("playwright")).chromium}catch{throw new Error("Scraping needs Playwright. Install it with `npm i -D playwright` (it ships as an optional dependency), then `npx playwright install chromium`.")}}async function ra(e){let t=e.width??1440,n=await Yl(),o;try{o=await n.launch({headless:!0})}catch(i){let a=i instanceof Error?i.message:String(i);throw/Executable doesn't exist|install/i.test(a)?new Error("Chromium isn't installed for Playwright. Run `npx playwright install chromium`."):i}try{let i=await o.newPage({viewport:{width:t,height:900},deviceScaleFactor:1});await i.goto(e.url,{waitUntil:"networkidle",timeout:45e3}),await i.waitForTimeout(700);let a=await i.evaluate(Ql,{maxNodes:320,maxDepth:14,textCap:200}),s={source:`scrape:${e.provider}`,url:e.url,viewport:t,title:a.title,root:a.root,nodeCount:a.nodeCount,truncated:a.truncated};return JSON.stringify(s,null,2)}finally{await o.close()}}function Ql(e){let t=new Set(["SCRIPT","STYLE","NOSCRIPT","LINK","META","HEAD","BR","TEMPLATE"]),n=0,o=!1,i=c=>!c||c==="none"||c==="normal"||c==="auto"||c==="0px"||c==="rgba(0, 0, 0, 0)"||c==="transparent";function a(c){let p="";for(let m of Array.from(c.childNodes))m.nodeType===3&&(p+=m.textContent??"");return p=p.replace(/\s+/g," ").trim(),p.length>e.textCap?`${p.slice(0,e.textCap)}\u2026`:p}function s(c){let p=getComputedStyle(c),m={},u=(g,w)=>{i(w)||(m[g]=w)};return u("display",p.display),(p.display.includes("flex")||p.display.includes("grid"))&&(u("flexDirection",p.flexDirection),u("justifyContent",p.justifyContent),u("alignItems",p.alignItems),u("gap",p.gap)),u("padding",p.padding),u("margin",p.margin),u("color",p.color),u("background",p.backgroundColor),p.backgroundImage&&p.backgroundImage!=="none"&&(m.backgroundImage=p.backgroundImage.slice(0,160)),u("fontFamily",p.fontFamily),u("fontSize",p.fontSize),u("fontWeight",p.fontWeight),u("lineHeight",p.lineHeight),u("letterSpacing",p.letterSpacing),u("textAlign",p.textAlign),u("border",p.border),u("borderRadius",p.borderRadius),u("boxShadow",p.boxShadow),p.opacity&&p.opacity!=="1"&&(m.opacity=p.opacity),p.position&&p.position!=="static"&&(m.position=p.position),m}function d(c,p){if(n>=e.maxNodes)return o=!0,null;if(t.has(c.tagName))return null;let m=c.getBoundingClientRect(),u=getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden"||u.opacity==="0"||m.width<1||m.height<1)return null;n++;let w={tag:c.tagName.toLowerCase(),rect:{x:Math.round(m.x),y:Math.round(m.y),w:Math.round(m.width),h:Math.round(m.height)}},y=(c.getAttribute("class")||"").trim().split(/\s+/).filter(Boolean).slice(0,3);y.length&&(w.class=y.join(" "));let h=s(c);if(Object.keys(h).length&&(w.style=h),c.tagName==="IMG"){let b=c;w.img={src:(b.currentSrc||b.src||"").slice(0,200),alt:b.alt||"",w:b.naturalWidth,h:b.naturalHeight}}let $=a(c);if($&&(w.text=$),p<e.maxDepth){let b=[];for(let T of Array.from(c.children)){let Q=d(T,p+1);Q&&b.push(Q)}b.length&&(w.children=b)}return w}let l=d(document.body,0);return{title:document.title,root:l,nodeCount:n,truncated:o}}var aa=v(()=>{"use strict";f()});async function la(e){let{fileKey:t,nodeId:n,token:o}=e,i=n?`${wo}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${wo}/files/${t}`,a=await fetch(i,{headers:{"X-Figma-Token":o}});if(!a.ok){let s=await a.text().catch(()=>""),d=a.status===403?" (check the token scope: it needs file_content:read, and access to this file)":a.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${a.status} ${a.statusText}${d}${s?` \u2014 ${s.slice(0,200)}`:""}`)}return a.json()}async function da(e){let{fileKey:t,nodeId:n,token:o,scale:i=1}=e;if(!n)throw new Error("A node id is required to render a Figma image.");let a=`${wo}/images/${t}?ids=${encodeURIComponent(n)}&format=png&scale=${i}`,s=await fetch(a,{headers:{"X-Figma-Token":o}});if(!s.ok){let p=await s.text().catch(()=>"");throw new Error(`Figma images ${s.status} ${s.statusText}${p?` \u2014 ${p.slice(0,200)}`:""}`)}let d=await s.json();if(d.err)throw new Error(`Figma images: ${d.err}`);let l=d.images?.[n]??Object.values(d.images??{}).find(Boolean);if(!l)throw new Error("Figma returned no image URL for that node.");let c=await fetch(l);if(!c.ok)throw new Error(`Fetching the rendered image failed: ${c.status} ${c.statusText}`);return Buffer.from(await c.arrayBuffer())}function bo(e){if(!e)return;let t=o=>Math.round(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0"),n=`#${t(e.r)}${t(e.g)}${t(e.b)}`;return e.a!==void 0&&e.a<1?`${n}${t(e.a)}`:n}function ca(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return bo(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>bo(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function pa(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:s,height:d}=e.absoluteBoundingBox;s!=null&&d!=null&&(n.size={w:Math.round(s),h:Math.round(d)})}e.layoutMode&&e.layoutMode!=="NONE"&&(n.layout={direction:e.layoutMode==="HORIZONTAL"?"row":"column",gap:e.itemSpacing,padding:[e.paddingTop,e.paddingRight,e.paddingBottom,e.paddingLeft],align:[e.primaryAxisAlignItems,e.counterAxisAlignItems].filter(Boolean).join("/")});let o=ca(e.fills);o&&(n.fill=o);let i=ca(e.strokes);i&&(n.stroke={color:i,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let a=(e.effects??[]).filter(s=>s.visible!==!1&&(s.type==="DROP_SHADOW"||s.type==="INNER_SHADOW")).map(s=>`${s.type==="INNER_SHADOW"?"inset ":""}${s.offset?.x??0} ${s.offset?.y??0} ${s.radius??0} ${bo(s.color)??""}`.trim());if(a.length&&(n.shadows=a),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let s=e.style??{};n.font={family:s.fontFamily,size:s.fontSize,weight:s.fontWeight,lineHeight:s.lineHeightPx,letterSpacing:s.letterSpacing,align:s.textAlignHorizontal}}if(e.children?.length&&t<Zl){let s=e.children.slice(0,sa).map(d=>pa(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>sa&&(n.childrenTruncated=e.children.length)}return n}function ma(e,t){let n=e,o;if(t&&n.nodes){let a=Object.keys(n.nodes)[0];o=a?n.nodes[a]?.document:void 0}if(o??=n.document,!o)throw new Error("Figma REST response had no document node to serialize.");let i={source:"figma-rest",file:n.name,root:pa(o,0)};return JSON.stringify(i,null,2)}var wo,Zl,sa,yo=v(()=>{"use strict";f();wo="https://api.figma.com/v1";Zl=12,sa=60});import{existsSync as ed}from"fs";import{mkdir as td,readFile as nd,writeFile as od}from"fs/promises";import kt from"path";function id(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),i=`${o(t)}__${o(n??"file")}.json`;return kt.join(e,"tmp","eds-cli","design-cache",i)}function rd(e,t){let n=`scrape__${t.replace(/[^a-z0-9._-]/gi,"-").slice(0,120)}.json`;return kt.join(e,"tmp","eds-cli","design-cache",n)}function ad(e){return e==="framer"||e==="stitch"}async function ua(e){if(!ed(e))return null;try{return await nd(e,"utf-8")}catch{return null}}async function fa(e,t){await td(kt.dirname(e),{recursive:!0}),await od(e,t,"utf-8")}async function ga(e){let{figma:t,projectRoot:n}=e;if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};if(ad(e.provider)&&e.designUrl){let a=rd(n,e.designUrl),s=kt.relative(n,a);if(e.dryRun)return{design:{mode:"scrape",spec:`{ "note": "dry run \u2014 the live ${e.provider} page is scraped at generate time", "url": "${e.designUrl}" }`,cachePath:s},summary:`scrape (dry run) ${e.designUrl}`};if(!e.refresh){let d=await ua(a);if(d)return{design:{mode:"scrape",spec:d,cachePath:s},summary:`cache ${s}`}}try{let d=await ra({url:e.designUrl,provider:e.provider});return await fa(a,d),{design:{mode:"scrape",spec:d,cachePath:s},summary:`scrape \u2192 ${s}`}}catch(d){return{summary:"scrape failed",scrapeError:d instanceof Error?d.message:String(d)}}}if(!t?.fileKey)return{summary:"no design source"};let o=id(n,t.fileKey,t.nodeId),i=kt.relative(n,o);if(!e.refresh){let a=await ua(o);if(a)return{design:{mode:"spec",spec:a,cachePath:i},summary:`cache ${i}`}}if(e.token&&!e.preferMcp)try{let a=await la({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=ma(a,t.nodeId);return await fa(o,s),{design:{mode:"spec",spec:s,cachePath:i},summary:`REST \u2192 ${i}`}}catch(a){return{design:{mode:"mcp",cachePath:i},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:i},summary:"MCP (1 call, cached)"}}var ha=v(()=>{"use strict";f();aa();yo()});function tn(e){if(/^\d+[-:]\d+$/.test(e.trim()))throw new Error(`Input "${e}" looks like a node-id but not a full URL. Provide a Figma URL or use --file-key.`);let t;try{t=new URL(e.trim())}catch{throw new Error(`Invalid Figma URL: "${e}"`)}if(!t.hostname.endsWith("figma.com"))throw new Error(`Not a Figma URL: "${e}"`);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error(`Cannot extract fileKey from URL: "${e}"`);let o=n[0],i,a;n[2]==="branch"&&n[3]?(i=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(i=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?sd(s):void 0;return{fileKey:i,nodeId:d,fileName:a}}function sd(e){return decodeURIComponent(e).replace(/-/g,":")}var wa=v(()=>{"use strict";f()});import{existsSync as cd}from"fs";import{readFile as ld}from"fs/promises";import dd from"path";function pd(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",i="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
498
+ `;await io(bt.join(o,`${e}.js`),i),await io(bt.join(o,`${e}.css`),a);let s=t.ueModel!==!1;s&&await io(bt.join(o,`_${e}.json`),ea(e)),r.success(`Block "${e}" created at ${Zr.cyan(bt.relative(n,o))}${s?Zr.dim(" (+ Universal Editor model)"):""}`)}var ao=k(()=>{"use strict";f();R();z();Be()});import{existsSync as en}from"fs";import{readFile as Jl}from"fs/promises";import{homedir as We}from"os";import Je from"path";async function co(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function ta(e){if(!e||typeof e!="object")return;let t=e,n=t.mcpServers;if(n&&typeof n=="object"){for(let o of Object.keys(n))if(o.toLowerCase().includes("figma"))return o}for(let o of Object.values(t)){let i=ta(o);if(i)return i}}async function lo(e){for(let t of e)try{if(!en(t))continue;let n=await Jl(t,"utf-8");try{let o=ta(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function na(e){if(e){let t=so.find(n=>n.type===e);if(t){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);return{type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}r.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of so){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);return{type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function tn(){let e=[];for(let t of so){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var so,mo=k(()=>{"use strict";f();R();so=[{type:"claude",binary:"claude",configDir:Je.join(We(),".claude"),mcpConfigPaths:[Je.join(We(),".claude","plugins.json"),Je.join(We(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Je.join(We(),".cursor"),mcpConfigPaths:[Je.join(We(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Je.join(We(),".codex"),mcpConfigPaths:[]}]});import{mkdir as ql,readFile as Kl,writeFile as Xl}from"fs/promises";import{tmpdir as Vl}from"os";import yt from"path";import Yl from"readline";import te from"chalk";async function po(e,t){let n=t?yt.join(t,"tmp"):Vl(),o=yt.join(n,"eds-cli");await ql(o,{recursive:!0});let i=`from-design-${Date.now()}.md`,a=yt.join(o,i);return await Xl(a,e,"utf-8"),a}async function uo(e,t,n,o){let{execa:i}=await import("execa"),a=await Kl(t,"utf-8");try{switch(e.type){case"claude":{r.info(`Running Claude Code ${te.dim("- live log:")}`);let s=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],d=[...new Set(s.map(m=>`mcp__${m}`)),"Edit","Write","Read"].join(","),c=i("claude",["-p",a,"--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",d],{cwd:n,buffer:!1,stdio:["ignore","pipe","inherit"]});await Zl(c,n);break}case"cursor":{r.info("Running Cursor agent..."),await i("cursor",["--prompt",a],{cwd:n,stdio:"inherit"});break}case"codex":{r.info("Running Codex..."),await i("codex",[a],{cwd:n,stdio:"inherit"});break}}return!0}catch(s){let d=s instanceof Error?s.message:String(s);return r.error(`Agent ${e.type} failed: ${d}`),!1}}function Ql(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function Zl(e,t){let n=(await import("ora")).default,o=Date.now(),i=()=>`${Math.round((Date.now()-o)/1e3)}s`,a=n({text:`thinking ${te.dim(i())}`,color:"yellow"}).start(),s="thinking",d=setInterval(()=>{a.text=`${s} ${te.dim(i())}`},300),l=new Map,c=p=>{a.stop(),r.info(` ${p}`),a.start()},m;try{if(e.stdout){let p=Yl.createInterface({input:e.stdout});for await(let u of p){let g=u.trim();if(!g)continue;let h;try{h=JSON.parse(g)}catch{continue}let b=Array.isArray(h.message?.content)?h.message.content:[];if(h.type==="assistant"){for(let w of b)if(w.type==="text"&&"text"in w){let y=w.text.trim().split(`
499
+ `)[0].slice(0,100);y&&c(te.dim(y))}else if(w.type==="tool_use"&&"name"in w){let y="id"in w&&w.id?w.id:`${Math.random()}`;l.set(y,{label:ed(w.name,w.input,t),start:Date.now()}),s=Ql(w.name)}}else if(h.type==="user"){for(let w of b)if(w.type==="tool_result"&&"tool_use_id"in w&&w.tool_use_id){let y=l.get(w.tool_use_id);if(y){let v=`${((Date.now()-y.start)/1e3).toFixed(1)}s`,T="is_error"in w&&w.is_error?` ${te.red("failed")}`:"";c(`${y.label} ${te.dim(v)}${T}`),l.delete(w.tool_use_id)}}}else if(h.type==="result"){let w=typeof h.duration_ms=="number"?`${(h.duration_ms/1e3).toFixed(1)}s`:"",y=typeof h.total_cost_usd=="number"?`$${h.total_cost_usd.toFixed(3)}`:"";m=[w,y].filter(Boolean).join(" \xB7 ")||"done"}}}for(let p of l.values())c(`${p.label} ${te.dim("\u2026")}`);clearInterval(d),m?a.succeed(`${U.accent("agent finished")} ${te.dim(m)}`):a.stop()}catch(p){throw clearInterval(d),a.stop(),p}await e}function ed(e,t,n){let o=i=>{let a=t?.[i];return typeof a!="string"?"":a.startsWith(n)?yt.relative(n,a):yt.basename(a)};if(e.includes("figma")){let i=e.split("__").pop()??e;return`${W.figma} ${te.bold(i)} ${te.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${U.accent("\u270E")} ${te.cyan(o("file_path"))}`;case"Read":return te.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let i=typeof t?.command=="string"?t.command.split(`
500
+ `)[0].slice(0,70):"";return te.dim(`$ ${i}`)}default:return`${U.blue("\u2192")} ${e}`}}var oa=k(()=>{"use strict";f();R();M()});import{existsSync as td}from"fs";import{readFile as nd}from"fs/promises";import{homedir as od}from"os";import fo from"path";async function ia(e){try{let t=await nd(e,"utf-8");return JSON.parse(t)}catch{return}}async function le(e){let t=await ia(go),n=e?await ia(fo.join(e,id)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},i=yn.safeParse(o);return i.success?i.data:(r.debug("Config validation issues:",i.error.flatten()),yn.parse({}))}function aa(){return ra}function ho(){return go}function wo(){return td(go)}var ra,go,id,ye=k(()=>{"use strict";f();R();Be();ra=fo.join(od(),".eds"),go=fo.join(ra,"config.json"),id=".edsrc.json"});function sa(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function rd(e,t="figma"){return e?e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0).map(n=>({width:n,label:sa(n),source:t})):[]}function ca(e,t){let n=rd(e,"figma");return n.length?n:ad(t)}function ad(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let i=Number(o?.width);if(!Number.isFinite(i)||i<=0||t.has(i))continue;t.add(i);let a=o.source;n.push({width:i,label:sa(i),source:a==="figma"?"figma":"default"})}return n}var la=k(()=>{"use strict";f()});import{existsSync as sd}from"fs";import{createRequire as cd}from"module";import ld from"path";import{pathToFileURL as da}from"url";async function ma(e){try{return(await import("playwright")).chromium}catch{}let t=[e,process.cwd()].filter(n=>!!n);if(t.length)try{let o=cd(da(ld.join(t[0],"package.json")).href).resolve("playwright",{paths:t});return(await import(da(o).href)).chromium}catch{}throw new Error("Scraping needs Playwright. Install it in your project (`npm i -D playwright`) or globally (`npm i -g playwright`), then `npx playwright install chromium`.")}async function pa(e){let t=e.width??1440,n=await ma(e.projectRoot),o;try{o=await n.launch({headless:!0})}catch(i){let a=i instanceof Error?i.message:String(i);throw/Executable doesn't exist|install/i.test(a)?new Error("Chromium isn't installed for Playwright. Run `npx playwright install chromium`."):i}try{let i=e.storageStatePath&&sd(e.storageStatePath),s=await(await o.newContext({viewport:{width:t,height:900},deviceScaleFactor:1,...i?{storageState:e.storageStatePath}:{}})).newPage();await s.goto(e.url,{waitUntil:"networkidle",timeout:45e3}),await s.waitForTimeout(700);let d=await s.evaluate(dd,{maxNodes:320,maxDepth:14,textCap:200}),l={source:`scrape:${e.provider}`,url:e.url,viewport:t,authenticated:!!i,title:d.title,root:d.root,nodeCount:d.nodeCount,truncated:d.truncated};return JSON.stringify(l,null,2)}finally{await o.close()}}async function ua(e){let n=await(await ma(e.projectRoot)).launch({headless:!1});try{let o=await n.newContext();await(await o.newPage()).goto(e.loginUrl,{waitUntil:"domcontentloaded",timeout:6e4}),await e.waitForUser(),await o.storageState({path:e.statePath})}finally{await n.close()}}function dd(e){let t=new Set(["SCRIPT","STYLE","NOSCRIPT","LINK","META","HEAD","BR","TEMPLATE"]),n=0,o=!1,i=c=>!c||c==="none"||c==="normal"||c==="auto"||c==="0px"||c==="rgba(0, 0, 0, 0)"||c==="transparent";function a(c){let m="";for(let p of Array.from(c.childNodes))p.nodeType===3&&(m+=p.textContent??"");return m=m.replace(/\s+/g," ").trim(),m.length>e.textCap?`${m.slice(0,e.textCap)}\u2026`:m}function s(c){let m=getComputedStyle(c),p={},u=(g,h)=>{i(h)||(p[g]=h)};return u("display",m.display),(m.display.includes("flex")||m.display.includes("grid"))&&(u("flexDirection",m.flexDirection),u("justifyContent",m.justifyContent),u("alignItems",m.alignItems),u("gap",m.gap)),u("padding",m.padding),u("margin",m.margin),u("color",m.color),u("background",m.backgroundColor),m.backgroundImage&&m.backgroundImage!=="none"&&(p.backgroundImage=m.backgroundImage.slice(0,160)),u("fontFamily",m.fontFamily),u("fontSize",m.fontSize),u("fontWeight",m.fontWeight),u("lineHeight",m.lineHeight),u("letterSpacing",m.letterSpacing),u("textAlign",m.textAlign),u("border",m.border),u("borderRadius",m.borderRadius),u("boxShadow",m.boxShadow),m.opacity&&m.opacity!=="1"&&(p.opacity=m.opacity),m.position&&m.position!=="static"&&(p.position=m.position),p}function d(c,m){if(n>=e.maxNodes)return o=!0,null;if(t.has(c.tagName))return null;let p=c.getBoundingClientRect(),u=getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden"||u.opacity==="0"||p.width<1||p.height<1)return null;n++;let h={tag:c.tagName.toLowerCase(),rect:{x:Math.round(p.x),y:Math.round(p.y),w:Math.round(p.width),h:Math.round(p.height)}},b=(c.getAttribute("class")||"").trim().split(/\s+/).filter(Boolean).slice(0,3);b.length&&(h.class=b.join(" "));let w=s(c);if(Object.keys(w).length&&(h.style=w),c.tagName==="IMG"){let v=c;h.img={src:(v.currentSrc||v.src||"").slice(0,200),alt:v.alt||"",w:v.naturalWidth,h:v.naturalHeight}}let y=a(c);if(y&&(h.text=y),m<e.maxDepth){let v=[];for(let T of Array.from(c.children)){let K=d(T,m+1);K&&v.push(K)}v.length&&(h.children=v)}return h}let l=d(document.body,0);return{title:document.title,root:l,nodeCount:n,truncated:o}}var bo=k(()=>{"use strict";f()});async function ha(e){let{fileKey:t,nodeId:n,token:o}=e,i=n?`${yo}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${yo}/files/${t}`,a=await fetch(i,{headers:{"X-Figma-Token":o}});if(!a.ok){let s=await a.text().catch(()=>""),d=a.status===403?" (check the token scope: it needs file_content:read, and access to this file)":a.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${a.status} ${a.statusText}${d}${s?` \u2014 ${s.slice(0,200)}`:""}`)}return a.json()}async function wa(e){let{fileKey:t,nodeId:n,token:o,scale:i=1}=e;if(!n)throw new Error("A node id is required to render a Figma image.");let a=`${yo}/images/${t}?ids=${encodeURIComponent(n)}&format=png&scale=${i}`,s=await fetch(a,{headers:{"X-Figma-Token":o}});if(!s.ok){let m=await s.text().catch(()=>"");throw new Error(`Figma images ${s.status} ${s.statusText}${m?` \u2014 ${m.slice(0,200)}`:""}`)}let d=await s.json();if(d.err)throw new Error(`Figma images: ${d.err}`);let l=d.images?.[n]??Object.values(d.images??{}).find(Boolean);if(!l)throw new Error("Figma returned no image URL for that node.");let c=await fetch(l);if(!c.ok)throw new Error(`Fetching the rendered image failed: ${c.status} ${c.statusText}`);return Buffer.from(await c.arrayBuffer())}function vo(e){if(!e)return;let t=o=>Math.round(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0"),n=`#${t(e.r)}${t(e.g)}${t(e.b)}`;return e.a!==void 0&&e.a<1?`${n}${t(e.a)}`:n}function ga(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return vo(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>vo(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function ba(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:s,height:d}=e.absoluteBoundingBox;s!=null&&d!=null&&(n.size={w:Math.round(s),h:Math.round(d)})}e.layoutMode&&e.layoutMode!=="NONE"&&(n.layout={direction:e.layoutMode==="HORIZONTAL"?"row":"column",gap:e.itemSpacing,padding:[e.paddingTop,e.paddingRight,e.paddingBottom,e.paddingLeft],align:[e.primaryAxisAlignItems,e.counterAxisAlignItems].filter(Boolean).join("/")});let o=ga(e.fills);o&&(n.fill=o);let i=ga(e.strokes);i&&(n.stroke={color:i,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let a=(e.effects??[]).filter(s=>s.visible!==!1&&(s.type==="DROP_SHADOW"||s.type==="INNER_SHADOW")).map(s=>`${s.type==="INNER_SHADOW"?"inset ":""}${s.offset?.x??0} ${s.offset?.y??0} ${s.radius??0} ${vo(s.color)??""}`.trim());if(a.length&&(n.shadows=a),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let s=e.style??{};n.font={family:s.fontFamily,size:s.fontSize,weight:s.fontWeight,lineHeight:s.lineHeightPx,letterSpacing:s.letterSpacing,align:s.textAlignHorizontal}}if(e.children?.length&&t<md){let s=e.children.slice(0,fa).map(d=>ba(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>fa&&(n.childrenTruncated=e.children.length)}return n}function ya(e,t){let n=e,o;if(t&&n.nodes){let a=Object.keys(n.nodes)[0];o=a?n.nodes[a]?.document:void 0}if(o??=n.document,!o)throw new Error("Figma REST response had no document node to serialize.");let i={source:"figma-rest",file:n.name,root:ba(o,0)};return JSON.stringify(i,null,2)}var yo,md,fa,ko=k(()=>{"use strict";f();yo="https://api.figma.com/v1";md=12,fa=60});import{existsSync as pd}from"fs";import{mkdir as ud,readFile as fd,writeFile as gd}from"fs/promises";import vt from"path";function hd(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),i=`${o(t)}__${o(n??"file")}.json`;return vt.join(e,"tmp","eds-cli","design-cache",i)}function wd(e,t){let n=`scrape__${t.replace(/[^a-z0-9._-]/gi,"-").slice(0,120)}.json`;return vt.join(e,"tmp","eds-cli","design-cache",n)}function xo(e){return e==="framer"||e==="stitch"}async function va(e){if(!pd(e))return null;try{return await fd(e,"utf-8")}catch{return null}}async function ka(e,t){await ud(vt.dirname(e),{recursive:!0}),await gd(e,t,"utf-8")}async function xa(e){let{figma:t,projectRoot:n}=e;if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};if(xo(e.provider)&&e.designUrl){let a=wd(n,e.designUrl),s=vt.relative(n,a);if(e.dryRun)return{design:{mode:"scrape",spec:`{ "note": "dry run \u2014 the live ${e.provider} page is scraped at generate time", "url": "${e.designUrl}" }`,cachePath:s},summary:`scrape (dry run) ${e.designUrl}`};if(!e.refresh){let d=await va(a);if(d)return{design:{mode:"scrape",spec:d,cachePath:s},summary:`cache ${s}`}}try{let d=await pa({url:e.designUrl,provider:e.provider,projectRoot:n,storageStatePath:e.storageStatePath});return await ka(a,d),{design:{mode:"scrape",spec:d,cachePath:s},summary:`scrape \u2192 ${s}`}}catch(d){return{summary:"scrape failed",scrapeError:d instanceof Error?d.message:String(d)}}}if(!t?.fileKey)return{summary:"no design source"};let o=hd(n,t.fileKey,t.nodeId),i=vt.relative(n,o);if(!e.refresh){let a=await va(o);if(a)return{design:{mode:"spec",spec:a,cachePath:i},summary:`cache ${i}`}}if(e.token&&!e.preferMcp)try{let a=await ha({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=ya(a,t.nodeId);return await ka(o,s),{design:{mode:"spec",spec:s,cachePath:i},summary:`REST \u2192 ${i}`}}catch(a){return{design:{mode:"mcp",cachePath:i},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:i},summary:"MCP (1 call, cached)"}}var $a=k(()=>{"use strict";f();bo();ko()});function nn(e){if(/^\d+[-:]\d+$/.test(e.trim()))throw new Error(`Input "${e}" looks like a node-id but not a full URL. Provide a Figma URL or use --file-key.`);let t;try{t=new URL(e.trim())}catch{throw new Error(`Invalid Figma URL: "${e}"`)}if(!t.hostname.endsWith("figma.com"))throw new Error(`Not a Figma URL: "${e}"`);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error(`Cannot extract fileKey from URL: "${e}"`);let o=n[0],i,a;n[2]==="branch"&&n[3]?(i=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(i=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?bd(s):void 0;return{fileKey:i,nodeId:d,fileName:a}}function bd(e){return decodeURIComponent(e).replace(/-/g,":")}var Sa=k(()=>{"use strict";f()});import{existsSync as yd}from"fs";import{readFile as vd}from"fs/promises";import kd from"path";function xd(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",i="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
501
501
  ## Content source: Content Fragment
502
502
  This block renders an AEM **Content Fragment**${o} - not inline-authored copy.
503
503
  - UE model: use an \`aem-content-fragment\` field (e.g. \`name: "fragment"\`) for the CF reference.
@@ -510,35 +510,35 @@ This block mixes **two sources in one model and one \`decorate(block)\`**:
510
510
  - **Inline (UE-authored)** parts \u2192 normal fields (text / richtext / image / select) read straight from the authored DOM cells, with semantic collapsing.
511
511
  - **Content Fragment** part${o} \u2192 an \`aem-content-fragment\` field; \`decorate()\` is **async** and also fetches that CF via a GraphQL persisted query (${i}) and renders its fields.
512
512
  - Field order in the model = cell order in the authored DOM. Read the inline cells by position; detect the CF reference by its \`/content/dam/\` link. Merge both into the final markup, and handle the CF loading/empty/error states.
513
- `}async function ba(e){let t=await md(e.projectRoot),n=pd(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,i=e.provider??"figma",a=qe[i],s=e.design,d=s?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(s.filePath):!1,c=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
513
+ `}async function ja(e){let t=await $d(e.projectRoot),n=xd(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,i=e.provider??"figma",a=qe[i],s=e.design,d=s?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(s.filePath):!1,c=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
514
514
  Do **exactly one** self-check \u2014 do **not** loop:
515
515
  1. Compare your implementation to ${s?.mode==="spec"?"the exact values in the embedded design data from Step 1":s?.mode==="scrape"?"the exact values in the scraped design data from Step 1":s?.mode==="file"?d?"the local design image":"the exact values in the local SVG":s?.mode==="mcp"?"the exact values from the `get_design_context` you cached":o?"the `get_screenshot` image":"the exact values from `get_design_context`"} once, across: spacing, fonts, colors, radius, shadows, alignment and proportions.
516
516
  2. Apply **one** round of corrections, then **stop** \u2014 don't iterate to "pixel perfect". The author reviews the result in the live preview (\`eds block preview\`) and will request another pass with specific feedback if needed.
517
- 3. Briefly state what you checked and any value you had to infer.`,p=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,m;s?.mode==="spec"?m=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
517
+ 3. Briefly state what you checked and any value you had to infer.`,m=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,p;s?.mode==="spec"?p=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
518
518
  The design was already fetched for you and is embedded below \u2014 **do not call any Figma MCP tool** (\`get_design_context\`, \`get_variable_defs\`, \`get_screenshot\`). Parse it for the exact structure, layout, spacing, colors, typography, radius and effects.
519
519
 
520
520
  \`\`\`json
521
521
  ${s.spec}
522
522
  \`\`\`
523
523
 
524
- Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="scrape"?m=`## Step 1 \u2014 Use the Scraped Design Data (no MCP)
524
+ Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="scrape"?p=`## Step 1 \u2014 Use the Scraped Design Data (no MCP)
525
525
  The design was scraped from the live **${a}** page (${e.designRef??"the URL"}) with headless Chromium and is embedded below \u2014 **do not call any MCP tool** and **do not fetch the URL yourself**. The tree holds **computed** values: geometry (\`rect\` x/y/w/h, px), layout (\`display\`/\`flexDirection\`/\`gap\`/\`padding\`), colours, typography, radius and shadows. Use them verbatim (convert px\u2192rem where appropriate) and regroup the flattened DOM into semantic structure yourself (Step 3).
526
526
 
527
527
  \`\`\`json
528
528
  ${s.spec}
529
529
  \`\`\`
530
530
 
531
- The scraped **text and images are reference content**, not authored copy \u2014 reproduce the layout/styling exactly, but read real content from the authored DOM at runtime and fall back to placeholders (see the Placeholders section). Do **not** hardcode the scraped copy or ship the scraped image URLs.`:s?.mode==="file"?m=`## Step 1 \u2014 Read the Local Design Export (no MCP)
531
+ The scraped **text and images are reference content**, not authored copy \u2014 reproduce the layout/styling exactly, but read real content from the authored DOM at runtime and fall back to placeholders (see the Placeholders section). Do **not** hardcode the scraped copy or ship the scraped image URLs.`:s?.mode==="file"?p=`## Step 1 \u2014 Read the Local Design Export (no MCP)
532
532
  Read \`${s.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
533
533
 
534
- ${d?"It's a raster image (PNG/JPG) \u2014 open it and reproduce it visually: infer spacing, colors, typography, radius, shadows and layout as precisely as you can from the pixels.":"It's an **SVG** \u2014 read it as text and parse the **exact** values: geometry and positions (x/y/width/height, `viewBox`), text and typography (font-family / font-size / font-weight on `<text>`/`<tspan>`), fills and gradients, strokes, and effects. Use the numbers verbatim, converting px\u2192rem where appropriate. The SVG is flattened \u2014 regroup into semantic structure yourself (Step 3), don't mirror raw `<g>`/`<path>` nesting."}`:s?.mode==="mcp"?m=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
534
+ ${d?"It's a raster image (PNG/JPG) \u2014 open it and reproduce it visually: infer spacing, colors, typography, radius, shadows and layout as precisely as you can from the pixels.":"It's an **SVG** \u2014 read it as text and parse the **exact** values: geometry and positions (x/y/width/height, `viewBox`), text and typography (font-family / font-size / font-weight on `<text>`/`<tspan>`), fills and gradients, strokes, and effects. Use the numbers verbatim, converting px\u2192rem where appropriate. The SVG is flattened \u2014 regroup into semantic structure yourself (Step 3), don't mirror raw `<g>`/`<path>` nesting."}`:s?.mode==="mcp"?p=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
535
535
  Call **\`get_design_context\` exactly once** for the target node. Do **not** call \`get_variable_defs\` or \`get_screenshot\` \u2014 each extra MCP call burns the Figma plan's scarce tool-call budget; derive colors and tokens from the context you already got.
536
536
  **Immediately after**, \`Write\` the raw design data you received to \`${s.cachePath}\` (pretty JSON) so re-runs and refine passes reuse it without another MCP call. Then generate from it.
537
537
 
538
- ${p}`:i==="figma"?m=`## Step 1 \u2014 Fetch the Design (single MCP call)
538
+ ${m}`:i==="figma"?p=`## Step 1 \u2014 Fetch the Design (single MCP call)
539
539
  Call **\`get_design_context\` exactly once** for the target node \u2014 it returns structure, layout, measurements, text and the colors/tokens you need. Do **not** call \`get_variable_defs\`${o?"":" or `get_screenshot`"} \u2014 each extra MCP call burns the Figma plan's scarce budget.${o?" You may call `get_screenshot` once (`maxDimension: 1024`) for the Step 5 check.":""}
540
540
 
541
- ${p}`:m=`## Step 1 \u2014 Read the Design
541
+ ${m}`:p=`## Step 1 \u2014 Read the Design
542
542
  Open the live **${a}** page at \`${e.designRef??"(the design URL)"}\` and read its rendered layout, typography, colours, spacing, radius and effects. Extract the **exact** values \u2014 do not approximate.`;let u=e.withUeModel?`
543
543
  ## Step 4b \u2014 Universal Editor Authoring (REQUIRED, not optional)
544
544
  Authors must be able to drop and edit this block in the Universal Editor, so generate its UE configuration **in the same pass** as the code.
@@ -614,14 +614,14 @@ Rules:
614
614
  If the project uses a **single aggregated model file** (\`component-definition.json\` + \`component-models.json\` + \`component-filters.json\`) instead of per-block \`_${e.blockName}.json\`, detect that convention and add the block's definition/model/filter to those files instead (and register the block in the \`section\` filter). Prefer the per-block \`_${e.blockName}.json\` when neither exists. Full field reference and a repeatable-cards round-trip example: \`docs/universal-editor-fields.md\`.
615
615
 
616
616
  **Reusable field groups (partials):** when the design shows one of these common shapes, reuse the standard group instead of inventing fields \u2014 same groups \`eds model add\` uses, so the model stays consistent across the project:
617
- ${ze.map(y=>`- \`${y.id}\` \u2014 ${y.label}`).join(`
617
+ ${ze.map(b=>`- \`${b.id}\` \u2014 ${b.label}`).join(`
618
618
  `)}
619
- `:"",g=s?.mode==="file"?"a design export":a,w=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
619
+ `:"",g=s?.mode==="file"?"a design export":a,h=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
620
620
 
621
621
  ## Task
622
- Generate an AEM Edge Delivery Services block named **\`${e.blockName}\`** that reproduces the ${w} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
622
+ Generate an AEM Edge Delivery Services block named **\`${e.blockName}\`** that reproduces the ${h} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
623
623
 
624
- ${m}
624
+ ${p}
625
625
 
626
626
  ## Step 2 \u2014 Extract Exact Values
627
627
  From the design data you fetched, record the **precise** values \u2014 do not approximate:
@@ -698,8 +698,8 @@ ${t}
698
698
  Finally, record the design's frame width(s) you read in Step 1 into \`blocks/${e.blockName}/.eds-meta.json\` as \`{ "breakpoints": [{ "width": <px>, "source": "${s?.mode==="scrape"?"scrape":i}" }] }\` (one entry per distinct frame width). The CLI merges this so \`eds block preview\` shows the block at the **real design widths**, not a fixed device set.
699
699
 
700
700
  ---
701
- *Prompt version: ${xt}*
702
- `}function ya(e){let t=e.provider??"figma",n=t==="figma"&&e.figma?.fileKey?`If the change needs design values, re-read **only what you need** from Figma (fileKey \`${e.figma.fileKey}\`${e.figma.nodeId?`, node \`${e.figma.nodeId}\``:""}) \u2014 don't re-fetch the whole design.`:"Use the values already in the files (and the cached design snapshot under `tmp/eds-cli/design-cache/` if present); infer sensibly if the request is purely stylistic.";return`# Refine the \`${e.blockName}\` EDS block
701
+ *Prompt version: ${kt}*
702
+ `}function Pa(e){let t=e.provider??"figma",n=t==="figma"&&e.figma?.fileKey?`If the change needs design values, re-read **only what you need** from Figma (fileKey \`${e.figma.fileKey}\`${e.figma.nodeId?`, node \`${e.figma.nodeId}\``:""}) \u2014 don't re-fetch the whole design.`:"Use the values already in the files (and the cached design snapshot under `tmp/eds-cli/design-cache/` if present); infer sensibly if the request is purely stylistic.";return`# Refine the \`${e.blockName}\` EDS block
703
703
 
704
704
  The block already exists in \`blocks/${e.blockName}/\` and the author reviewed it in the live preview. Apply **this change** and nothing else:
705
705
 
@@ -718,8 +718,8 @@ The block already exists in \`blocks/${e.blockName}/\` and the author reviewed i
718
718
  - **No shell access:** only read/write files${t==="figma"?" and call the Figma MCP":""}. Do **not** run \`eslint\`, \`stylelint\`, \`npm\`, \`npx\`, \`tsc\`, a build, or any Bash command \u2014 they aren't granted and just fail.
719
719
  - **Minimise chat output:** edit files directly, don't paste code back. End with a **\u22642-line** summary of what changed.
720
720
 
721
- *Prompt version: ${xt}*
722
- `}async function md(e){let t=dd.join(e,"styles","styles.css");if(!cd(t))return"";try{let o=(await ld(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let i=o[1].split(`
721
+ *Prompt version: ${kt}*
722
+ `}async function $d(e){let t=kd.join(e,"styles","styles.css");if(!yd(t))return"";try{let o=(await vd(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let i=o[1].split(`
723
723
  `).filter(a=>a.trim().startsWith("--")).map(a=>a.trim()).join(`
724
724
  `);return i?`
725
725
  ## Existing Project Tokens
@@ -731,7 +731,7 @@ Reuse them instead of hardcoding values:
731
731
  ${i}
732
732
  }
733
733
  \`\`\`
734
- `:""}catch{return""}}var xt,qe,va=v(()=>{"use strict";f();Xn();xt="0.7.0",qe={figma:"Figma",framer:"Framer",stitch:"Google Stitch"}});function ce(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ud(e){let t=e,n=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(t=n[1]),t.replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?(?:html|head|body)[^>]*>/gi,"").replace(/<link\b[^>]*>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<!--[\s\S]*?-->/g,"").trim()}function nn(e){let{blockName:t}=e,n=ud(e.sampleContent);return`<!DOCTYPE html>
734
+ `:""}catch{return""}}var kt,qe,Ea=k(()=>{"use strict";f();Vn();kt="0.7.0",qe={figma:"Figma",framer:"Framer",stitch:"Google Stitch"}});import{existsSync as Sd}from"fs";import{chmod as jd,mkdir as Pd}from"fs/promises";import{homedir as Ed}from"os";import Ca from"path";function $o(e){return Ca.join(Ed(),".eds","auth",`${e}.json`)}function Aa(e){return Sd($o(e))}async function Ta(e){await Pd(Ca.dirname(e),{recursive:!0,mode:448})}async function Ra(e){try{await jd(e,384)}catch{}}var Fa=k(()=>{"use strict";f()});function de(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Cd(e){let t=e,n=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(t=n[1]),t.replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?(?:html|head|body)[^>]*>/gi,"").replace(/<link\b[^>]*>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<!--[\s\S]*?-->/g,"").trim()}function on(e){let{blockName:t}=e,n=Cd(e.sampleContent);return`<!DOCTYPE html>
735
735
  <html lang="en">
736
736
  <head>
737
737
  <meta charset="utf-8" />
@@ -761,9 +761,9 @@ ${n}
761
761
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
762
762
  </script>
763
763
  </body>
764
- </html>`}function fd(e){let t=e.filter(n=>n.figma);return(t.length?t:e).reduce((n,o)=>o.width>n.width?o:n,e[0])}function ka(e){let t=e.map((o,i)=>{let a=fd(o.breakpoints),s=o.breakpoints.map(c=>`<option value="${c.width}"${c.width===a.width?" selected":""}>${ce(c.label)}</option>`).join(""),d=o.figmaUrl?`<a class="figma-link" href="${ce(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",l=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
764
+ </html>`}function Ad(e){let t=e.filter(n=>n.figma);return(t.length?t:e).reduce((n,o)=>o.width>n.width?o:n,e[0])}function Da(e){let t=e.map((o,i)=>{let a=Ad(o.breakpoints),s=o.breakpoints.map(c=>`<option value="${c.width}"${c.width===a.width?" selected":""}>${de(c.label)}</option>`).join(""),d=o.figmaUrl?`<a class="figma-link" href="${de(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",l=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
765
765
  <div class="cardbar">
766
- <span class="block">${ce(o.blockName)}</span>
766
+ <span class="block">${de(o.blockName)}</span>
767
767
  <select class="bp" data-i="${i}">
768
768
  ${s}
769
769
  <option value="full">Full</option>
@@ -773,7 +773,7 @@ ${n}
773
773
  </div>
774
774
  <div class="stage">
775
775
  <div class="device" data-i="${i}" data-w="${a.width}" style="width:${a.width}px">
776
- <iframe src="${ce(o.frameRoute)}" title="${ce(o.blockName)} preview" loading="lazy"></iframe>
776
+ <iframe src="${de(o.frameRoute)}" title="${de(o.blockName)} preview" loading="lazy"></iframe>
777
777
  </div>
778
778
  </div>
779
779
  </section>`}).join(`
@@ -822,16 +822,16 @@ ${n}
822
822
  try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
823
823
  </script>
824
824
  </body>
825
- </html>`}function xa(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:i,placeholder:a}=e,s=n.filter(m=>m.figma),d=(s.length?s:n).reduce((m,u)=>u.width>m.width?u:m,n[0]),l=n.map(m=>`<option value="${m.width}"${m.width===d.width?" selected":""}>${ce(m.label)}</option>`).join(`
826
- `),c=o?`<a class="figma-link" href="${ce(o)}" target="_blank" rel="noopener">
825
+ </html>`}function La(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:i,placeholder:a}=e,s=n.filter(p=>p.figma),d=(s.length?s:n).reduce((p,u)=>u.width>p.width?u:p,n[0]),l=n.map(p=>`<option value="${p.width}"${p.width===d.width?" selected":""}>${de(p.label)}</option>`).join(`
826
+ `),c=o?`<a class="figma-link" href="${de(o)}" target="_blank" rel="noopener">
827
827
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>
828
828
  Open in Figma
829
- </a>`:"",p=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
829
+ </a>`:"",m=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
830
830
  <html lang="en">
831
831
  <head>
832
832
  <meta charset="utf-8" />
833
833
  <meta name="viewport" content="width=device-width, initial-scale=1" />
834
- <title>eds preview \u2014 ${ce(t)}</title>
834
+ <title>eds preview \u2014 ${de(t)}</title>
835
835
  <style>
836
836
  *{box-sizing:border-box}
837
837
  html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
@@ -853,18 +853,18 @@ ${n}
853
853
  </head>
854
854
  <body>
855
855
  <div class="bar">
856
- <span class="label">Block</span><span class="block">${ce(t)}</span>
856
+ <span class="label">Block</span><span class="block">${de(t)}</span>
857
857
  <label class="label" for="bp" style="margin-left:8px">Breakpoint</label>
858
858
  <select id="bp">
859
859
  ${l}
860
860
  <option value="full">Full ca\u0142a szeroko\u015B\u0107</option>
861
861
  </select>
862
- ${p}
862
+ ${m}
863
863
  ${c}
864
864
  </div>
865
865
  <div class="stage">
866
866
  <div class="device" id="device" data-w="${d.width}" style="width:${d.width}px">
867
- <iframe id="frame" src="${i}" title="${ce(t)} preview"></iframe>
867
+ <iframe id="frame" src="${i}" title="${de(t)} preview"></iframe>
868
868
  </div>
869
869
  </div>
870
870
  <script>
@@ -878,24 +878,24 @@ ${n}
878
878
  setWidth(Number(bp.value));
879
879
  </script>
880
880
  </body>
881
- </html>`}var $a=v(()=>{"use strict";f()});import{createReadStream as gd,existsSync as hd,statSync as wd}from"fs";import bd from"http";import vo from"path";function on(e,t,n,o="127.0.0.1",i){let a=vo.resolve(e),s=new Set,d=bd.createServer(async(l,c)=>{let p=decodeURIComponent((l.url??"/").split("?")[0]);if(p===vd){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({eds:!0}));return}if(p===kd){c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(`: connected
881
+ </html>`}var Oa=k(()=>{"use strict";f()});import{createReadStream as Td,existsSync as Rd,statSync as Fd}from"fs";import Dd from"http";import So from"path";function rn(e,t,n,o="127.0.0.1",i){let a=So.resolve(e),s=new Set,d=Dd.createServer(async(l,c)=>{let m=decodeURIComponent((l.url??"/").split("?")[0]);if(m===Od){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({eds:!0}));return}if(m===Nd){c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(`: connected
882
882
 
883
- `),s.add(c),l.on("close",()=>s.delete(c));return}let m=t[p];if(m){c.writeHead(200,{"content-type":m.type}),c.end(m.body);return}if(i)try{let g=await i(p);if(g){c.writeHead(200,{"content-type":g.type}),c.end(g.body);return}}catch(g){c.writeHead(500,{"content-type":"text/plain"}),c.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let u=vo.join(a,p);if(!u.startsWith(a)){c.writeHead(403),c.end("Forbidden");return}if(!hd(u)||!wd(u).isFile()){c.writeHead(404,{"content-type":"text/plain"}),c.end(`Not found: ${p}`);return}c.writeHead(200,{"content-type":yd[vo.extname(u).toLowerCase()]??"application/octet-stream"}),gd(u).pipe(c)});return new Promise((l,c)=>{let p=0,m=u=>{d.once("error",g=>{g.code==="EADDRINUSE"&&p<10?(p++,m(u+1)):c(g)}),d.listen(u,o,()=>{l({url:`http://${o}:${u}/`,port:u,reload:()=>{for(let g of s)g.write(`data: reload
883
+ `),s.add(c),l.on("close",()=>s.delete(c));return}let p=t[m];if(p){c.writeHead(200,{"content-type":p.type}),c.end(p.body);return}if(i)try{let g=await i(m);if(g){c.writeHead(200,{"content-type":g.type}),c.end(g.body);return}}catch(g){c.writeHead(500,{"content-type":"text/plain"}),c.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let u=So.join(a,m);if(!u.startsWith(a)){c.writeHead(403),c.end("Forbidden");return}if(!Rd(u)||!Fd(u).isFile()){c.writeHead(404,{"content-type":"text/plain"}),c.end(`Not found: ${m}`);return}c.writeHead(200,{"content-type":Ld[So.extname(u).toLowerCase()]??"application/octet-stream"}),Td(u).pipe(c)});return new Promise((l,c)=>{let m=0,p=u=>{d.once("error",g=>{g.code==="EADDRINUSE"&&m<10?(m++,p(u+1)):c(g)}),d.listen(u,o,()=>{l({url:`http://${o}:${u}/`,port:u,reload:()=>{for(let g of s)g.write(`data: reload
884
884
 
885
- `)},close:()=>new Promise(g=>{for(let w of s)w.end();d.close(()=>g())})})})};m(n)})}var yd,vd,kd,Sa=v(()=>{"use strict";f();yd={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff":"font/woff",".woff2":"font/woff2",".ico":"image/x-icon"},vd="/__eds_ping",kd="/__eds_events"});var $t={};L($t,{FRAME_PREFIX:()=>ve,galleryPreview:()=>Pd,listPreviewableBlocks:()=>Fe,loadBlockForPreview:()=>pe,previewBlock:()=>jd,startFrameServer:()=>Ke,startPreview:()=>Ta});import{existsSync as oe,watch as ja}from"fs";import{readFile as rn,readdir as xd}from"fs/promises";import Y from"path";import ye from"chalk";function ko(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Pa(e,t){if(e){let o=e.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(o.length)return o.map(i=>({width:i,label:ko(i),figma:!1}))}let n=t?.breakpoints;return Array.isArray(n)&&n.length?n.map(o=>({width:Number(o.width),label:typeof o.label=="string"?o.label:ko(Number(o.width)),figma:o.source==="figma"})).filter(o=>Number.isFinite(o.width)&&o.width>0):Sd.map(o=>({width:o,label:ko(o),figma:!1}))}function Ea(e){if(!e?.figmaFileKey||typeof e.figmaFileKey!="string")return;let t=typeof e.figmaNodeId=="string"?e.figmaNodeId.replace(":","-"):void 0,n=`https://www.figma.com/design/${e.figmaFileKey}/preview`;return t?`${n}?node-id=${t}`:n}function Ca(e){return`<div class="${e} block">
885
+ `)},close:()=>new Promise(g=>{for(let h of s)h.end();d.close(()=>g())})})})};p(n)})}var Ld,Od,Nd,Na=k(()=>{"use strict";f();Ld={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff":"font/woff",".woff2":"font/woff2",".ico":"image/x-icon"},Od="/__eds_ping",Nd="/__eds_events"});var xt={};O(xt,{FRAME_PREFIX:()=>ke,galleryPreview:()=>Bd,listPreviewableBlocks:()=>Le,loadBlockForPreview:()=>ue,previewBlock:()=>Ud,startFrameServer:()=>Ke,startPreview:()=>Ha});import{existsSync as ie,watch as Ma}from"fs";import{readFile as an,readdir as Md}from"fs/promises";import Z from"path";import ve from"chalk";function jo(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Ia(e,t){if(e){let o=e.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(o.length)return o.map(i=>({width:i,label:jo(i),figma:!1}))}let n=t?.breakpoints;return Array.isArray(n)&&n.length?n.map(o=>({width:Number(o.width),label:typeof o.label=="string"?o.label:jo(Number(o.width)),figma:o.source==="figma"})).filter(o=>Number.isFinite(o.width)&&o.width>0):_d.map(o=>({width:o,label:jo(o),figma:!1}))}function _a(e){if(!e?.figmaFileKey||typeof e.figmaFileKey!="string")return;let t=typeof e.figmaNodeId=="string"?e.figmaNodeId.replace(":","-"):void 0,n=`https://www.figma.com/design/${e.figmaFileKey}/preview`;return t?`${n}?node-id=${t}`:n}function Ua(e){return`<div class="${e} block">
886
886
  <div><div>
887
887
  <h2>${e} heading</h2>
888
888
  <p>Sample body copy for the preview. Replace with real authored content.</p>
889
889
  <p><a href="#">Primary action</a></p>
890
890
  <p><a href="#">Secondary action</a></p>
891
891
  </div></div>
892
- </div>`}async function pe(e,t,n){let o=Y.join(e,"blocks",t);if(!oe(Y.join(o,`${t}.css`))&&!oe(Y.join(o,`${t}.js`)))return null;let i=null,a=Y.join(o,".eds-meta.json");if(oe(a))try{i=JSON.parse(await rn(a,"utf-8"))}catch{}let s=Y.join(o,`_${t}.preview.html`),d,l=!1;return oe(s)?d=await rn(s,"utf-8"):(d=Ca(t),l=!0),{name:t,sampleContent:d,breakpoints:Pa(n,i),figmaUrl:Ea(i),placeholder:l}}async function Ke(e,t,n){return on(e,{},n,"127.0.0.1",async i=>{if(!i.startsWith(ve))return;let a=i.slice(ve.length);if(!/^[a-z0-9-]+$/i.test(a))return;let s=await pe(e,a,t);if(s)return{body:nn({blockName:a,breakpoints:s.breakpoints,sampleContent:s.sampleContent,frameRoute:ve+a}),type:"text/html; charset=utf-8"}})}async function Fe(e){let t=Y.join(e,"blocks");if(!oe(t))return[];let n=await xd(t,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory()||$d.has(i.name))continue;let a=Y.join(t,i.name);(oe(Y.join(a,`${i.name}.css`))||oe(Y.join(a,`${i.name}.js`)))&&o.push(i.name)}return o.sort()}async function Aa(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore",shell:process.platform==="win32"})}catch{}}async function Ta(e,t={}){let n=P();if(!n)return r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=Y.join(n,"blocks",e);if(!oe(o))return r.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!oe(Y.join(o,`${e}.css`))&&!oe(Y.join(o,`${e}.js`)))return r.error(`Block "${e}" has no ${e}.css / ${e}.js to preview.`),process.exitCode=1,null;(e==="header"||e==="footer")&&(r.warn(`"${e}" is page chrome, not a content block \u2014 it won't render standalone here.`),r.info(ye.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),r.info(ye.dim(" Preview a content block instead (e.g. a block generated from a design).")));let i=null,a=Y.join(o,".eds-meta.json");if(oe(a))try{i=JSON.parse(await rn(a,"utf-8"))}catch{}let s=Y.join(o,`_${e}.preview.html`),d,l=!1;oe(s)?d=await rn(s,"utf-8"):(d=Ca(e),l=!0);let c=Pa(t.widths,i),p=Ea(i),m="/__eds_preview_frame",u=nn({blockName:e,breakpoints:c,sampleContent:d,frameRoute:m}),g=xa({blockName:e,breakpoints:c,sampleContent:d,figmaUrl:p,frameRoute:m,placeholder:l}),w=Number.parseInt(t.port??"8777",10),y=await on(n,{"/":{body:g,type:"text/html; charset=utf-8"},[m]:{body:u,type:"text/html; charset=utf-8"}},Number.isFinite(w)?w:8777);r.logoOnce(E(`Preview \u2014 ${e}`)),r.info(S("Live preview",y.url)),r.info(A("pass","breakpoints",`${c.map(b=>`${b.width}${b.figma?"\u2713":""}`).join(", ")}, Full`)),l&&r.info(A("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let h,$=ja(o,{recursive:!0},()=>{clearTimeout(h),h=setTimeout(()=>y.reload(),150)});return r.info(""),r.info(` ${ye.bold("\u279C")} ${ye.cyan(y.url)}`),r.info(A("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await Aa(y.url),{url:y.url,close:async()=>{$.close(),await y.close()}}}async function jd(e,t={}){let n=await Ta(e,t);n&&(r.info(ye.dim(` Press Ctrl+C to stop.
893
- `)),await new Promise(o=>{let i=async()=>{await n.close(),o(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}))}async function Pd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async c=>{if(c==="/"){let p=await Fe(t),m=[];for(let u of p){let g=await pe(t,u,e.widths);g&&m.push({blockName:u,breakpoints:g.breakpoints,frameRoute:n+u,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:ka(m),type:"text/html; charset=utf-8"}}if(c.startsWith(n)){let p=c.slice(n.length);if(!/^[a-z0-9-]+$/i.test(p))return;let m=await pe(t,p,e.widths);return m?{body:nn({blockName:p,breakpoints:m.breakpoints,sampleContent:m.sampleContent,frameRoute:n+p}),type:"text/html; charset=utf-8"}:void 0}},i=Number.parseInt(e.port??"8777",10),a=await on(t,{},Number.isFinite(i)?i:8777,"127.0.0.1",o),s=await Fe(t);r.logoOnce(E("Preview \u2014 gallery")),r.info(S("Live gallery",a.url)),r.info(A(s.length?"pass":"warn","blocks",s.length?s.join(", "):"none yet \u2014 generate one with eds block from-design"));let d,l=ja(Y.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(d),d=setTimeout(()=>a.reload(),150)});r.info(""),r.info(` ${ye.bold("\u279C")} ${ye.cyan(a.url)}`),r.info(A("pass","live reload","new & edited blocks refresh the browser")),r.info(ye.dim(` Press Ctrl+C to stop.
894
- `)),e.open!==!1&&await Aa(a.url),await new Promise(c=>{let p=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p)})}var $d,Sd,ve,De=v(()=>{"use strict";f();R();$a();Sa();B();N();$d=new Set(["header","footer"]),Sd=[375,768,1280];ve="/__eds_frame/"});var $o={};L($o,{blockFromDesign:()=>Nd});import{existsSync as ie}from"fs";import{readFile as Xe,writeFile as Ed}from"fs/promises";import W from"path";import{fileURLToPath as Cd}from"url";import C from"chalk";import an from"ora";function Ad(){let e=W.dirname(Cd(import.meta.url));return[W.resolve(e,"../../samples/hero.svg"),W.resolve(e,"../../../samples/hero.svg")].find(n=>ie(n))??null}async function Td(e=8777){try{let t=new AbortController,n=setTimeout(()=>t.abort(),400),o=await fetch(`http://127.0.0.1:${e}/__eds_ping`,{signal:t.signal});return clearTimeout(n),o.ok?(await o.json())?.eds===!0:!1}catch{return!1}}async function Rd(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(G(),H)),i=await n({message:"1/7 Design source",choices:[{name:"Figma (REST / MCP / local)",value:"figma"},{name:"Framer (scraped, headless Chromium)",value:"framer"},{name:"Google Stitch (scraped, headless Chromium)",value:"stitch"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:b=>Se.test(b.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${qe[i]} link`,validate:b=>{if(!b.trim())return"Paste the design link";if(i!=="figma")return/^https?:\/\//i.test(b.trim())||"Paste a public http(s) URL to the page";try{return tn(b.trim()),!0}catch(T){return T.message}}}),d=await n({message:"4/7 Where does the content come from?",choices:[{name:"Document authoring (default EDS)",value:"document"},{name:"Universal Editor",value:"ue"},{name:"Content Fragment",value:"cf"},{name:"Mixed - Universal Editor + Content Fragment",value:"mixed"}],default:"document"}),l;(d==="cf"||d==="mixed")&&(l=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let c=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),p=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),m=await en(),u=await n({message:"7/7 Run with",choices:[...m.map(b=>({name:`${b.type}${i==="figma"&&!b.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${b.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:m[0]?`agent:${m[0].type}`:"dry-run"}),g=qe[i].toLowerCase();r.info(S("Summary"));let w=M(["component",g,"content","ue model","screenshot","run"]);r.info(j("component",a,w));let y=i==="figma"?(()=>{let b=tn(s.trim());return b.nodeId?`node ${b.nodeId}`:b.fileKey})():s.trim();if(r.info(j(g,y,w)),r.info(j("content",d+(l?` (${l})`:""),w)),r.info(j("ue model",c?"yes":"no",w)),r.info(j("screenshot",p?"yes":"no (token-lean)",w)),r.info(j("run",u.replace("agent:",""),w)),r.info(""),!await o({message:"Generate this block?",default:!0}))return null;let $={figmaUrl:s.trim(),name:a,provider:i,source:d,cfHint:l,ueModel:c,screenshot:p};return u==="dry-run"?$.dryRun=!0:u==="none"?$.agent="none":($.agent=u.replace("agent:",""),$.yes=!0),$}function xo(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function Fd(e){try{let t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname.split(".")[0]}catch{return""}}function Dd(e){if(e)try{let t=new URL(e).hostname.toLowerCase();if(t.includes("figma.com"))return"figma";if(t.includes("framer"))return"framer";if(t.includes("stitch"))return"stitch"}catch{}}function Od(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=W.isAbsolute(e)?e:W.resolve(process.cwd(),e);return!ie(t)||!Ld.has(W.extname(t).toLowerCase())?null:t}async function Nd(e,t){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await r.logoOnceAnimated("Design \u2192 EDS block");let o=e,i=t;if(!o&&i.sample){let J=Ad();if(!J){r.error("Bundled sample design not found (samples/hero.svg)."),process.exitCode=1;return}o=J,i={name:"hero",provider:"figma",...i},r.info(` ${q.pass} Sample design ${C.dim("Kiri Bloom hero")} ${C.dim("(bundled \xB7 no token \xB7 no MCP)")}`)}if(!o){let J=await Rd(o);if(!J){r.info("Cancelled.");return}o=J.figmaUrl,i={...i,...J}}let a=i.provider;if(a&&!(a in qe)){r.error(`Unknown --provider "${a}". Use: figma, framer or stitch.`),process.exitCode=1;return}let s=a??Dd(o)??"figma",d=qe[s],l=Od(o),c=l?l.startsWith(n+W.sep)?W.relative(n,l):l:void 0,p=null,m=c??o;if(l)r.info(` ${q.pass} Local design file ${C.dim(c)} ${C.dim("(no Figma MCP)")}`);else if(s==="figma"){let J=an("Parsing Figma URL...").start();try{p=tn(o),J.succeed(`Parsed Figma URL ${C.dim(p.nodeId?`node ${p.nodeId}`:`file ${p.fileKey}`)}`)}catch(Ne){J.fail(Ne.message),process.exitCode=1;return}}else r.info(` ${q.pass} ${d} design ${C.dim(m)}`);let u=i.name||(l?xo(W.basename(l,W.extname(l))):p?xo(p.fileName):o?xo(Fd(o)):"");if(!Se.test(u)){r.error(`Invalid block name "${u}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!i.name&&p?.nodeId&&(r.warn(`Block name "${u}" came from the Figma file name, not the selected frame.`),r.info(C.dim(` Pass ${C.cyan("--name <kebab-case>")} for a cleaner block name.`)));let g=await se(n),w=g.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,y=an("Resolving design source...").start(),h=await ga({figma:p,localFile:c,token:w,projectRoot:n,preferMcp:i.mcp,refresh:i.refresh,provider:s,designUrl:l?void 0:o,dryRun:i.dryRun});if(h.scrapeError){y.fail(`Scrape failed: ${h.scrapeError}`),r.info(C.dim(` Check the URL is a public ${d} page, and that Chromium is installed (${C.cyan("npx playwright install chromium")}).`)),process.exitCode=1;return}y.succeed(`Design source ${C.dim(h.summary)}`),h.restError&&r.warn(`Figma REST fetch failed, using MCP fallback: ${h.restError}`);let $=an("Reading design tokens & building prompt...").start(),b=await ba({provider:s,figma:p,designRef:m,blockName:u,projectRoot:n,withUeModel:i.ueModel!==!1,contentSource:i.source??"document",cfHint:i.cfHint,screenshot:i.screenshot===!0,design:h.design}),T=await po(b,n),Q=ie(W.join(n,"styles","styles.css"));if($.succeed(Q?`Loaded design tokens ${C.dim("styles/styles.css")}`:`Built prompt ${C.dim("no project tokens found")}`),r.info(C.dim(` prompt \u2192 ${T}`)),i.dryRun){r.info(""),r.info(C.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),r.info(`Prompt file: ${C.cyan(T)}`),r.info(`Block name: ${C.cyan(u)}`),r.info(`Prompt version: ${xt}`),r.info(""),r.info("Preview:"),r.info(C.dim("\u2500".repeat(60))),console.log(b);return}let z=i.agent||g.agent;if(i.agent==="none"){r.info("Agent skipped (--agent none). Use the prompt file manually:"),r.info(` ${C.cyan(T)}`);return}let ue=an("Detecting AI agent...").start(),te=await Yr(z);if(!te){ue.fail("No AI agent found (claude, cursor, or codex)."),r.info(`Install Claude Code: ${C.cyan("npm install -g @anthropic-ai/claude-code")}`),r.info(`Or use the prompt file manually: ${C.cyan(T)}`),process.exitCode=1;return}if(ue.succeed(`Agent ready ${C.cyan(te.type)} ${C.dim(te.path)}`),(h.design?.mode==="mcp"||!h.design&&s==="figma")&&s==="figma"&&!te.hasFigmaMcp&&(r.warn(`Figma MCP may not be configured for ${te.type}.`),r.info(`Run ${C.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!i.yes){let{confirm:J}=await Promise.resolve().then(()=>(G(),H));if(!await J({message:`Run ${te.type} with the generated prompt?`,default:!0})){r.info(`Prompt saved to: ${C.cyan(T)}`);return}}let ms=h.design?.mode==="spec"?"embedded design (no MCP)":h.design?.mode==="scrape"?`scraped ${d} page (no MCP)`:h.design?.mode==="file"?`reading ${c}`:h.design?.mode==="mcp"?`via ${d} MCP (1 call, cached)`:`via ${d} MCP`;if(r.info(` ${C.dim("\u2192")} Handing off to ${C.cyan(te.type)} ${C.dim(ms)}`),h.design?.mode==="mcp"&&r.info(C.dim(" get_design_context \xD71 \u2192 cache")),!await mo(te,T,n,g.model)){process.exitCode=1;return}let nt=W.join(n,"blocks",u);if(!(ie(W.join(nt,`${u}.js`))||ie(W.join(nt,`${u}.css`)))){r.warn(`No block files were written to blocks/${u}/ \u2014 nothing to preview.`),h.design?.mode==="mcp"?(r.info(C.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),r.info(C.dim(` ${d} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),r.info(C.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command."))):r.info(C.dim(" The agent generated nothing \u2014 see the log above for why.")),process.exitCode=1;return}let us=await Id(nt,u,i.ueModel!==!1);if(ie(nt)){let J=W.join(nt,".eds-meta.json"),Ne;if(ie(J))try{Ne=JSON.parse(await Xe(J,"utf-8")).breakpoints}catch{}let Me=oa(i.widths,Ne),fs={provider:s,designRef:m,figmaFileKey:p?.fileKey??null,figmaNodeId:p?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:xt,agentUsed:te.type,...Me.length?{breakpoints:Me}:{}};await Ed(J,`${JSON.stringify(fs,null,2)}
895
- `),Me.length&&r.info(C.dim(` Preview breakpoints: ${Me.map(gs=>gs.width).join(" \xB7 ")}`))}if(!us){r.warn(`Block "${u}" generated with issues \u2014 review the output above before publishing.`),process.exitCode=1;return}if(r.success(`Block "${u}" generation complete.`),!i.yes){let{confirm:J}=await Promise.resolve().then(()=>(G(),H));if(await J({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:Me}=await Promise.resolve().then(()=>(ft(),ut));await Me(u,{})}}if(!i.yes)await Md({blockName:u,projectRoot:n,agent:te,model:g.model,provider:s,figma:p,designRef:m});else if(i.serve){let{previewBlock:J}=await Promise.resolve().then(()=>(De(),$t));await J(u,{})}else r.info(` ${C.dim("\u2192")} Next: ${C.cyan(`eds block preview ${u}`)}`)}async function Md(e){let{select:t,input:n}=await Promise.resolve().then(()=>(G(),H)),{startPreview:o}=await Promise.resolve().then(()=>(De(),$t)),i=null;for(r.info("");;){let a=await t({message:"Block ready \u2014 what next?",choices:[{name:"Refine \u2014 describe a change",value:"refine"},{name:i?`Preview open at ${i.url} (reloads on change)`:"Open live preview",value:"preview",disabled:i?"running":!1},{name:"Finish",value:"done"}],default:"refine"});if(a==="done")break;if(a==="preview"){await Td()?r.info(C.dim(" A preview server is already running at http://127.0.0.1:8777.")):i=await o(e.blockName,{});continue}let s=(await n({message:"Describe the change:"})).trim();if(!s)continue;let d=ya({blockName:e.blockName,feedback:s,provider:e.provider,figma:e.figma,designRef:e.designRef}),l=await po(d,e.projectRoot);r.info(` ${C.dim("\u2192")} Applying your change with ${C.cyan(e.agent.type)}\u2026`),await mo(e.agent,l,e.projectRoot,e.model)}i&&(r.info(C.dim(` Preview still live at ${i.url} \u2014 press Ctrl+C to stop.
896
- `)),await new Promise(a=>{let s=async()=>{i&&await i.close(),a(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}))}async function Id(e,t,n){let o=[],i=W.join(e,`${t}.js`),a=W.join(e,`${t}.css`),s=ie(i),d=ie(a);if(o.push({status:s?"pass":"fail",name:`${t}.js`,message:s?"created":"missing \u2014 agent did not write the JS file"}),o.push({status:d?"pass":"fail",name:`${t}.css`,message:d?"created":"missing \u2014 agent did not write the CSS file"}),s){let c=await Xe(i,"utf-8");o.push({status:/export\s+default/.test(c)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(c)?"found":"no default export \u2014 block won't load"}),c.includes("console.log")&&o.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(d){let c=await Xe(a,"utf-8");o.push({status:c.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:c.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let c=ie(W.join(e,`_${t}.json`)),p=W.join(e,"..","..","component-models.json"),m=!1;if(!c&&ie(p))try{m=(await Xe(p,"utf-8")).includes(`"${t}"`)}catch{}let u=c||m;if(o.push({status:u?"pass":"warn",name:"Universal Editor model",message:u?c?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),c&&s)try{let g=await Xe(W.join(e,`_${t}.json`),"utf-8"),w=await Xe(i,"utf-8"),y=/"resourceType"\s*:\s*"[^"]*\/item"/.test(g)||/"filter"\s*:/.test(g)||/"multi"\s*:\s*true/.test(g),h=/\.children/.test(w)||/\bfor\s*\(/.test(w)||/\.forEach\s*\(/.test(w);y&&o.push({status:h?"pass":"warn",name:"multifield wired",message:h?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}r.info(S("Verification"));let l=M(o.map(c=>c.name));for(let c of o)r.info(A(c.status,c.name,c.message,l));return r.info(""),!o.some(c=>c.status==="fail")}var Ld,So=v(()=>{"use strict";f();lo();Qr();be();ia();ha();wa();va();R();B();Be();N();Ld=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var Ra={};L(Ra,{listBlocks:()=>Bd});import{existsSync as St}from"fs";import{readFile as _d,readdir as Ud}from"fs/promises";import Ve from"path";import Ye from"chalk";async function Bd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ve.join(t,"blocks");if(!St(n)){r.info("No blocks/ directory found.");return}let o=await Ud(n,{withFileTypes:!0}),i=[];for(let s of o){if(!s.isDirectory())continue;let d=s.name,l=Ve.join(n,d),c={name:d,hasJs:St(Ve.join(l,`${d}.js`)),hasCss:St(Ve.join(l,`${d}.css`)),hasUeModel:St(Ve.join(l,`_${d}.json`))},p=Ve.join(l,".eds-meta.json");if(St(p))try{let m=JSON.parse(await _d(p,"utf-8"));c.figmaSource={fileKey:m.figmaFileKey,nodeId:m.figmaNodeId,lastSyncedAt:m.lastSyncedAt}}catch{}i.push(c)}if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){r.info("No blocks found.");return}r.info(S("Blocks",`${i.length} in project`));let a=M(i.map(s=>s.name));for(let s of i){let d=[s.hasJs?_.ok("js"):Ye.dim.strikethrough("js"),s.hasCss?_.ok("css"):Ye.dim.strikethrough("css")];s.hasUeModel&&d.push(_.blue("ue-model")),s.figmaSource&&d.push(`${q.figma} ${_.dotPurple("figma")}`);let l=ot(Ye.bold(s.name),a);if(r.info(` ${l} ${Ye.dim("[")}${d.join(" ")}${Ye.dim("]")}`),s.figmaSource){let c=new Date(s.figmaSource.lastSyncedAt).toLocaleDateString();r.info(` ${" ".repeat(a)} ${q.arrow} ${Ye.dim(`figma:${s.figmaSource.fileKey} \xB7 synced ${c}`)}`)}}r.info("")}var Fa=v(()=>{"use strict";f();R();B();N()});import Da from"path";function jo(e,t){return Da.join(e,"blocks",t,"__snapshots__")}function Oa(e,t,n){return Da.join(jo(e,t),`${t}-${n}.png`)}function jt(e){return`${(e*100).toFixed(2)}%`}async function Po(e,t,n=900){let o;try{({chromium:o}=await import("playwright"))}catch{throw new Error(La)}let i=await o.launch();try{let a=await i.newPage({viewport:{width:t,height:n}});return await a.goto(e,{waitUntil:"networkidle"}),await a.waitForTimeout(300),await a.screenshot({fullPage:!0})}finally{await i.close()}}async function Na(){try{let e="pngjs",t="pixelmatch",{PNG:n}=await import(e),o=(await import(t)).default;return{PNG:n,pixelmatch:o}}catch{throw new Error(La)}}async function Ma(e,t){let{PNG:n,pixelmatch:o}=await Na(),i=n.sync.read(e),a=n.sync.read(t);if(i.width!==a.width||i.height!==a.height)return{diffPixels:-1,totalPixels:0,ratio:1,sizeMismatch:!0,width:i.width,height:i.height};let{width:s,height:d}=i,l=new n({width:s,height:d}),c=o(i.data,a.data,l.data,s,d,{threshold:.1}),p=s*d;return{diffPixels:c,totalPixels:p,ratio:p?c/p:0,width:s,height:d,diffPng:n.sync.write(l)}}async function Ia(e,t){let{PNG:n,pixelmatch:o}=await Na(),i=n.sync.read(e),a=n.sync.read(t),s=Math.min(i.width,a.width),d=Math.min(i.height,a.height),l=new n({width:s,height:d}),c=new n({width:s,height:d});i.bitblt(l,0,0,s,d,0,0),a.bitblt(c,0,0,s,d,0,0);let p=new n({width:s,height:d}),m=o(l.data,c.data,p.data,s,d,{threshold:.1}),u=s*d;return{diffPixels:m,totalPixels:u,ratio:u?m/u:0,width:s,height:d,diffPng:n.sync.write(p)}}var La,_a=v(()=>{"use strict";f();La=`Visual testing needs extra tools. Install them with:
897
- npm i -D playwright pixelmatch pngjs && npx playwright install chromium`});var Ga={};L(Ga,{visualTest:()=>Hd});import{existsSync as Ua}from"fs";import{mkdir as Eo,readFile as Ba,writeFile as Pt}from"fs/promises";import me from"path";import Co from"chalk";async function Hd(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}if(t.design){await Gd(n,e,t);return}let o=e?[e]:await Fe(n);if(!o.length){r.warn("No previewable blocks to test.");return}let i=Number.parseInt(t.port??"8788",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8788),s=Number.parseFloat(t.threshold??"0.01"),d=me.join(n,"tmp","eds-cli","visual-diff");r.logoOnce(E("Visual test"));let l=0,c=0,p=0,m=0;try{for(let u of o){let g=await pe(n,u,t.widths);if(g){r.info(S(u));for(let w of g.breakpoints){let y=await Po(Ha(a.url,u),w.width),h=Oa(n,u,w.width),$=Ua(h);if(t.update||!$){await Eo(jo(n,u),{recursive:!0}),await Pt(h,y),$?(m++,r.info(A("pass",`${w.width}px`,"baseline updated"))):(p++,r.info(A("pass",`${w.width}px`,"baseline created")));continue}let b=await Ma(await Ba(h),y);if(b.sizeMismatch){c++,r.info(A("fail",`${w.width}px`,`size changed \u2192 ${b.width}\xD7${b.height}`));continue}if(b.ratio>s){c++,await Eo(d,{recursive:!0});let T=me.join(d,`${u}-${w.width}.diff.png`);b.diffPng&&await Pt(T,b.diffPng),r.info(A("fail",`${w.width}px`,`${jt(b.ratio)} changed \u2192 ${me.relative(n,T)}`))}else l++,r.info(A("pass",`${w.width}px`,b.ratio>0?`${jt(b.ratio)} (within ${jt(s)})`:"identical"))}}}}catch(u){r.error(u instanceof Error?u.message:String(u)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Co.green(`${l} passed`)} \xB7 ${Co.yellow(`${c} changed`)} \xB7 ${p} new \xB7 ${m} updated`),c>0&&(r.warn(`${c} visual change(s). Review the diff PNGs in tmp/eds-cli/visual-diff/, then re-run with --update to accept.`),process.exitCode=1)}async function Gd(e,t,n){if(!t){r.error("Design diff needs a block name: eds block test <name> --design"),process.exitCode=1;return}let o=await pe(e,t,n.widths);if(!o){r.error(`Block "${t}" has no css/js to render.`),process.exitCode=1;return}let i,a,s=me.join(e,"blocks",t,".eds-meta.json");if(Ua(s))try{let g=JSON.parse(await Ba(s,"utf-8"));i=g.figmaFileKey??void 0,a=g.figmaNodeId??void 0}catch{}if(!i||!a){r.error(`"${t}" has no Figma source in .eds-meta.json \u2014 can't fetch the design image.`),process.exitCode=1;return}let l=(await se(e)).figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT;if(!l){r.error("Design diff needs a Figma token (FIGMA_TOKEN or figma.token) to render the node."),process.exitCode=1;return}let c=o.breakpoints.filter(g=>g.figma),p=(c.length?c:o.breakpoints).reduce((g,w)=>w.width>g.width?w:g,o.breakpoints[0]).width,m=Number.parseInt(n.port??"8788",10),u=await Ke(e,n.widths,Number.isFinite(m)?m:8788);r.logoOnce(E("Design \u2194 render")),r.info(S(t,`${p}px`));try{let g=await Po(Ha(u.url,t),p);r.info(A("pass","render","block screenshot captured"));let w=await da({fileKey:i,nodeId:a,token:l,scale:1});r.info(A("pass","design","Figma image fetched (REST)"));let y=await Ia(w,g),h=me.join(e,"tmp","eds-cli","visual-diff");await Eo(h,{recursive:!0}),await Pt(me.join(h,`${t}-design.png`),w),await Pt(me.join(h,`${t}-render.png`),g),y.diffPng&&await Pt(me.join(h,`${t}-design-diff.png`),y.diffPng),r.info(A("warn","diff",`~${jt(y.ratio)} different over ${y.width}\xD7${y.height} (approximate)`)),r.info(""),r.info(Co.dim(` Saved design / render / diff to ${me.relative(e,h)}/${t}-*.png \u2014 compare side by side.`))}catch(g){r.error(g instanceof Error?g.message:String(g)),process.exitCode=1}finally{await u.close()}}var Ha,za=v(()=>{"use strict";f();be();yo();R();_a();B();N();De();Ha=(e,t)=>`${e}${ve.slice(1)}${t}`});async function Wa(e,t){let n;try{({chromium:n}=await import("playwright"))}catch{throw new Error(zd)}let o=await n.launch();try{let i=await o.newPage({viewport:{width:t,height:900}});return await i.goto(e,{waitUntil:"networkidle"}),await i.waitForTimeout(200),await i.evaluate(Wd)}finally{await o.close()}}var zd,Wd,Ja=v(()=>{"use strict";f();zd=`Content checks need Playwright. Install it with:
898
- npm i -D playwright && npx playwright install chromium`,Wd=`(() => {
892
+ </div>`}async function ue(e,t,n){let o=Z.join(e,"blocks",t);if(!ie(Z.join(o,`${t}.css`))&&!ie(Z.join(o,`${t}.js`)))return null;let i=null,a=Z.join(o,".eds-meta.json");if(ie(a))try{i=JSON.parse(await an(a,"utf-8"))}catch{}let s=Z.join(o,`_${t}.preview.html`),d,l=!1;return ie(s)?d=await an(s,"utf-8"):(d=Ua(t),l=!0),{name:t,sampleContent:d,breakpoints:Ia(n,i),figmaUrl:_a(i),placeholder:l}}async function Ke(e,t,n){return rn(e,{},n,"127.0.0.1",async i=>{if(!i.startsWith(ke))return;let a=i.slice(ke.length);if(!/^[a-z0-9-]+$/i.test(a))return;let s=await ue(e,a,t);if(s)return{body:on({blockName:a,breakpoints:s.breakpoints,sampleContent:s.sampleContent,frameRoute:ke+a}),type:"text/html; charset=utf-8"}})}async function Le(e){let t=Z.join(e,"blocks");if(!ie(t))return[];let n=await Md(t,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory()||Id.has(i.name))continue;let a=Z.join(t,i.name);(ie(Z.join(a,`${i.name}.css`))||ie(Z.join(a,`${i.name}.js`)))&&o.push(i.name)}return o.sort()}async function Ba(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore",shell:process.platform==="win32"})}catch{}}async function Ha(e,t={}){let n=P();if(!n)return r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=Z.join(n,"blocks",e);if(!ie(o))return r.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!ie(Z.join(o,`${e}.css`))&&!ie(Z.join(o,`${e}.js`)))return r.error(`Block "${e}" has no ${e}.css / ${e}.js to preview.`),process.exitCode=1,null;(e==="header"||e==="footer")&&(r.warn(`"${e}" is page chrome, not a content block \u2014 it won't render standalone here.`),r.info(ve.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),r.info(ve.dim(" Preview a content block instead (e.g. a block generated from a design).")));let i=null,a=Z.join(o,".eds-meta.json");if(ie(a))try{i=JSON.parse(await an(a,"utf-8"))}catch{}let s=Z.join(o,`_${e}.preview.html`),d,l=!1;ie(s)?d=await an(s,"utf-8"):(d=Ua(e),l=!0);let c=Ia(t.widths,i),m=_a(i),p="/__eds_preview_frame",u=on({blockName:e,breakpoints:c,sampleContent:d,frameRoute:p}),g=La({blockName:e,breakpoints:c,sampleContent:d,figmaUrl:m,frameRoute:p,placeholder:l}),h=Number.parseInt(t.port??"8777",10),b=await rn(n,{"/":{body:g,type:"text/html; charset=utf-8"},[p]:{body:u,type:"text/html; charset=utf-8"}},Number.isFinite(h)?h:8777);r.logoOnce(C(`Preview \u2014 ${e}`)),r.info(S("Live preview",b.url)),r.info(A("pass","breakpoints",`${c.map(v=>`${v.width}${v.figma?"\u2713":""}`).join(", ")}, Full`)),l&&r.info(A("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let w,y=Ma(o,{recursive:!0},()=>{clearTimeout(w),w=setTimeout(()=>b.reload(),150)});return r.info(""),r.info(` ${ve.bold("\u279C")} ${ve.cyan(b.url)}`),r.info(A("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await Ba(b.url),{url:b.url,close:async()=>{y.close(),await b.close()}}}async function Ud(e,t={}){let n=await Ha(e,t);n&&(r.info(ve.dim(` Press Ctrl+C to stop.
893
+ `)),await new Promise(o=>{let i=async()=>{await n.close(),o(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}))}async function Bd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async c=>{if(c==="/"){let m=await Le(t),p=[];for(let u of m){let g=await ue(t,u,e.widths);g&&p.push({blockName:u,breakpoints:g.breakpoints,frameRoute:n+u,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:Da(p),type:"text/html; charset=utf-8"}}if(c.startsWith(n)){let m=c.slice(n.length);if(!/^[a-z0-9-]+$/i.test(m))return;let p=await ue(t,m,e.widths);return p?{body:on({blockName:m,breakpoints:p.breakpoints,sampleContent:p.sampleContent,frameRoute:n+m}),type:"text/html; charset=utf-8"}:void 0}},i=Number.parseInt(e.port??"8777",10),a=await rn(t,{},Number.isFinite(i)?i:8777,"127.0.0.1",o),s=await Le(t);r.logoOnce(C("Preview \u2014 gallery")),r.info(S("Live gallery",a.url)),r.info(A(s.length?"pass":"warn","blocks",s.length?s.join(", "):"none yet \u2014 generate one with eds block from-design"));let d,l=Ma(Z.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(d),d=setTimeout(()=>a.reload(),150)});r.info(""),r.info(` ${ve.bold("\u279C")} ${ve.cyan(a.url)}`),r.info(A("pass","live reload","new & edited blocks refresh the browser")),r.info(ve.dim(` Press Ctrl+C to stop.
894
+ `)),e.open!==!1&&await Ba(a.url),await new Promise(c=>{let m=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",m),process.on("SIGTERM",m)})}var Id,_d,ke,Oe=k(()=>{"use strict";f();R();Oa();Na();z();M();Id=new Set(["header","footer"]),_d=[375,768,1280];ke="/__eds_frame/"});var Eo={};O(Eo,{blockFromDesign:()=>Yd});import{existsSync as ae}from"fs";import{readFile as Xe,writeFile as Hd}from"fs/promises";import q from"path";import{fileURLToPath as Gd}from"url";import E from"chalk";import sn from"ora";function zd(){let e=q.dirname(Gd(import.meta.url));return[q.resolve(e,"../../samples/hero.svg"),q.resolve(e,"../../../samples/hero.svg")].find(n=>ae(n))??null}async function Wd(e=8777){try{let t=new AbortController,n=setTimeout(()=>t.abort(),400),o=await fetch(`http://127.0.0.1:${e}/__eds_ping`,{signal:t.signal});return clearTimeout(n),o.ok?(await o.json())?.eds===!0:!1}catch{return!1}}async function Jd(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(G(),H)),i=await n({message:"1/7 Design source",choices:[{name:"Figma (REST / MCP / local)",value:"figma"},{name:"Framer (scraped, headless Chromium)",value:"framer"},{name:"Google Stitch (scraped, headless Chromium)",value:"stitch"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:v=>Pe.test(v.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${qe[i]} link`,validate:v=>{if(!v.trim())return"Paste the design link";if(i!=="figma")return/^https?:\/\//i.test(v.trim())||"Paste a public http(s) URL to the page";try{return nn(v.trim()),!0}catch(T){return T.message}}}),d=await n({message:"4/7 Where does the content come from?",choices:[{name:"Document authoring (default EDS)",value:"document"},{name:"Universal Editor",value:"ue"},{name:"Content Fragment",value:"cf"},{name:"Mixed - Universal Editor + Content Fragment",value:"mixed"}],default:"document"}),l;(d==="cf"||d==="mixed")&&(l=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let c=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),m=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),p=await tn(),u=await n({message:"7/7 Run with",choices:[...p.map(v=>({name:`${v.type}${i==="figma"&&!v.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${v.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:p[0]?`agent:${p[0].type}`:"dry-run"}),g=qe[i].toLowerCase();r.info(S("Summary"));let h=I(["component",g,"content","ue model","screenshot","run"]);r.info(j("component",a,h));let b=i==="figma"?(()=>{let v=nn(s.trim());return v.nodeId?`node ${v.nodeId}`:v.fileKey})():s.trim();if(r.info(j(g,b,h)),r.info(j("content",d+(l?` (${l})`:""),h)),r.info(j("ue model",c?"yes":"no",h)),r.info(j("screenshot",m?"yes":"no (token-lean)",h)),r.info(j("run",u.replace("agent:",""),h)),r.info(""),!await o({message:"Generate this block?",default:!0}))return null;let y={figmaUrl:s.trim(),name:a,provider:i,source:d,cfHint:l,ueModel:c,screenshot:m};return u==="dry-run"?y.dryRun=!0:u==="none"?y.agent="none":(y.agent=u.replace("agent:",""),y.yes=!0),y}function Po(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function qd(e){try{let t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname.split(".")[0]}catch{return""}}function Kd(e){if(e)try{let t=new URL(e).hostname.toLowerCase();if(t.includes("figma.com"))return"figma";if(t.includes("framer"))return"framer";if(t.includes("stitch"))return"stitch"}catch{}}function Vd(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=q.isAbsolute(e)?e:q.resolve(process.cwd(),e);return!ae(t)||!Xd.has(q.extname(t).toLowerCase())?null:t}async function Yd(e,t){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await r.logoOnceAnimated("Design \u2192 EDS block");let o=e,i=t;if(!o&&i.sample){let D=zd();if(!D){r.error("Bundled sample design not found (samples/hero.svg)."),process.exitCode=1;return}o=D,i={name:"hero",provider:"figma",...i},r.info(` ${W.pass} Sample design ${E.dim("Kiri Bloom hero")} ${E.dim("(bundled \xB7 no token \xB7 no MCP)")}`)}if(!o){let D=await Jd(o);if(!D){r.info("Cancelled.");return}o=D.figmaUrl,i={...i,...D}}let a=i.provider;if(a&&!(a in qe)){r.error(`Unknown --provider "${a}". Use: figma, framer or stitch.`),process.exitCode=1;return}let s=a??Kd(o)??"figma",d=qe[s],l=Vd(o),c=l?l.startsWith(n+q.sep)?q.relative(n,l):l:void 0,m=null,p=c??o;if(l)r.info(` ${W.pass} Local design file ${E.dim(c)} ${E.dim("(no Figma MCP)")}`);else if(s==="figma"){let D=sn("Parsing Figma URL...").start();try{m=nn(o),D.succeed(`Parsed Figma URL ${E.dim(m.nodeId?`node ${m.nodeId}`:`file ${m.fileKey}`)}`)}catch(re){D.fail(re.message),process.exitCode=1;return}}else r.info(` ${W.pass} ${d} design ${E.dim(p)}`);let u=i.name||(l?Po(q.basename(l,q.extname(l))):m?Po(m.fileName):o?Po(qd(o)):"");if(!Pe.test(u)){r.error(`Invalid block name "${u}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!i.name&&m?.nodeId&&(r.warn(`Block name "${u}" came from the Figma file name, not the selected frame.`),r.info(E.dim(` Pass ${E.cyan("--name <kebab-case>")} for a cleaner block name.`)));let g=await le(n),h=g.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,b;if(xo(s)&&!l&&!i.dryRun&&(i.auth||i.authRefresh))if(b=$o(s),i.authRefresh||!Aa(s)){let D=(()=>{try{return new URL(o).origin}catch{return o}})();r.info(` ${E.dim("\u2192")} Opening ${E.cyan(d)} \u2014 click ${E.cyan("Sign In")} and log in, then come back here.`);let{input:re}=await Promise.resolve().then(()=>(G(),H));try{await Ta(b),await ua({loginUrl:D,statePath:b,projectRoot:n,waitForUser:async()=>{await re({message:"Press Enter once you're signed in (you don't need to open the design)"})}}),await Ra(b),r.info(` ${W.pass} Session saved ${E.dim(b)}`)}catch(ne){r.error(`Could not capture the ${d} session: ${ne instanceof Error?ne.message:String(ne)}`),process.exitCode=1;return}}else r.info(` ${W.pass} Using saved ${d} session ${E.dim(b)} ${E.dim("(--auth-refresh to re-login)")}`);let w=sn("Resolving design source...").start(),y=await xa({figma:m,localFile:c,token:h,projectRoot:n,preferMcp:i.mcp,refresh:i.refresh,provider:s,designUrl:l?void 0:o,storageStatePath:b,dryRun:i.dryRun});if(y.scrapeError){w.fail(`Scrape failed: ${y.scrapeError}`),r.info(E.dim(` Check the URL is a public ${d} page, and that Chromium is installed (${E.cyan("npx playwright install chromium")}).`)),process.exitCode=1;return}if(w.succeed(`Design source ${E.dim(y.summary)}`),y.restError&&r.warn(`Figma REST fetch failed, using MCP fallback: ${y.restError}`),y.design?.mode==="scrape"&&!i.dryRun)try{let D=JSON.parse(y.design.spec),re=(D.title??"").toLowerCase(),ne=y.design.spec.toLowerCase(),Tt=/isn'?t shared|doesn'?t exist|page not found|\b404\b/;(Tt.test(re)||Tt.test(ne)||/\bsign[ -]?in\b|\blog[ -]?in\b/.test(re)||(D.nodeCount??0)<8)&&(r.warn(`The scraped page looks like a login / error shell${D.title?` ("${D.title}")`:""} \u2014 the design may be gated or the URL wrong.`),r.info(E.dim(` Use ${E.cyan("--auth")} to log in once (or ${E.cyan("--auth-refresh")} to re-login), and confirm the URL opens the design when you're signed in.`)))}catch{}let v=sn("Reading design tokens & building prompt...").start(),T=await ja({provider:s,figma:m,designRef:p,blockName:u,projectRoot:n,withUeModel:i.ueModel!==!1,contentSource:i.source??"document",cfHint:i.cfHint,screenshot:i.screenshot===!0,design:y.design}),K=await po(T,n),J=ae(q.join(n,"styles","styles.css"));if(v.succeed(J?`Loaded design tokens ${E.dim("styles/styles.css")}`:`Built prompt ${E.dim("no project tokens found")}`),r.info(E.dim(` prompt \u2192 ${K}`)),i.dryRun){r.info(""),r.info(E.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),r.info(`Prompt file: ${E.cyan(K)}`),r.info(`Block name: ${E.cyan(u)}`),r.info(`Prompt version: ${kt}`),r.info(""),r.info("Preview:"),r.info(E.dim("\u2500".repeat(60))),console.log(T);return}let Se=i.agent||g.agent;if(i.agent==="none"){r.info("Agent skipped (--agent none). Use the prompt file manually:"),r.info(` ${E.cyan(K)}`);return}let At=sn("Detecting AI agent...").start(),Y=await na(Se);if(!Y){At.fail("No AI agent found (claude, cursor, or codex)."),r.info(`Install Claude Code: ${E.cyan("npm install -g @anthropic-ai/claude-code")}`),r.info(`Or use the prompt file manually: ${E.cyan(K)}`),process.exitCode=1;return}if(At.succeed(`Agent ready ${E.cyan(Y.type)} ${E.dim(Y.path)}`),(y.design?.mode==="mcp"||!y.design&&s==="figma")&&s==="figma"&&!Y.hasFigmaMcp&&(r.warn(`Figma MCP may not be configured for ${Y.type}.`),r.info(`Run ${E.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!i.yes){let{confirm:D}=await Promise.resolve().then(()=>(G(),H));if(!await D({message:`Run ${Y.type} with the generated prompt?`,default:!0})){r.info(`Prompt saved to: ${E.cyan(K)}`);return}}let Ss=y.design?.mode==="spec"?"embedded design (no MCP)":y.design?.mode==="scrape"?`scraped ${d} page (no MCP)`:y.design?.mode==="file"?`reading ${c}`:y.design?.mode==="mcp"?`via ${d} MCP (1 call, cached)`:`via ${d} MCP`;if(r.info(` ${E.dim("\u2192")} Handing off to ${E.cyan(Y.type)} ${E.dim(Ss)}`),y.design?.mode==="mcp"&&r.info(E.dim(" get_design_context \xD71 \u2192 cache")),!await uo(Y,K,n,g.model)){process.exitCode=1;return}let tt=q.join(n,"blocks",u);if(!(ae(q.join(tt,`${u}.js`))||ae(q.join(tt,`${u}.css`)))){r.warn(`No block files were written to blocks/${u}/ \u2014 nothing to preview.`),y.design?.mode==="mcp"?(r.info(E.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),r.info(E.dim(` ${d} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),r.info(E.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command."))):r.info(E.dim(" The agent generated nothing \u2014 see the log above for why.")),process.exitCode=1;return}let js=await Zd(tt,u,i.ueModel!==!1);if(ae(tt)){let D=q.join(tt,".eds-meta.json"),re;if(ae(D))try{re=JSON.parse(await Xe(D,"utf-8")).breakpoints}catch{}let ne=ca(i.widths,re),Tt={provider:s,designRef:p,figmaFileKey:m?.fileKey??null,figmaNodeId:m?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:kt,agentUsed:Y.type,...ne.length?{breakpoints:ne}:{}};await Hd(D,`${JSON.stringify(Tt,null,2)}
895
+ `),ne.length&&r.info(E.dim(` Preview breakpoints: ${ne.map(ei=>ei.width).join(" \xB7 ")}`))}if(!js){r.warn(`Block "${u}" generated with issues \u2014 review the output above before publishing.`),process.exitCode=1;return}if(r.success(`Block "${u}" generation complete.`),!i.yes){let{confirm:D}=await Promise.resolve().then(()=>(G(),H));if(await D({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:ne}=await Promise.resolve().then(()=>(ut(),pt));await ne(u,{})}}if(!i.yes)await Qd({blockName:u,projectRoot:n,agent:Y,model:g.model,provider:s,figma:m,designRef:p});else if(i.serve){let{previewBlock:D}=await Promise.resolve().then(()=>(Oe(),xt));await D(u,{})}else r.info(` ${E.dim("\u2192")} Next: ${E.cyan(`eds block preview ${u}`)}`)}async function Qd(e){let{select:t,input:n}=await Promise.resolve().then(()=>(G(),H)),{startPreview:o}=await Promise.resolve().then(()=>(Oe(),xt)),i=null;for(r.info("");;){let a=await t({message:"Block ready \u2014 what next?",choices:[{name:"Refine \u2014 describe a change",value:"refine"},{name:i?`Preview open at ${i.url} (reloads on change)`:"Open live preview",value:"preview",disabled:i?"running":!1},{name:"Finish",value:"done"}],default:"refine"});if(a==="done")break;if(a==="preview"){await Wd()?r.info(E.dim(" A preview server is already running at http://127.0.0.1:8777.")):i=await o(e.blockName,{});continue}let s=(await n({message:"Describe the change:"})).trim();if(!s)continue;let d=Pa({blockName:e.blockName,feedback:s,provider:e.provider,figma:e.figma,designRef:e.designRef}),l=await po(d,e.projectRoot);r.info(` ${E.dim("\u2192")} Applying your change with ${E.cyan(e.agent.type)}\u2026`),await uo(e.agent,l,e.projectRoot,e.model)}i&&(r.info(E.dim(` Preview still live at ${i.url} \u2014 press Ctrl+C to stop.
896
+ `)),await new Promise(a=>{let s=async()=>{i&&await i.close(),a(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}))}async function Zd(e,t,n){let o=[],i=q.join(e,`${t}.js`),a=q.join(e,`${t}.css`),s=ae(i),d=ae(a);if(o.push({status:s?"pass":"fail",name:`${t}.js`,message:s?"created":"missing \u2014 agent did not write the JS file"}),o.push({status:d?"pass":"fail",name:`${t}.css`,message:d?"created":"missing \u2014 agent did not write the CSS file"}),s){let c=await Xe(i,"utf-8");o.push({status:/export\s+default/.test(c)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(c)?"found":"no default export \u2014 block won't load"}),c.includes("console.log")&&o.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(d){let c=await Xe(a,"utf-8");o.push({status:c.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:c.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let c=ae(q.join(e,`_${t}.json`)),m=q.join(e,"..","..","component-models.json"),p=!1;if(!c&&ae(m))try{p=(await Xe(m,"utf-8")).includes(`"${t}"`)}catch{}let u=c||p;if(o.push({status:u?"pass":"warn",name:"Universal Editor model",message:u?c?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),c&&s)try{let g=await Xe(q.join(e,`_${t}.json`),"utf-8"),h=await Xe(i,"utf-8"),b=/"resourceType"\s*:\s*"[^"]*\/item"/.test(g)||/"filter"\s*:/.test(g)||/"multi"\s*:\s*true/.test(g),w=/\.children/.test(h)||/\bfor\s*\(/.test(h)||/\.forEach\s*\(/.test(h);b&&o.push({status:w?"pass":"warn",name:"multifield wired",message:w?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}r.info(S("Verification"));let l=I(o.map(c=>c.name));for(let c of o)r.info(A(c.status,c.name,c.message,l));return r.info(""),!o.some(c=>c.status==="fail")}var Xd,Co=k(()=>{"use strict";f();mo();oa();ye();la();$a();Sa();Ea();R();z();Be();Fa();bo();M();Xd=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var Ga={};O(Ga,{listBlocks:()=>nm});import{existsSync as $t}from"fs";import{readFile as em,readdir as tm}from"fs/promises";import Ve from"path";import Ye from"chalk";async function nm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ve.join(t,"blocks");if(!$t(n)){r.info("No blocks/ directory found.");return}let o=await tm(n,{withFileTypes:!0}),i=[];for(let s of o){if(!s.isDirectory())continue;let d=s.name,l=Ve.join(n,d),c={name:d,hasJs:$t(Ve.join(l,`${d}.js`)),hasCss:$t(Ve.join(l,`${d}.css`)),hasUeModel:$t(Ve.join(l,`_${d}.json`))},m=Ve.join(l,".eds-meta.json");if($t(m))try{let p=JSON.parse(await em(m,"utf-8"));c.figmaSource={fileKey:p.figmaFileKey,nodeId:p.figmaNodeId,lastSyncedAt:p.lastSyncedAt}}catch{}i.push(c)}if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){r.info("No blocks found.");return}r.info(S("Blocks",`${i.length} in project`));let a=I(i.map(s=>s.name));for(let s of i){let d=[s.hasJs?U.ok("js"):Ye.dim.strikethrough("js"),s.hasCss?U.ok("css"):Ye.dim.strikethrough("css")];s.hasUeModel&&d.push(U.blue("ue-model")),s.figmaSource&&d.push(`${W.figma} ${U.dotPurple("figma")}`);let l=nt(Ye.bold(s.name),a);if(r.info(` ${l} ${Ye.dim("[")}${d.join(" ")}${Ye.dim("]")}`),s.figmaSource){let c=new Date(s.figmaSource.lastSyncedAt).toLocaleDateString();r.info(` ${" ".repeat(a)} ${W.arrow} ${Ye.dim(`figma:${s.figmaSource.fileKey} \xB7 synced ${c}`)}`)}}r.info("")}var za=k(()=>{"use strict";f();R();z();M()});import Wa from"path";function Ao(e,t){return Wa.join(e,"blocks",t,"__snapshots__")}function qa(e,t,n){return Wa.join(Ao(e,t),`${t}-${n}.png`)}function St(e){return`${(e*100).toFixed(2)}%`}async function To(e,t,n=900){let o;try{({chromium:o}=await import("playwright"))}catch{throw new Error(Ja)}let i=await o.launch();try{let a=await i.newPage({viewport:{width:t,height:n}});return await a.goto(e,{waitUntil:"networkidle"}),await a.waitForTimeout(300),await a.screenshot({fullPage:!0})}finally{await i.close()}}async function Ka(){try{let e="pngjs",t="pixelmatch",{PNG:n}=await import(e),o=(await import(t)).default;return{PNG:n,pixelmatch:o}}catch{throw new Error(Ja)}}async function Xa(e,t){let{PNG:n,pixelmatch:o}=await Ka(),i=n.sync.read(e),a=n.sync.read(t);if(i.width!==a.width||i.height!==a.height)return{diffPixels:-1,totalPixels:0,ratio:1,sizeMismatch:!0,width:i.width,height:i.height};let{width:s,height:d}=i,l=new n({width:s,height:d}),c=o(i.data,a.data,l.data,s,d,{threshold:.1}),m=s*d;return{diffPixels:c,totalPixels:m,ratio:m?c/m:0,width:s,height:d,diffPng:n.sync.write(l)}}async function Va(e,t){let{PNG:n,pixelmatch:o}=await Ka(),i=n.sync.read(e),a=n.sync.read(t),s=Math.min(i.width,a.width),d=Math.min(i.height,a.height),l=new n({width:s,height:d}),c=new n({width:s,height:d});i.bitblt(l,0,0,s,d,0,0),a.bitblt(c,0,0,s,d,0,0);let m=new n({width:s,height:d}),p=o(l.data,c.data,m.data,s,d,{threshold:.1}),u=s*d;return{diffPixels:p,totalPixels:u,ratio:u?p/u:0,width:s,height:d,diffPng:n.sync.write(m)}}var Ja,Ya=k(()=>{"use strict";f();Ja=`Visual testing needs extra tools. Install them with:
897
+ npm i -D playwright pixelmatch pngjs && npx playwright install chromium`});var ts={};O(ts,{visualTest:()=>om});import{existsSync as Qa}from"fs";import{mkdir as Ro,readFile as Za,writeFile as jt}from"fs/promises";import fe from"path";import Fo from"chalk";async function om(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}if(t.design){await im(n,e,t);return}let o=e?[e]:await Le(n);if(!o.length){r.warn("No previewable blocks to test.");return}let i=Number.parseInt(t.port??"8788",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8788),s=Number.parseFloat(t.threshold??"0.01"),d=fe.join(n,"tmp","eds-cli","visual-diff");r.logoOnce(C("Visual test"));let l=0,c=0,m=0,p=0;try{for(let u of o){let g=await ue(n,u,t.widths);if(g){r.info(S(u));for(let h of g.breakpoints){let b=await To(es(a.url,u),h.width),w=qa(n,u,h.width),y=Qa(w);if(t.update||!y){await Ro(Ao(n,u),{recursive:!0}),await jt(w,b),y?(p++,r.info(A("pass",`${h.width}px`,"baseline updated"))):(m++,r.info(A("pass",`${h.width}px`,"baseline created")));continue}let v=await Xa(await Za(w),b);if(v.sizeMismatch){c++,r.info(A("fail",`${h.width}px`,`size changed \u2192 ${v.width}\xD7${v.height}`));continue}if(v.ratio>s){c++,await Ro(d,{recursive:!0});let T=fe.join(d,`${u}-${h.width}.diff.png`);v.diffPng&&await jt(T,v.diffPng),r.info(A("fail",`${h.width}px`,`${St(v.ratio)} changed \u2192 ${fe.relative(n,T)}`))}else l++,r.info(A("pass",`${h.width}px`,v.ratio>0?`${St(v.ratio)} (within ${St(s)})`:"identical"))}}}}catch(u){r.error(u instanceof Error?u.message:String(u)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Fo.green(`${l} passed`)} \xB7 ${Fo.yellow(`${c} changed`)} \xB7 ${m} new \xB7 ${p} updated`),c>0&&(r.warn(`${c} visual change(s). Review the diff PNGs in tmp/eds-cli/visual-diff/, then re-run with --update to accept.`),process.exitCode=1)}async function im(e,t,n){if(!t){r.error("Design diff needs a block name: eds block test <name> --design"),process.exitCode=1;return}let o=await ue(e,t,n.widths);if(!o){r.error(`Block "${t}" has no css/js to render.`),process.exitCode=1;return}let i,a,s=fe.join(e,"blocks",t,".eds-meta.json");if(Qa(s))try{let g=JSON.parse(await Za(s,"utf-8"));i=g.figmaFileKey??void 0,a=g.figmaNodeId??void 0}catch{}if(!i||!a){r.error(`"${t}" has no Figma source in .eds-meta.json \u2014 can't fetch the design image.`),process.exitCode=1;return}let l=(await le(e)).figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT;if(!l){r.error("Design diff needs a Figma token (FIGMA_TOKEN or figma.token) to render the node."),process.exitCode=1;return}let c=o.breakpoints.filter(g=>g.figma),m=(c.length?c:o.breakpoints).reduce((g,h)=>h.width>g.width?h:g,o.breakpoints[0]).width,p=Number.parseInt(n.port??"8788",10),u=await Ke(e,n.widths,Number.isFinite(p)?p:8788);r.logoOnce(C("Design \u2194 render")),r.info(S(t,`${m}px`));try{let g=await To(es(u.url,t),m);r.info(A("pass","render","block screenshot captured"));let h=await wa({fileKey:i,nodeId:a,token:l,scale:1});r.info(A("pass","design","Figma image fetched (REST)"));let b=await Va(h,g),w=fe.join(e,"tmp","eds-cli","visual-diff");await Ro(w,{recursive:!0}),await jt(fe.join(w,`${t}-design.png`),h),await jt(fe.join(w,`${t}-render.png`),g),b.diffPng&&await jt(fe.join(w,`${t}-design-diff.png`),b.diffPng),r.info(A("warn","diff",`~${St(b.ratio)} different over ${b.width}\xD7${b.height} (approximate)`)),r.info(""),r.info(Fo.dim(` Saved design / render / diff to ${fe.relative(e,w)}/${t}-*.png \u2014 compare side by side.`))}catch(g){r.error(g instanceof Error?g.message:String(g)),process.exitCode=1}finally{await u.close()}}var es,ns=k(()=>{"use strict";f();ye();ko();R();Ya();z();M();Oe();es=(e,t)=>`${e}${ke.slice(1)}${t}`});async function os(e,t){let n;try{({chromium:n}=await import("playwright"))}catch{throw new Error(rm)}let o=await n.launch();try{let i=await o.newPage({viewport:{width:t,height:900}});return await i.goto(e,{waitUntil:"networkidle"}),await i.waitForTimeout(200),await i.evaluate(am)}finally{await o.close()}}var rm,am,is=k(()=>{"use strict";f();rm=`Content checks need Playwright. Install it with:
898
+ npm i -D playwright && npx playwright install chromium`,am=`(() => {
899
899
  const out = [];
900
900
  const root = document.querySelector('[class$="block"]') || document.body;
901
901
  const trunc = (s) => (s || '').slice(0, 60);
@@ -929,14 +929,14 @@ ${n}
929
929
  }
930
930
  }
931
931
  return out;
932
- })()`});var qa={};L(qa,{blockCheck:()=>Jd});import Ao from"chalk";async function Jd(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let o=e?[e]:await Fe(n);if(!o.length){r.warn("No previewable blocks to check.");return}let i=Number.parseInt(t.port??"8789",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8789);r.logoOnce(E("Content check"));let s=0,d=0,l=0;try{for(let c of o){let p=await pe(n,c,t.widths);if(!p)continue;let m=p.breakpoints.reduce((g,w)=>w.width>g.width?w:g,p.breakpoints[0]).width,u=await Wa(`${a.url}${ve.slice(1)}${c}`,m);if(r.info(S(c,`${m}px`)),!u.length){l++,r.info(A("pass","clean","no issues"));continue}for(let g of u)g.level==="error"?s++:d++,r.info(A(g.level==="error"?"fail":"warn",g.rule,g.detail))}}catch(c){r.error(c instanceof Error?c.message:String(c)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Ao.green(`${l} clean`)} \xB7 ${Ao.red(`${s} error(s)`)} \xB7 ${Ao.yellow(`${d} warning(s)`)}`),(s>0||t.strict&&d>0)&&(process.exitCode=1)}var Ka=v(()=>{"use strict";f();R();Ja();B();N();De()});function Xa(e){return sn.find(t=>t.id===e)}function Va(e,t){return`
932
+ })()`});var rs={};O(rs,{blockCheck:()=>sm});import Do from"chalk";async function sm(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let o=e?[e]:await Le(n);if(!o.length){r.warn("No previewable blocks to check.");return}let i=Number.parseInt(t.port??"8789",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8789);r.logoOnce(C("Content check"));let s=0,d=0,l=0;try{for(let c of o){let m=await ue(n,c,t.widths);if(!m)continue;let p=m.breakpoints.reduce((g,h)=>h.width>g.width?h:g,m.breakpoints[0]).width,u=await os(`${a.url}${ke.slice(1)}${c}`,p);if(r.info(S(c,`${p}px`)),!u.length){l++,r.info(A("pass","clean","no issues"));continue}for(let g of u)g.level==="error"?s++:d++,r.info(A(g.level==="error"?"fail":"warn",g.rule,g.detail))}}catch(c){r.error(c instanceof Error?c.message:String(c)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Do.green(`${l} clean`)} \xB7 ${Do.red(`${s} error(s)`)} \xB7 ${Do.yellow(`${d} warning(s)`)}`),(s>0||t.strict&&d>0)&&(process.exitCode=1)}var as=k(()=>{"use strict";f();R();is();z();M();Oe()});function ss(e){return cn.find(t=>t.id===e)}function cs(e,t){return`
933
933
  // \u2500\u2500 ${e} (eds integrate) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
934
934
  {
935
935
  ${t.split(`
936
936
  `).map(n=>n&&` ${n}`).join(`
937
937
  `)}
938
938
  }
939
- `}var sn,Ya=v(()=>{"use strict";f();sn=[{id:"gtm",name:"Google Tag Manager",fields:[{name:"id",message:"GTM container ID",placeholder:"GTM-XXXXXXX"}],code:()=>`// Google Tag Manager - loaded from ./analytics.js (delayed phase, after LCP).
939
+ `}var cn,ls=k(()=>{"use strict";f();cn=[{id:"gtm",name:"Google Tag Manager",fields:[{name:"id",message:"GTM container ID",placeholder:"GTM-XXXXXXX"}],code:()=>`// Google Tag Manager - loaded from ./analytics.js (delayed phase, after LCP).
940
940
  import { loadGTM } from './analytics.js';
941
941
  import pageMetaPush from './page-meta.js';
942
942
 
@@ -1027,19 +1027,19 @@ document.head.appendChild(cb);`},{id:"custom",name:"Custom third-party script",f
1027
1027
  const s = document.createElement('script');
1028
1028
  s.async = true;
1029
1029
  s.src = ${JSON.stringify(e.url||"")};
1030
- document.head.appendChild(s);`}]});var Ro={};L(Ro,{integrate:()=>Vd});import{existsSync as qd}from"fs";import{mkdir as Qa,readFile as Kd,writeFile as Za}from"fs/promises";import cn from"path";import To from"chalk";async function Vd(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(G(),H)),i=e||await n({message:"Which service do you want to add?",choices:sn.map(m=>({name:m.name,value:m.id}))}),a=Xa(i);if(!a){r.error(`Unknown integration "${i}". Options: ${sn.map(m=>m.id).join(", ")}`),process.exitCode=1;return}let s={};for(let m of a.fields){let u=await o({message:` ${m.message}`,default:m.placeholder});s[m.name]=u.trim()}let d=[];if(a.module)for(let m of a.module(s)){let u=cn.join(t,m.file);await Qa(cn.dirname(u),{recursive:!0}),await Za(u,m.content),d.push(m.file)}let l=a.module?`
1030
+ document.head.appendChild(s);`}]});var Oo={};O(Oo,{integrate:()=>mm});import{existsSync as cm}from"fs";import{mkdir as ds,readFile as lm,writeFile as ms}from"fs/promises";import ln from"path";import Lo from"chalk";async function mm(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(G(),H)),i=e||await n({message:"Which service do you want to add?",choices:cn.map(p=>({name:p.name,value:p.id}))}),a=ss(i);if(!a){r.error(`Unknown integration "${i}". Options: ${cn.map(p=>p.id).join(", ")}`),process.exitCode=1;return}let s={};for(let p of a.fields){let u=await o({message:` ${p.message}`,default:p.placeholder});s[p.name]=u.trim()}let d=[];if(a.module)for(let p of a.module(s)){let u=ln.join(t,p.file);await ds(ln.dirname(u),{recursive:!0}),await ms(u,p.content),d.push(p.file)}let l=a.module?`
1031
1031
  // ${a.name} (eds integrate)
1032
1032
  ${a.code(s)}
1033
- `:Va(a.name,a.code(s)),c=cn.join(t,"scripts","delayed.js");await Qa(cn.dirname(c),{recursive:!0});let p=qd(c)?await Kd(c,"utf-8"):Xd;await Za(c,`${p.replace(/\s*$/,"")}
1034
- ${l}`),r.info(S("Added"));for(let m of d)r.info(j(a.name,`wrote ${m}`));r.info(j(a.name,"wired into scripts/delayed.js")),r.info(""),r.info(To.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(a.id==="gtm"||a.id==="ga4")&&r.info(To.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),a.id==="chat"&&r.info(To.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),r.info(""),r.info(O(["Integration added"]))}var Xd,Fo=v(()=>{"use strict";f();Ya();R();B();N();Xd=`// delayed.js - third-party / non-critical scripts.
1033
+ `:cs(a.name,a.code(s)),c=ln.join(t,"scripts","delayed.js");await ds(ln.dirname(c),{recursive:!0});let m=cm(c)?await lm(c,"utf-8"):dm;await ms(c,`${m.replace(/\s*$/,"")}
1034
+ ${l}`),r.info(S("Added"));for(let p of d)r.info(j(a.name,`wrote ${p}`));r.info(j(a.name,"wired into scripts/delayed.js")),r.info(""),r.info(Lo.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(a.id==="gtm"||a.id==="ga4")&&r.info(Lo.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),a.id==="chat"&&r.info(Lo.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),r.info(""),r.info(N(["Integration added"]))}var dm,No=k(()=>{"use strict";f();ls();R();z();M();dm=`// delayed.js - third-party / non-critical scripts.
1035
1035
  // Loaded in the EDS delayed phase (after LCP), so nothing here blocks the page.
1036
- `});var Do={};L(Do,{figmaSetup:()=>ep});import{existsSync as Yd}from"fs";import{mkdir as Qd,writeFile as Zd}from"fs/promises";import re from"chalk";async function ep(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(E()),r.info(S("Figma MCP Setup Wizard")),r.info("Detecting installed AI agents...");let n=await en(),o;if(n.length===0?(r.warn("No AI agents found (claude, cursor, codex)."),r.info(`Install Claude Code: ${re.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(r.success(`Found: ${n.map(a=>re.cyan(a.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(a=>({name:`${a.type}${a.hasFigmaMcp?re.green(" (Figma MCP detected)"):""}`,value:a.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let a=n.find(s=>s.type===o);if(a&&!a.hasFigmaMcp){switch(r.warn(`Figma MCP is not configured for ${o}.
1036
+ `});var Mo={};O(Mo,{figmaSetup:()=>gm});import{existsSync as pm}from"fs";import{mkdir as um,writeFile as fm}from"fs/promises";import se from"chalk";async function gm(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(C()),r.info(S("Figma MCP Setup Wizard")),r.info("Detecting installed AI agents...");let n=await tn(),o;if(n.length===0?(r.warn("No AI agents found (claude, cursor, codex)."),r.info(`Install Claude Code: ${se.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(r.success(`Found: ${n.map(a=>se.cyan(a.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(a=>({name:`${a.type}${a.hasFigmaMcp?se.green(" (Figma MCP detected)"):""}`,value:a.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let a=n.find(s=>s.type===o);if(a&&!a.hasFigmaMcp){switch(r.warn(`Figma MCP is not configured for ${o}.
1037
1037
  `),r.info(`Install it with one of these methods:
1038
- `),o){case"claude":r.info(` ${re.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),r.info(" or for Figma Desktop app:"),r.info(` ${re.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":r.info(` Add to ${re.cyan("~/.cursor/mcp.json")}:`),r.info(re.dim(JSON.stringify({mcpServers:{figma:{url:"https://mcp.figma.com/sse"}}},null,2)));break;case"codex":r.info(" See Figma MCP docs: https://help.figma.com/hc/en-us/articles/32132100833559");break}r.info("")}else a?.hasFigmaMcp&&r.success(`Figma MCP is already configured for ${o}!`)}if(r.info(re.dim(`
1039
- Note: Figma MCP requires a Figma seat (Dev or Full on paid plans for desktop server).`)),await t({message:"Save preferences to ~/.eds/config.json?",default:!0})){let a=ta();Yd(a)||await Qd(a,{recursive:!0});let s={};o!=="none"&&(s.agent=o),await Zd(go(),`${JSON.stringify(s,null,2)}
1040
- `,{mode:384}),r.success(`Config saved to ${re.cyan(go())}`)}r.info(re.bold(`
1041
- Setup complete!`)),o!=="none"&&r.info(`Try: ${re.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var Lo=v(()=>{"use strict";f();lo();be();R();N()});var Oo={};L(Oo,{doctor:()=>np});import{existsSync as Et}from"fs";import{readFile as Ct,readdir as tp}from"fs/promises";import Le from"path";import{parse as es}from"yaml";async function np(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=xi(t);e.json||(r.logoOnce(E("Doctor")),r.info(S("Doctor",t)));let o=[];if(o.push({name:"fstab.yaml exists",status:n.hasFstab?"pass":"warn",message:n.hasFstab?"Found":"Missing - fine for Universal Editor / DA; required for document-mounted setups"}),n.hasFstab)try{let m=await Ct(Le.join(t,"fstab.yaml"),"utf-8");es(m),o.push({name:"fstab.yaml valid YAML",status:"pass",message:"Valid"})}catch{o.push({name:"fstab.yaml valid YAML",status:"fail",message:"Invalid YAML syntax"})}if(o.push({name:"head.html exists",status:n.hasHeadHtml?"pass":"warn",message:n.hasHeadHtml?"Found":"Missing - recommended for metadata/scripts"}),o.push({name:"blocks/ directory",status:n.hasBlocks?"pass":"warn",message:n.hasBlocks?"Found":"Missing - no blocks yet"}),n.hasBlocks){let m=Le.join(t,"blocks"),u=await tp(m,{withFileTypes:!0}),g="",w=Le.join(t,"component-models.json");if(Et(w))try{g=await Ct(w,"utf-8")}catch{}for(let y of u){if(!y.isDirectory())continue;let h=y.name,$=Le.join(m,h,`${h}.js`),b=Et($);o.push({name:`blocks/${h} has JS`,status:b?"pass":"warn",message:b?"Found":`Missing ${h}.js`}),b&&(await Ct($,"utf-8")).includes("console.log")&&o.push({name:`blocks/${h} no console.log`,status:"warn",message:"Found console.log - remove before production"});let T=Et(Le.join(m,h,`_${h}.json`)),Q=g.includes(`"${h}"`);o.push({name:`blocks/${h} UE model`,status:T||Q?"pass":"warn",message:T||Q?T?`_${h}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let z=Le.join(m,h,".eds-meta.json");if(Et(z))try{let ue=JSON.parse(await Ct(z,"utf-8")),te=new Date(ue.lastSyncedAt),tt=Math.floor((Date.now()-te.getTime())/(1e3*60*60*24));o.push({name:`blocks/${h} Figma sync`,status:tt>30?"warn":"pass",message:tt>30?`Last synced ${tt} days ago - design may have changed`:`Synced ${tt} days ago`})}catch{o.push({name:`blocks/${h} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let i=Le.join(t,"helix-query.yaml");if(Et(i))try{let m=await Ct(i,"utf-8");es(m),o.push({name:"helix-query.yaml valid",status:"pass",message:"Valid YAML"})}catch{o.push({name:"helix-query.yaml valid",status:"fail",message:"Invalid YAML syntax"})}o.push({name:"~/.eds/config.json",status:ho()?"pass":"warn",message:ho()?"Found":'Missing - run "eds figma setup" to configure'});let a=o.filter(m=>m.status==="fail"),s=o.filter(m=>m.status==="warn");if(e.json){let m={pass:o.filter(u=>u.status==="pass").length,warn:s.length,fail:a.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:m},null,2)),a.length>0&&(process.exitCode=1);return}let d=M(o.map(m=>m.name));for(let m of o)r.info(A(m.status,m.name,m.message,d));let l=o.filter(m=>m.status==="fail"),c=o.filter(m=>m.status==="warn"),p=o.filter(m=>m.status==="pass");r.info(""),r.info(O([fe({pass:p.length,warn:c.length,fail:l.length})])),l.length>0&&(process.exitCode=1)}var No=v(()=>{"use strict";f();be();R();B();N()});var Io={};L(Io,{auditLoading:()=>ip});import{existsSync as ke}from"fs";import{readFile as Qe,readdir as op,stat as ts}from"fs/promises";import xe from"path";import Mo from"chalk";async function ip(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(r.logoOnce(E("Loading Audit")),r.info(S("Loading Order Audit",t)));let n=[];if(await rp(t,n),await ap(t,n),await sp(t,n),await cp(t,n),await lp(t,n),await dp(t,n),e.json){let o={pass:n.filter(i=>i.status==="pass").length,warn:n.filter(i=>i.status==="warn").length,fail:n.filter(i=>i.status==="fail").length,info:n.filter(i=>i.status==="info").length};console.log(JSON.stringify({projectRoot:t,results:n,summary:o},null,2)),o.fail>0&&(process.exitCode=1);return}mp(n)}async function rp(e,t){let n=xe.join(e,"head.html");if(!ke(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1042
- `);for(let l=0;l<i.length;l++){let c=i[l];/<script\b/i.test(c)&&!/type\s*=\s*["']module["']/i.test(c)&&!/<\/script>/.test(c)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:l+1})}let s=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(l=>!l.includes("styles/styles.css")&&!l.includes("styles.css"));s.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${s.length} extra stylesheet(s) \u2014 each competes with LCP budget`,file:"head.html"}),/<link[^>]+rel=["'](preload|preconnect)["']/i.test(o)&&t.push({rule:"No preload/preconnect in head.html",status:"warn",message:"preload/preconnect can hurt EDS LCP \u2014 resources compete with the 100KB budget",file:"head.html"}),/<script\b[^>]*>[\s\S]*?[^\s<][\s\S]*?<\/script>/i.test(o)&&t.push({rule:"No inline scripts in head.html",status:"warn",message:"Inline scripts block rendering \u2014 move to delayed.js",file:"head.html"});let d=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let l of o.matchAll(d)){let c=l[1];c.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${c} \u2014 move to delayed.js`,file:"head.html"})}/<link[^>]+as=["']font["']/i.test(o)&&t.push({rule:"No font preloads in head.html",status:"warn",message:"Font preloads consume LCP bandwidth budget \u2014 let loadFonts() handle them",file:"head.html"}),t.some(l=>l.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function ap(e,t){let n=xe.join(e,"scripts","scripts.js");if(!ke(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1043
- `),a=/function\s+loadEager|loadEager\s*=/i.test(o),s=/function\s+loadLazy|loadLazy\s*=/i.test(o),d=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:d?"pass":"warn",message:d?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let l=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(d&&l){let c=Number.parseInt(l[1],10);c<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${c}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${c}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(a){let c=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(c)&&t.push({rule:"loadEager loads only first section",status:"fail",message:"loadEager calls loadSections() \u2014 should only load first section for fast LCP",file:"scripts/scripts.js"})}for(let c=0;c<i.length;c++){let p=i[c];/import\s.*from\s+['"]https?:\/\//i.test(p)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${c+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:c+1})}if(a){let c=pp(o,"loadEager");c&&/loadHeader|loadFooter/.test(c)&&t.push({rule:"Header/footer not in loadEager",status:"warn",message:"Header/footer in loadEager delays LCP \u2014 move to loadLazy",file:"scripts/scripts.js"})}}async function sp(e,t){let n=xe.join(e,"styles","styles.css");if(!ke(n))return;let i=(await ts(n)).size/1024;t.push({rule:"styles.css size within LCP budget",status:i>40?"warn":"pass",message:`${i.toFixed(1)} KB${i>40?" \u2014 large CSS competes with 100KB LCP budget":""}`,file:"styles/styles.css"});let a=await Qe(n,"utf-8");/@import\s/.test(a)&&t.push({rule:"No @import in styles.css",status:"warn",message:"@import creates a request chain \u2014 inline the CSS or use lazy-styles.css",file:"styles/styles.css"})}async function cp(e,t){let n=xe.join(e,"scripts","delayed.js");if(!ke(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await Qe(n,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim()||t.push({rule:"delayed.js has content",status:"info",message:"delayed.js is empty \u2014 add analytics/martech here",file:"scripts/delayed.js"})}async function lp(e,t){let n=xe.join(e,"blocks");if(!ke(n))return;let o=await op(n,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=xe.join(n,a,`${a}.js`);if(!ke(s))continue;let d=await Qe(s,"utf-8"),l=d.split(`
1044
- `),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let u=0;u<l.length;u++){let g=l[u].toLowerCase();for(let w of c)g.includes("from")&&g.includes(w)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${w}" \u2014 heavy library delays section loading`,file:`blocks/${a}/${a}.js`,line:u+1})}/document\.write/i.test(d)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${a}/${a}.js`});let m=(await ts(s)).size/1024;m>20&&t.push({rule:"Block JS size reasonable",status:"warn",message:`${m.toFixed(1)} KB \u2014 consider splitting or lazy-loading parts`,file:`blocks/${a}/${a}.js`})}for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=xe.join(n,a,`${a}.css`);if(!ke(s))continue;let d=await Qe(s,"utf-8"),l=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let c of d.matchAll(l)){let p=c[1];["body","html","main"].includes(p)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${p}" \u2014 may leak styles and cause CLS. Use .${a} prefix`,file:`blocks/${a}/${a}.css`})}}}async function dp(e,t){let n=xe.join(e,"scripts","aem.js");if(!ke(n)){t.push({rule:"scripts/aem.js exists",status:"warn",message:"Missing aem.js (or lib-franklin.js) \u2014 the EDS framework library"});return}t.push({rule:"aem.js present",status:"pass",message:"Found \u2014 remember: never modify this file",file:"scripts/aem.js"})}function pp(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let i=1,a=o.index+o[0].length,s=a;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,a++;return e.slice(s,a-1)}function mp(e){let t=new Map;for(let o of e){let i=o.file||"general",a=t.get(i)??[];a.push(o),t.set(i,a)}for(let[o,i]of t){r.info(` ${q.bullet} ${Mo.underline(o)}`);for(let a of i){let s=a.line?Mo.dim(`:${a.line}`):"";r.info(` ${Tt(a.status)} ${a.rule}${s}`),a.status!=="pass"&&r.info(Mo.dim(` ${a.message}`))}r.info("")}let n={pass:e.filter(o=>o.status==="pass").length,warn:e.filter(o=>o.status==="warn").length,fail:e.filter(o=>o.status==="fail").length,info:e.filter(o=>o.status==="info").length};r.info(O([fe(n)])),n.fail>0&&(process.exitCode=1)}var _o=v(()=>{"use strict";f();R();B();N()});var Bo={};L(Bo,{auditSecurity:()=>kp});import{existsSync as ln}from"fs";import{readFile as up,readdir as fp}from"fs/promises";import Oe from"path";import Uo from"chalk";async function*os(e){let t=await fp(e,{withFileTypes:!0});for(let n of t){let o=Oe.join(e,n.name);if(n.isDirectory()){if(wp.has(n.name))continue;yield*os(o)}else n.isFile()&&(yield o)}}function yp(e,t,n){let o=[],i=e.split(`
1045
- `);for(let a=0;a<i.length;a++){let s=i[a],d=!1;for(let l of gp)l.ext.includes(n)&&(l.id==="innerhtml-static"&&d||l.re.test(s)&&(l.extra&&!l.extra(s)||(l.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:l.severity,rule:l.id,message:l.message,file:t,line:a+1,snippet:s.trim().slice(0,100)}))))}return o}async function vp(e){if(!ln(Oe.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(ln(Oe.join(e,"package-lock.json"))||ln(Oe.join(e,"npm-shrinkwrap.json")))&&!ln(Oe.join(e,"node_modules")))return{status:"skipped",note:"no package-lock.json / node_modules \u2014 run npm install"};try{let{execa:n}=await import("execa"),{stdout:o}=await n("npm",["audit","--json"],{cwd:e,reject:!1}),a=JSON.parse(o)?.metadata?.vulnerabilities??{},s={critical:a.critical??0,high:a.high??0,moderate:a.moderate??0,low:a.low??0};return{status:s.critical+s.high+s.moderate+s.low>0?"vulnerable":"ok",counts:s}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function kp(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let l of os(t)){let c=Oe.extname(l).slice(1).toLowerCase();if(!bp.has(c))continue;let p=Oe.relative(t,l);if(p.endsWith("aem.js")||p.endsWith("lib-franklin.js"))continue;let m=await up(l,"utf-8");n.push(...yp(m,p,c))}let o=await vp(t),i=l=>n.filter(c=>c.severity===l),a={critical:i("critical").length,high:i("high").length,moderate:i("moderate").length,low:i("low").length},s=a.critical>0||a.high>0||(o.counts?.critical??0)>0||(o.counts?.high??0)>0;if(e.json){console.log(JSON.stringify({projectRoot:t,dependencies:o,findings:n,summary:{code:a}},null,2)),s&&(process.exitCode=1);return}if(r.logoOnce(E("Security Audit")),r.info(S("Dependencies","npm audit")),o.status==="skipped")r.info(A("info","npm audit",o.note??"skipped"));else if(o.status==="ok")r.info(A("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};r.info(A(l.critical+l.high>0?"fail":"warn","npm audit",`${l.critical} critical, ${l.high} high, ${l.moderate} moderate, ${l.low} low \u2014 run \`npm audit fix\``))}if(r.info(S("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)r.info(A("pass","code","no risky patterns found"));else{let l=[...n].sort((c,p)=>ns.indexOf(c.severity)-ns.indexOf(p.severity));for(let c of l){let p=hp[c.severity],m=Uo.dim(`${c.file}:${c.line}`);r.info(` ${Tt(p.status)} ${Uo.bold(p.label)} ${c.message} ${m}`),r.info(Uo.dim(` ${c.snippet}`))}}let d=fe({fail:a.critical+a.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:a.moderate+(o.counts?.moderate??0),info:a.low+(o.counts?.low??0)});r.info(""),r.info(O([d||`${q.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var gp,ns,hp,wp,bp,Ho=v(()=>{"use strict";f();R();B();N();gp=[{id:"eval",severity:"critical",re:/\beval\s*\(/,message:"eval() executes arbitrary code \u2014 prime XSS / RCE vector",ext:["js","mjs","html"]},{id:"aws-key",severity:"critical",re:/\bAKIA[0-9A-Z]{16}\b/,message:"Hardcoded AWS access key id",ext:["js","mjs","html","json"]},{id:"private-key",severity:"critical",re:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,message:"Embedded private key material",ext:["js","mjs","html","json","pem","txt"]},{id:"new-function",severity:"high",re:/\bnew\s+Function\s*\(/,message:"new Function() runs strings as code",ext:["js","mjs","html"]},{id:"document-write",severity:"high",re:/document\.write(?:ln)?\s*\(/,message:"document.write() enables XSS and blocks parsing",ext:["js","mjs","html"]},{id:"innerhtml-dynamic",severity:"high",re:/\.(?:inner|outer)HTML\s*=\s*[^;\n]*(?:\$\{|\+|concat)/,message:"Dynamic innerHTML assignment \u2014 sanitize or use textContent / DOM APIs",ext:["js","mjs"]},{id:"insert-adjacent-html",severity:"high",re:/insertAdjacentHTML\s*\(/,message:"insertAdjacentHTML with untrusted data is an XSS vector",ext:["js","mjs"]},{id:"js-url",severity:"high",re:/(?:href|src)\s*=\s*["']?\s*javascript:/i,message:"javascript: URL \u2014 XSS vector",ext:["js","mjs","html"]},{id:"secret",severity:"high",re:/(?:api[_-]?key|secret|access[_-]?token|auth[_-]?token|client[_-]?secret|passwd|password)\s*[:=]\s*["'][^"']{8,}["']/i,message:"Possible hardcoded secret / credential",ext:["js","mjs","html","json"],extra:e=>!/(example|placeholder|your[-_]|changeme|xxxx|<[^>]+>|\$\{)/i.test(e)},{id:"bearer-token",severity:"high",re:/Bearer\s+[A-Za-z0-9\-._~+/]{20,}/,message:"Hardcoded bearer token",ext:["js","mjs","html","json"]},{id:"innerhtml-static",severity:"moderate",re:/\.(?:inner|outer)HTML\s*=/,message:"innerHTML assignment \u2014 confirm the content is trusted / sanitized",ext:["js","mjs"]},{id:"insecure-url",severity:"moderate",re:/(?:href|src)\s*=\s*["']http:\/\/(?!localhost|127\.0\.0\.1)/i,message:"Insecure http:// resource \u2014 mixed content, use https://",ext:["html","js","mjs"]},{id:"target-blank",severity:"moderate",re:/target\s*=\s*["']_blank["']/,message:'target="_blank" without rel="noopener" \u2014 reverse tabnabbing',ext:["html","js","mjs"],extra:e=>!/rel\s*=\s*["'][^"']*noopener/i.test(e)},{id:"postmessage-wildcard",severity:"moderate",re:/postMessage\s*\([^,]+,\s*["']\*["']\s*\)/,message:"postMessage to '*' origin \u2014 restrict the target origin",ext:["js","mjs"]},{id:"inline-handler",severity:"low",re:/\son[a-z]+\s*=\s*["']/i,message:"Inline event handler \u2014 move to addEventListener (CSP-unfriendly)",ext:["html"]},{id:"console-log",severity:"low",re:/console\.(?:log|debug)\s*\(/,message:"console.log / debug left in code \u2014 potential info leak",ext:["js","mjs"]}],ns=["critical","high","moderate","low"],hp={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},wp=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),bp=new Set(["js","mjs","html","json","pem","txt"])});async function is(e,t,n){let o=t.ref||"main",i=n.startsWith("/")?n:`/${n}`,a=`${xp}/${e}/${t.org}/${t.site}/${o}${i}`;r.debug(`POST ${a}`);let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await s.json().catch(()=>({})),l=d;return s.ok?{ok:!0,status:s.status,path:i,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:i,message:d.message||`HTTP ${s.status}`}}async function Go(e,t){return is("preview",e,t)}async function zo(e,t){return is("live",e,t)}async function rs(e,t){return Promise.all(t.map(n=>Go(e,n)))}async function as(e,t){return Promise.all(t.map(n=>zo(e,n)))}var xp,Wo=v(()=>{"use strict";f();R();xp="https://admin.hlx.page"});var Jo={};L(Jo,{preview:()=>Sp,resolveAdminConfig:()=>dn});import ss from"chalk";import $p from"ora";async function Sp(e,t){let n=P(),o=await se(n),i=dn(o,t);if(!i)return;let a=$p(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await Go(i,e[0])]:await rs(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${ss.cyan(l.previewUrl||"preview updated")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function dn(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,i=t.ref||e.admin?.ref||"main";if(!n||!o){r.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),r.info(ss.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:i}}var pn=v(()=>{"use strict";f();Wo();be();R();B()});var qo={};L(qo,{publish:()=>Ep});import jp from"chalk";import Pp from"ora";async function Ep(e,t){let n=P(),o=await se(n),i=dn(o,t);if(!i)return;let a=Pp(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await zo(i,e[0])]:await as(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${jp.cyan(l.liveUrl||"published")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Ko=v(()=>{"use strict";f();Wo();be();R();B();pn()});var mn={};L(mn,{adminWizard:()=>Cp});async function Cp(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(E("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),s=(await se(t)).admin??{},d=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),l=(await o({message:"GitHub org / owner",default:s.org})).trim(),c=(await o({message:"Repository / site",default:s.site})).trim(),p=(await o({message:"Git ref",default:s.ref||"main"})).trim(),u=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||u.length===0){r.error("org, site and at least one path are required."),process.exitCode=1;return}r.info(S("Summary"));let g=M(["operation","org","site","ref","paths"]);if(r.info(j("operation",d,g)),r.info(j("org",l,g)),r.info(j("site",c,g)),r.info(j("ref",p,g)),r.info(j("paths",u.join(", "),g)),r.info(""),d==="publish"&&!await i({message:`Publish ${u.length} path(s) to LIVE?`,default:!1})){r.info("Cancelled.");return}let w={org:l,site:c,ref:p};if(d==="preview"){let{preview:y}=await Promise.resolve().then(()=>(pn(),Jo));await y(u,w)}else{let{publish:y}=await Promise.resolve().then(()=>(Ko(),qo));await y(u,w)}}var un=v(()=>{"use strict";f();be();R();B();N()});var cs={};L(cs,{mainMenu:()=>Fp});import{existsSync as Ap}from"fs";import{readdir as Tp}from"fs/promises";import Rp from"path";async function Xo(e){let t=Rp.join(e,"blocks");return Ap(t)?(await Tp(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function Fp(){let{select:e,input:t}=await Promise.resolve().then(()=>(G(),H));switch(await r.logoOnceAnimated(""),await e({message:"Choose an action",choices:[{name:"Set up project",value:"init",description:"Authoring model, CI, naming"},{name:"Page template",value:"template",description:"Generate initial content"},{name:"Sandbox repo",value:"sandbox",description:"Disposable GitHub repo"},{name:"Block from design",value:"from-design",description:"Figma, Framer or Google Stitch"},{name:"Migrate component",value:"migrate",description:"Classic AEM component \u2192 EDS"},{name:"Scaffold UE",value:"scaffold",description:"Universal Editor components"},{name:"Empty block",value:"create",description:"Create a bare block"},{name:"Integration",value:"integrate",description:"GTM, chat, consent\u2026"},{name:"Model fields",value:"model",description:"Add fields to a block model (partials)"},{name:"Analytics",value:"track",description:"Instrument a block (dataLayer)"},{name:"Structured data",value:"schema",description:"Add JSON-LD to a block"},{name:"Universal Editor",value:"ue",description:"Check readiness / open the editor"},{name:"Preview block",value:"preview-block",description:"Live preview in the browser"},{name:"Pages",value:"admin",description:"Preview / publish (Admin API)"},{name:"Audit",value:"audit",description:"Doctor / loading / security"},{name:"Figma MCP",value:"figma-setup",description:"Configure the connection"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(Jt(),Wt));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:i}=await Promise.resolve().then(()=>(In(),Mn));await i(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:a=>/^[a-z0-9][a-z0-9._-]*$/i.test(a.trim())||"Use a valid repo name"}),{sandboxNew:i}=await Promise.resolve().then(()=>(Ae(),Ce));await i(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(So(),$o));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(zn(),Gn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(ae(),le));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>Se.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:i}=await Promise.resolve().then(()=>(ro(),io));await i(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(Fo(),Ro));await o(void 0);return}case"preview-block":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(De(),$t));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(Zn(),Qn));await o(void 0,[],{});return}case"track":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:i.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(ft(),ut));await s(a,{});return}case"schema":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Xo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(to(),eo));await s(a,{});return}case"ue":{if(await e({message:"Universal Editor:",choices:[{name:"Check readiness (which blocks are editable)",value:"check"},{name:"Open a page in the editor",value:"open"}]})==="check"){let{ueCheck:i}=await Promise.resolve().then(()=>(bt(),wt));await i()}else{let i=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(bt(),wt));await a(i.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o();return}case"audit":{let o=await e({message:"Which audit?",choices:[{name:"Doctor \u2014 overall project health",value:"doctor"},{name:"Loading \u2014 three-phase / LCP budget",value:"loading"},{name:"Security \u2014 vulnerabilities & exploit patterns",value:"security"}]});if(o==="doctor"){let{doctor:i}=await Promise.resolve().then(()=>(No(),Oo));await i({})}else if(o==="loading"){let{auditLoading:i}=await Promise.resolve().then(()=>(_o(),Io));await i({})}else{let{auditSecurity:i}=await Promise.resolve().then(()=>(Ho(),Bo));await i({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(Lo(),Do));await o();return}}}var ls=v(()=>{"use strict";f();R();B();Be()});f();import Dp from"chalk";import{Command as Lp}from"commander";var Vo={name:"aem-eds-kit",version:"0.4.30",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","samples","CHANGELOG.md"],scripts:{dev:"tsx src/bin/eds.ts",build:"tsup",test:"vitest run","test:watch":"vitest",lint:"biome check src/ tests/","lint:fix":"biome check --write src/ tests/",typecheck:"tsc --noEmit",prepare:"git config core.hooksPath .githooks || true",prepublishOnly:"npm run build"},keywords:["aem","edge-delivery-services","helix","figma","mcp","cli","adobe"],author:"Piotr Godycki <piotrgodycki@yahoo.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/piotrgodycki/aem-eds-kit.git"},homepage:"https://piotrgodycki.github.io/aem-eds-kit/",bugs:{url:"https://github.com/piotrgodycki/aem-eds-kit/issues"},dependencies:{"@inquirer/prompts":"^7.0.0",chalk:"^5.4.0",commander:"^13.0.0",execa:"^9.5.0","fast-xml-parser":"^5.11.2",ora:"^8.1.0",yaml:"^2.6.0",zod:"^3.24.0"},devDependencies:{"@biomejs/biome":"^1.9.0","@types/node":"^22.0.0",tsup:"^8.3.0",tsx:"^4.19.0",typescript:"^5.7.0",vitest:"^2.1.0"},optionalDependencies:{"@modelcontextprotocol/sdk":"^1.29.0",pixelmatch:"^6.0.0",playwright:"^1.48.0",pngjs:"^7.0.0"}};R();N();var I=new Lp;I.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(Vo.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-error output").option("--json","Output in JSON format").option("--no-color","Disable color output").showHelpAfterError("(add --help for usage)").hook("preAction",e=>{let t=e.opts();t.verbose&&r.setLevel("debug"),t.quiet&&r.setQuiet(!0),t.color===!1&&(Dp.level=0)});I.addHelpText("beforeAll",()=>E());var At=I.command("sandbox").description("Disposable EDS sandbox repos on GitHub");At.command("new <name>").description("Create a disposable EDS repo from a boilerplate (GitHub auth, no gh required)").option("--org <org>","Create under a GitHub org (else your account)").option("--boilerplate <repo>","Template repo (default adobe/aem-boilerplate)").option("--ue","Use the crosswalk / Universal Editor boilerplate").option("--private","Create a private repo").option("--yes","Skip the guided prompts (use flags/defaults)").action(async(e,t)=>{let{sandboxNew:n}=await Promise.resolve().then(()=>(Ae(),Ce));await n(e,t)});At.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Ae(),Ce));await e()});At.command("rm <name>").description("Delete a sandbox repo (destructive)").option("--org <org>","Owner org (else your account)").option("--yes","Skip the confirmation").action(async(e,t)=>{let{sandboxRm:n}=await Promise.resolve().then(()=>(Ae(),Ce));await n(e,t)});var Op=I.command("template").description("Generate page templates / initial content");Op.command("new <name>").description("Generate EDS page initial content (sections + blocks + metadata), DA push optional").option("--path <path>","Content path (default: /templates/<name>)").option("--title <title>","Page title").option("--description <text>","Page description").option("--blocks <list>","Comma-separated block ids to seed",e=>e.split(",").map(t=>t.trim())).option("--area <area>","Site area / template label (stored in metadata)").option("--authoring <model>","Force authoring model: da | gdrive | sharepoint | ue").option("--push","Push the page to DA (da.live)").option("--org <org>","DA org (else from .edsrc.json)").option("--site <site>","DA site (else from .edsrc.json)").option("--yes","Skip prompts").action(async(e,t)=>{let{templateNew:n}=await Promise.resolve().then(()=>(In(),Mn));await n(e,t)});I.command("init").description("Set up a freshly cloned EDS boilerplate for your authoring model (interactive)").option("--name <name>","Project name (kebab-case)").option("--authoring <model>","Authoring model: ue | da | gdrive | sharepoint").option("--mountpoint <url>","Content source URL (document models)").option("--org <org>","DA org (authoring=da)").option("--site <site>","DA site (authoring=da)").option("--no-ci","Skip the GitHub Actions CI workflow").option("--no-env","Skip the local-dev .env (aem up config)").option("--no-xwalk","Skip xwalk.json (UE multi-field)").option("--yes","Skip prompts; apply with flags/defaults").action(async e=>{let{initProject:t}=await Promise.resolve().then(()=>(Jt(),Wt));await t(e)});var Np=I.command("migrate").description("Migrate from classic AEM to EDS");Np.command("component [dir]").description("Migrate a classic AEM component's dialog into an EDS block + UE model").option("--name <name>","Block name (otherwise inferred from the component)").option("--clientlib <dir>","Path to the component's clientlib (otherwise auto-detected)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(zn(),Gn));await n(e,t)});var Mp=I.command("model").description("Compose Universal Editor models");Mp.command("add <block> [partials...]").description("Add reusable field groups (partials) to a block's UE model").option("--yes","Skip prompts").action(async(e,t,n)=>{let{modelAdd:o}=await Promise.resolve().then(()=>(Zn(),Qn));await o(e,t,n)});var Ip=I.command("schema").description("Structured data (JSON-LD) for blocks");Ip.command("block <name>").description("Inject a JSON-LD (schema.org) builder into a block's decorate()").option("--type <type>","schema.org type (Article, FAQPage, Product, ...)").option("--yes","Skip prompts").action(async(e,t)=>{let{schemaBlock:n}=await Promise.resolve().then(()=>(to(),eo));await n(e,t)});var _p=I.command("track").description("Instrument blocks for analytics");_p.command("block <name>").description("Add dataLayer tracking (click + form submit) to a block's decorate()").option("--no-click","Skip click tracking").option("--no-submit","Skip form-submit tracking").action(async(e,t)=>{let{trackBlock:n}=await Promise.resolve().then(()=>(ft(),ut));await n(e,t)});var ds=I.command("ue").description("Universal Editor - readiness check + editor deep link");ds.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(bt(),wt));await e()});ds.command("open [path]").description("Open a page in the hosted Universal Editor (preview host from git)").option("--org <slug>","IMS org slug (skips the org picker)").option("--ref <branch>","Branch/ref for the preview host (default: main)").option("--url <host>","Override the delivery host (e.g. main--repo--owner.aem.page)").option("--no-open","Print the link without opening the browser").action(async(e,t)=>{let{ueOpen:n}=await Promise.resolve().then(()=>(bt(),wt));await n(e,t)});var Ze=I.command("block").description("Manage EDS blocks");Ze.command("create <name>").description("Scaffold a new EDS block (with Universal Editor model by default)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").action(async(e,t)=>{let{createBlock:n}=await Promise.resolve().then(()=>(ro(),io));await n(e,t)});Ze.command("from-design [design]").description("Generate an EDS block from a design: a Figma URL, a Framer/Stitch page (scraped with headless Chromium), or a local SVG/PNG export (quota-free, no MCP). Interactive wizard when run with no argument.").option("--name <name>","Override the inferred block name").option("--provider <type>","Design source: figma | framer | stitch (else detected from the URL)").option("--agent <type>","Force agent type (claude|cursor|codex|none)").option("--dry-run","Generate prompt only, do not invoke agent").option("--source <type>","Content source: document|ue|cf|mixed (default: document)").option("--widths <list>","Design frame widths for preview breakpoints (e.g. 390,768,1440)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").option("--screenshot","Add a screenshot MCP call for pixel verification (opt-in; costs a call)").option("--mcp","Force the Figma MCP adapter even when a REST token is set").option("--refresh","Ignore the cached design snapshot and re-fetch").option("--sample","Use the bundled sample design (Kiri Bloom hero) \u2014 no URL, no token, no MCP").option("--serve","Auto-start the live preview after generating (non-interactive runs only)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(So(),$o));await n(e,t)});Ze.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(Fa(),Ra));await t({...e,json:I.opts().json})});Ze.command("preview [name]").description("Serve a live, breakpoint-switchable preview of a block \u2014 or a gallery of all blocks when no name is given").option("--port <port>","Port to serve on (default: 8777, falls back if taken)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--no-open","Do not open the browser automatically").action(async(e,t)=>{let n=await Promise.resolve().then(()=>(De(),$t));e?await n.previewBlock(e,t):await n.galleryPreview(t)});Ze.command("test [name]").description("Visual-regression test a block (or all blocks) against committed baselines").option("--update","(Re)write the baseline screenshots instead of comparing").option("--threshold <ratio>","Max changed-pixel ratio before failing (default 0.01 = 1%)").option("--design","Compare the rendered block against its Figma design image (needs a token)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--port <port>","Port for the internal preview server (default: 8788)").action(async(e,t)=>{let{visualTest:n}=await Promise.resolve().then(()=>(za(),Ga));await n(e,t)});Ze.command("check [name]").description("Content, link and a11y check on a block's rendered DOM (or all blocks)").option("--strict","Fail on warnings too, not just errors").option("--widths <list>","Comma-separated breakpoint widths (uses the widest)").option("--port <port>","Port for the internal preview server (default: 8789)").action(async(e,t)=>{let{blockCheck:n}=await Promise.resolve().then(()=>(Ka(),qa));await n(e,t)});var et=I.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("blocks [names...]").description("Scaffold standard blocks (hero, cards, columns, accordion, embed) with UE models").action(async e=>{let{scaffoldBlocks:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(ae(),le));await e()});et.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("env").description("Write a local-dev .env for `aem up` (AEM_OPEN / AEM_PORT / AEM_PAGES_URL)").option("--open <path>","AEM_OPEN - path opened on start (default: /)").option("--port <port>","AEM_PORT - proxy port (default: 3007)").option("--pages-url <url>","AEM_PAGES_URL - content origin (default: from git remote)").option("--yes","Skip prompts; use flags/defaults").action(async e=>{let{scaffoldEnv:t}=await Promise.resolve().then(()=>(ae(),le));await t(e)});et.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(ae(),le));await e()});I.command("integrate [type]").description("Add a third-party service (GTM, GA4, chat, consent) to scripts/delayed.js").action(async e=>{let{integrate:t}=await Promise.resolve().then(()=>(Fo(),Ro));await t(e)});var Up=I.command("figma").description("Figma MCP integration");Up.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(Lo(),Do));await e()});I.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(No(),Oo));await e({json:I.opts().json})});var ps=I.command("audit").description("Run project audits");ps.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(_o(),Io));await e({json:I.opts().json})});ps.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Ho(),Bo));await e({json:I.opts().json})});I.command("preview [paths...]").description("Preview pages via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(pn(),Jo));await n(e,t)});I.command("publish [paths...]").description("Publish pages to live via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(un(),mn));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Ko(),qo));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(ls(),cs));await e()}else I.outputHelp();else await I.parseAsync()}catch(e){r.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();
1038
+ `),o){case"claude":r.info(` ${se.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),r.info(" or for Figma Desktop app:"),r.info(` ${se.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":r.info(` Add to ${se.cyan("~/.cursor/mcp.json")}:`),r.info(se.dim(JSON.stringify({mcpServers:{figma:{url:"https://mcp.figma.com/sse"}}},null,2)));break;case"codex":r.info(" See Figma MCP docs: https://help.figma.com/hc/en-us/articles/32132100833559");break}r.info("")}else a?.hasFigmaMcp&&r.success(`Figma MCP is already configured for ${o}!`)}if(r.info(se.dim(`
1039
+ Note: Figma MCP requires a Figma seat (Dev or Full on paid plans for desktop server).`)),await t({message:"Save preferences to ~/.eds/config.json?",default:!0})){let a=aa();pm(a)||await um(a,{recursive:!0});let s={};o!=="none"&&(s.agent=o),await fm(ho(),`${JSON.stringify(s,null,2)}
1040
+ `,{mode:384}),r.success(`Config saved to ${se.cyan(ho())}`)}r.info(se.bold(`
1041
+ Setup complete!`)),o!=="none"&&r.info(`Try: ${se.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var Io=k(()=>{"use strict";f();mo();ye();R();M()});var _o={};O(_o,{doctor:()=>wm});import{existsSync as Pt}from"fs";import{readFile as Et,readdir as hm}from"fs/promises";import Ne from"path";import{parse as ps}from"yaml";async function wm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ei(t);e.json||(r.logoOnce(C("Doctor")),r.info(S("Doctor",t)));let o=[];if(o.push({name:"fstab.yaml exists",status:n.hasFstab?"pass":"warn",message:n.hasFstab?"Found":"Missing - fine for Universal Editor / DA; required for document-mounted setups"}),n.hasFstab)try{let p=await Et(Ne.join(t,"fstab.yaml"),"utf-8");ps(p),o.push({name:"fstab.yaml valid YAML",status:"pass",message:"Valid"})}catch{o.push({name:"fstab.yaml valid YAML",status:"fail",message:"Invalid YAML syntax"})}if(o.push({name:"head.html exists",status:n.hasHeadHtml?"pass":"warn",message:n.hasHeadHtml?"Found":"Missing - recommended for metadata/scripts"}),o.push({name:"blocks/ directory",status:n.hasBlocks?"pass":"warn",message:n.hasBlocks?"Found":"Missing - no blocks yet"}),n.hasBlocks){let p=Ne.join(t,"blocks"),u=await hm(p,{withFileTypes:!0}),g="",h=Ne.join(t,"component-models.json");if(Pt(h))try{g=await Et(h,"utf-8")}catch{}for(let b of u){if(!b.isDirectory())continue;let w=b.name,y=Ne.join(p,w,`${w}.js`),v=Pt(y);o.push({name:`blocks/${w} has JS`,status:v?"pass":"warn",message:v?"Found":`Missing ${w}.js`}),v&&(await Et(y,"utf-8")).includes("console.log")&&o.push({name:`blocks/${w} no console.log`,status:"warn",message:"Found console.log - remove before production"});let T=Pt(Ne.join(p,w,`_${w}.json`)),K=g.includes(`"${w}"`);o.push({name:`blocks/${w} UE model`,status:T||K?"pass":"warn",message:T||K?T?`_${w}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let J=Ne.join(p,w,".eds-meta.json");if(Pt(J))try{let Se=JSON.parse(await Et(J,"utf-8")),At=new Date(Se.lastSyncedAt),Y=Math.floor((Date.now()-At.getTime())/(1e3*60*60*24));o.push({name:`blocks/${w} Figma sync`,status:Y>30?"warn":"pass",message:Y>30?`Last synced ${Y} days ago - design may have changed`:`Synced ${Y} days ago`})}catch{o.push({name:`blocks/${w} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let i=Ne.join(t,"helix-query.yaml");if(Pt(i))try{let p=await Et(i,"utf-8");ps(p),o.push({name:"helix-query.yaml valid",status:"pass",message:"Valid YAML"})}catch{o.push({name:"helix-query.yaml valid",status:"fail",message:"Invalid YAML syntax"})}o.push({name:"~/.eds/config.json",status:wo()?"pass":"warn",message:wo()?"Found":'Missing - run "eds figma setup" to configure'});let a=o.filter(p=>p.status==="fail"),s=o.filter(p=>p.status==="warn");if(e.json){let p={pass:o.filter(u=>u.status==="pass").length,warn:s.length,fail:a.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:p},null,2)),a.length>0&&(process.exitCode=1);return}let d=I(o.map(p=>p.name));for(let p of o)r.info(A(p.status,p.name,p.message,d));let l=o.filter(p=>p.status==="fail"),c=o.filter(p=>p.status==="warn"),m=o.filter(p=>p.status==="pass");r.info(""),r.info(N([ge({pass:m.length,warn:c.length,fail:l.length})])),l.length>0&&(process.exitCode=1)}var Uo=k(()=>{"use strict";f();ye();R();z();M()});var Ho={};O(Ho,{auditLoading:()=>ym});import{existsSync as xe}from"fs";import{readFile as Qe,readdir as bm,stat as us}from"fs/promises";import $e from"path";import Bo from"chalk";async function ym(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(r.logoOnce(C("Loading Audit")),r.info(S("Loading Order Audit",t)));let n=[];if(await vm(t,n),await km(t,n),await xm(t,n),await $m(t,n),await Sm(t,n),await jm(t,n),e.json){let o={pass:n.filter(i=>i.status==="pass").length,warn:n.filter(i=>i.status==="warn").length,fail:n.filter(i=>i.status==="fail").length,info:n.filter(i=>i.status==="info").length};console.log(JSON.stringify({projectRoot:t,results:n,summary:o},null,2)),o.fail>0&&(process.exitCode=1);return}Em(n)}async function vm(e,t){let n=$e.join(e,"head.html");if(!xe(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1042
+ `);for(let l=0;l<i.length;l++){let c=i[l];/<script\b/i.test(c)&&!/type\s*=\s*["']module["']/i.test(c)&&!/<\/script>/.test(c)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:l+1})}let s=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(l=>!l.includes("styles/styles.css")&&!l.includes("styles.css"));s.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${s.length} extra stylesheet(s) \u2014 each competes with LCP budget`,file:"head.html"}),/<link[^>]+rel=["'](preload|preconnect)["']/i.test(o)&&t.push({rule:"No preload/preconnect in head.html",status:"warn",message:"preload/preconnect can hurt EDS LCP \u2014 resources compete with the 100KB budget",file:"head.html"}),/<script\b[^>]*>[\s\S]*?[^\s<][\s\S]*?<\/script>/i.test(o)&&t.push({rule:"No inline scripts in head.html",status:"warn",message:"Inline scripts block rendering \u2014 move to delayed.js",file:"head.html"});let d=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let l of o.matchAll(d)){let c=l[1];c.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${c} \u2014 move to delayed.js`,file:"head.html"})}/<link[^>]+as=["']font["']/i.test(o)&&t.push({rule:"No font preloads in head.html",status:"warn",message:"Font preloads consume LCP bandwidth budget \u2014 let loadFonts() handle them",file:"head.html"}),t.some(l=>l.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function km(e,t){let n=$e.join(e,"scripts","scripts.js");if(!xe(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await Qe(n,"utf-8"),i=o.split(`
1043
+ `),a=/function\s+loadEager|loadEager\s*=/i.test(o),s=/function\s+loadLazy|loadLazy\s*=/i.test(o),d=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:d?"pass":"warn",message:d?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let l=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(d&&l){let c=Number.parseInt(l[1],10);c<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${c}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${c}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(a){let c=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(c)&&t.push({rule:"loadEager loads only first section",status:"fail",message:"loadEager calls loadSections() \u2014 should only load first section for fast LCP",file:"scripts/scripts.js"})}for(let c=0;c<i.length;c++){let m=i[c];/import\s.*from\s+['"]https?:\/\//i.test(m)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${c+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:c+1})}if(a){let c=Pm(o,"loadEager");c&&/loadHeader|loadFooter/.test(c)&&t.push({rule:"Header/footer not in loadEager",status:"warn",message:"Header/footer in loadEager delays LCP \u2014 move to loadLazy",file:"scripts/scripts.js"})}}async function xm(e,t){let n=$e.join(e,"styles","styles.css");if(!xe(n))return;let i=(await us(n)).size/1024;t.push({rule:"styles.css size within LCP budget",status:i>40?"warn":"pass",message:`${i.toFixed(1)} KB${i>40?" \u2014 large CSS competes with 100KB LCP budget":""}`,file:"styles/styles.css"});let a=await Qe(n,"utf-8");/@import\s/.test(a)&&t.push({rule:"No @import in styles.css",status:"warn",message:"@import creates a request chain \u2014 inline the CSS or use lazy-styles.css",file:"styles/styles.css"})}async function $m(e,t){let n=$e.join(e,"scripts","delayed.js");if(!xe(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await Qe(n,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim()||t.push({rule:"delayed.js has content",status:"info",message:"delayed.js is empty \u2014 add analytics/martech here",file:"scripts/delayed.js"})}async function Sm(e,t){let n=$e.join(e,"blocks");if(!xe(n))return;let o=await bm(n,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=$e.join(n,a,`${a}.js`);if(!xe(s))continue;let d=await Qe(s,"utf-8"),l=d.split(`
1044
+ `),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let u=0;u<l.length;u++){let g=l[u].toLowerCase();for(let h of c)g.includes("from")&&g.includes(h)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${h}" \u2014 heavy library delays section loading`,file:`blocks/${a}/${a}.js`,line:u+1})}/document\.write/i.test(d)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${a}/${a}.js`});let p=(await us(s)).size/1024;p>20&&t.push({rule:"Block JS size reasonable",status:"warn",message:`${p.toFixed(1)} KB \u2014 consider splitting or lazy-loading parts`,file:`blocks/${a}/${a}.js`})}for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=$e.join(n,a,`${a}.css`);if(!xe(s))continue;let d=await Qe(s,"utf-8"),l=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let c of d.matchAll(l)){let m=c[1];["body","html","main"].includes(m)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${m}" \u2014 may leak styles and cause CLS. Use .${a} prefix`,file:`blocks/${a}/${a}.css`})}}}async function jm(e,t){let n=$e.join(e,"scripts","aem.js");if(!xe(n)){t.push({rule:"scripts/aem.js exists",status:"warn",message:"Missing aem.js (or lib-franklin.js) \u2014 the EDS framework library"});return}t.push({rule:"aem.js present",status:"pass",message:"Found \u2014 remember: never modify this file",file:"scripts/aem.js"})}function Pm(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let i=1,a=o.index+o[0].length,s=a;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,a++;return e.slice(s,a-1)}function Em(e){let t=new Map;for(let o of e){let i=o.file||"general",a=t.get(i)??[];a.push(o),t.set(i,a)}for(let[o,i]of t){r.info(` ${W.bullet} ${Bo.underline(o)}`);for(let a of i){let s=a.line?Bo.dim(`:${a.line}`):"";r.info(` ${Rt(a.status)} ${a.rule}${s}`),a.status!=="pass"&&r.info(Bo.dim(` ${a.message}`))}r.info("")}let n={pass:e.filter(o=>o.status==="pass").length,warn:e.filter(o=>o.status==="warn").length,fail:e.filter(o=>o.status==="fail").length,info:e.filter(o=>o.status==="info").length};r.info(N([ge(n)])),n.fail>0&&(process.exitCode=1)}var Go=k(()=>{"use strict";f();R();z();M()});var Wo={};O(Wo,{auditSecurity:()=>Nm});import{existsSync as dn}from"fs";import{readFile as Cm,readdir as Am}from"fs/promises";import Me from"path";import zo from"chalk";async function*gs(e){let t=await Am(e,{withFileTypes:!0});for(let n of t){let o=Me.join(e,n.name);if(n.isDirectory()){if(Fm.has(n.name))continue;yield*gs(o)}else n.isFile()&&(yield o)}}function Lm(e,t,n){let o=[],i=e.split(`
1045
+ `);for(let a=0;a<i.length;a++){let s=i[a],d=!1;for(let l of Tm)l.ext.includes(n)&&(l.id==="innerhtml-static"&&d||l.re.test(s)&&(l.extra&&!l.extra(s)||(l.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:l.severity,rule:l.id,message:l.message,file:t,line:a+1,snippet:s.trim().slice(0,100)}))))}return o}async function Om(e){if(!dn(Me.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(dn(Me.join(e,"package-lock.json"))||dn(Me.join(e,"npm-shrinkwrap.json")))&&!dn(Me.join(e,"node_modules")))return{status:"skipped",note:"no package-lock.json / node_modules \u2014 run npm install"};try{let{execa:n}=await import("execa"),{stdout:o}=await n("npm",["audit","--json"],{cwd:e,reject:!1}),a=JSON.parse(o)?.metadata?.vulnerabilities??{},s={critical:a.critical??0,high:a.high??0,moderate:a.moderate??0,low:a.low??0};return{status:s.critical+s.high+s.moderate+s.low>0?"vulnerable":"ok",counts:s}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function Nm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let l of gs(t)){let c=Me.extname(l).slice(1).toLowerCase();if(!Dm.has(c))continue;let m=Me.relative(t,l);if(m.endsWith("aem.js")||m.endsWith("lib-franklin.js"))continue;let p=await Cm(l,"utf-8");n.push(...Lm(p,m,c))}let o=await Om(t),i=l=>n.filter(c=>c.severity===l),a={critical:i("critical").length,high:i("high").length,moderate:i("moderate").length,low:i("low").length},s=a.critical>0||a.high>0||(o.counts?.critical??0)>0||(o.counts?.high??0)>0;if(e.json){console.log(JSON.stringify({projectRoot:t,dependencies:o,findings:n,summary:{code:a}},null,2)),s&&(process.exitCode=1);return}if(r.logoOnce(C("Security Audit")),r.info(S("Dependencies","npm audit")),o.status==="skipped")r.info(A("info","npm audit",o.note??"skipped"));else if(o.status==="ok")r.info(A("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};r.info(A(l.critical+l.high>0?"fail":"warn","npm audit",`${l.critical} critical, ${l.high} high, ${l.moderate} moderate, ${l.low} low \u2014 run \`npm audit fix\``))}if(r.info(S("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)r.info(A("pass","code","no risky patterns found"));else{let l=[...n].sort((c,m)=>fs.indexOf(c.severity)-fs.indexOf(m.severity));for(let c of l){let m=Rm[c.severity],p=zo.dim(`${c.file}:${c.line}`);r.info(` ${Rt(m.status)} ${zo.bold(m.label)} ${c.message} ${p}`),r.info(zo.dim(` ${c.snippet}`))}}let d=ge({fail:a.critical+a.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:a.moderate+(o.counts?.moderate??0),info:a.low+(o.counts?.low??0)});r.info(""),r.info(N([d||`${W.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var Tm,fs,Rm,Fm,Dm,Jo=k(()=>{"use strict";f();R();z();M();Tm=[{id:"eval",severity:"critical",re:/\beval\s*\(/,message:"eval() executes arbitrary code \u2014 prime XSS / RCE vector",ext:["js","mjs","html"]},{id:"aws-key",severity:"critical",re:/\bAKIA[0-9A-Z]{16}\b/,message:"Hardcoded AWS access key id",ext:["js","mjs","html","json"]},{id:"private-key",severity:"critical",re:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,message:"Embedded private key material",ext:["js","mjs","html","json","pem","txt"]},{id:"new-function",severity:"high",re:/\bnew\s+Function\s*\(/,message:"new Function() runs strings as code",ext:["js","mjs","html"]},{id:"document-write",severity:"high",re:/document\.write(?:ln)?\s*\(/,message:"document.write() enables XSS and blocks parsing",ext:["js","mjs","html"]},{id:"innerhtml-dynamic",severity:"high",re:/\.(?:inner|outer)HTML\s*=\s*[^;\n]*(?:\$\{|\+|concat)/,message:"Dynamic innerHTML assignment \u2014 sanitize or use textContent / DOM APIs",ext:["js","mjs"]},{id:"insert-adjacent-html",severity:"high",re:/insertAdjacentHTML\s*\(/,message:"insertAdjacentHTML with untrusted data is an XSS vector",ext:["js","mjs"]},{id:"js-url",severity:"high",re:/(?:href|src)\s*=\s*["']?\s*javascript:/i,message:"javascript: URL \u2014 XSS vector",ext:["js","mjs","html"]},{id:"secret",severity:"high",re:/(?:api[_-]?key|secret|access[_-]?token|auth[_-]?token|client[_-]?secret|passwd|password)\s*[:=]\s*["'][^"']{8,}["']/i,message:"Possible hardcoded secret / credential",ext:["js","mjs","html","json"],extra:e=>!/(example|placeholder|your[-_]|changeme|xxxx|<[^>]+>|\$\{)/i.test(e)},{id:"bearer-token",severity:"high",re:/Bearer\s+[A-Za-z0-9\-._~+/]{20,}/,message:"Hardcoded bearer token",ext:["js","mjs","html","json"]},{id:"innerhtml-static",severity:"moderate",re:/\.(?:inner|outer)HTML\s*=/,message:"innerHTML assignment \u2014 confirm the content is trusted / sanitized",ext:["js","mjs"]},{id:"insecure-url",severity:"moderate",re:/(?:href|src)\s*=\s*["']http:\/\/(?!localhost|127\.0\.0\.1)/i,message:"Insecure http:// resource \u2014 mixed content, use https://",ext:["html","js","mjs"]},{id:"target-blank",severity:"moderate",re:/target\s*=\s*["']_blank["']/,message:'target="_blank" without rel="noopener" \u2014 reverse tabnabbing',ext:["html","js","mjs"],extra:e=>!/rel\s*=\s*["'][^"']*noopener/i.test(e)},{id:"postmessage-wildcard",severity:"moderate",re:/postMessage\s*\([^,]+,\s*["']\*["']\s*\)/,message:"postMessage to '*' origin \u2014 restrict the target origin",ext:["js","mjs"]},{id:"inline-handler",severity:"low",re:/\son[a-z]+\s*=\s*["']/i,message:"Inline event handler \u2014 move to addEventListener (CSP-unfriendly)",ext:["html"]},{id:"console-log",severity:"low",re:/console\.(?:log|debug)\s*\(/,message:"console.log / debug left in code \u2014 potential info leak",ext:["js","mjs"]}],fs=["critical","high","moderate","low"],Rm={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Fm=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Dm=new Set(["js","mjs","html","json","pem","txt"])});async function hs(e,t,n){let o=t.ref||"main",i=n.startsWith("/")?n:`/${n}`,a=`${Mm}/${e}/${t.org}/${t.site}/${o}${i}`;r.debug(`POST ${a}`);let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await s.json().catch(()=>({})),l=d;return s.ok?{ok:!0,status:s.status,path:i,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:i,message:d.message||`HTTP ${s.status}`}}async function qo(e,t){return hs("preview",e,t)}async function Ko(e,t){return hs("live",e,t)}async function ws(e,t){return Promise.all(t.map(n=>qo(e,n)))}async function bs(e,t){return Promise.all(t.map(n=>Ko(e,n)))}var Mm,Xo=k(()=>{"use strict";f();R();Mm="https://admin.hlx.page"});var Vo={};O(Vo,{preview:()=>_m,resolveAdminConfig:()=>mn});import ys from"chalk";import Im from"ora";async function _m(e,t){let n=P(),o=await le(n),i=mn(o,t);if(!i)return;let a=Im(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await qo(i,e[0])]:await ws(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${ys.cyan(l.previewUrl||"preview updated")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function mn(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,i=t.ref||e.admin?.ref||"main";if(!n||!o){r.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),r.info(ys.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:i}}var pn=k(()=>{"use strict";f();Xo();ye();R();z()});var Yo={};O(Yo,{publish:()=>Hm});import Um from"chalk";import Bm from"ora";async function Hm(e,t){let n=P(),o=await le(n),i=mn(o,t);if(!i)return;let a=Bm(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await Ko(i,e[0])]:await bs(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${Um.cyan(l.liveUrl||"published")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Qo=k(()=>{"use strict";f();Xo();ye();R();z();pn()});var un={};O(un,{adminWizard:()=>Gm});async function Gm(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),s=(await le(t)).admin??{},d=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),l=(await o({message:"GitHub org / owner",default:s.org})).trim(),c=(await o({message:"Repository / site",default:s.site})).trim(),m=(await o({message:"Git ref",default:s.ref||"main"})).trim(),u=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||u.length===0){r.error("org, site and at least one path are required."),process.exitCode=1;return}r.info(S("Summary"));let g=I(["operation","org","site","ref","paths"]);if(r.info(j("operation",d,g)),r.info(j("org",l,g)),r.info(j("site",c,g)),r.info(j("ref",m,g)),r.info(j("paths",u.join(", "),g)),r.info(""),d==="publish"&&!await i({message:`Publish ${u.length} path(s) to LIVE?`,default:!1})){r.info("Cancelled.");return}let h={org:l,site:c,ref:m};if(d==="preview"){let{preview:b}=await Promise.resolve().then(()=>(pn(),Vo));await b(u,h)}else{let{publish:b}=await Promise.resolve().then(()=>(Qo(),Yo));await b(u,h)}}var fn=k(()=>{"use strict";f();ye();R();z();M()});var vs={};O(vs,{mainMenu:()=>qm});import{existsSync as zm}from"fs";import{readdir as Wm}from"fs/promises";import Jm from"path";async function Zo(e){let t=Jm.join(e,"blocks");return zm(t)?(await Wm(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function qm(){let{select:e,input:t}=await Promise.resolve().then(()=>(G(),H));switch(await r.logoOnceAnimated(""),await e({message:"Choose an action",choices:[{name:"Set up project",value:"init",description:"Authoring model, CI, naming"},{name:"Page template",value:"template",description:"Generate initial content"},{name:"Sandbox repo",value:"sandbox",description:"Disposable GitHub repo"},{name:"Block from design",value:"from-design",description:"Figma, Framer or Google Stitch"},{name:"Migrate component",value:"migrate",description:"Classic AEM component \u2192 EDS"},{name:"Scaffold UE",value:"scaffold",description:"Universal Editor components"},{name:"Empty block",value:"create",description:"Create a bare block"},{name:"Integration",value:"integrate",description:"GTM, chat, consent\u2026"},{name:"Model fields",value:"model",description:"Add fields to a block model (partials)"},{name:"Analytics",value:"track",description:"Instrument a block (dataLayer)"},{name:"Structured data",value:"schema",description:"Add JSON-LD to a block"},{name:"Universal Editor",value:"ue",description:"Check readiness / open the editor"},{name:"Preview block",value:"preview-block",description:"Live preview in the browser"},{name:"Pages",value:"admin",description:"Preview / publish (Admin API)"},{name:"Audit",value:"audit",description:"Doctor / loading / security"},{name:"Figma MCP",value:"figma-setup",description:"Configure the connection"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(qt(),Jt));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:i}=await Promise.resolve().then(()=>(_n(),In));await i(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:a=>/^[a-z0-9][a-z0-9._-]*$/i.test(a.trim())||"Use a valid repo name"}),{sandboxNew:i}=await Promise.resolve().then(()=>(Re(),Te));await i(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(Co(),Eo));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(Wn(),zn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(ce(),me));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>Pe.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:i}=await Promise.resolve().then(()=>(ao(),ro));await i(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(No(),Oo));await o(void 0);return}case"preview-block":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(Oe(),xt));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(eo(),Zn));await o(void 0,[],{});return}case"track":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:i.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(ut(),pt));await s(a,{});return}case"schema":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(no(),to));await s(a,{});return}case"ue":{if(await e({message:"Universal Editor:",choices:[{name:"Check readiness (which blocks are editable)",value:"check"},{name:"Open a page in the editor",value:"open"}]})==="check"){let{ueCheck:i}=await Promise.resolve().then(()=>(wt(),ht));await i()}else{let i=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(wt(),ht));await a(i.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o();return}case"audit":{let o=await e({message:"Which audit?",choices:[{name:"Doctor \u2014 overall project health",value:"doctor"},{name:"Loading \u2014 three-phase / LCP budget",value:"loading"},{name:"Security \u2014 vulnerabilities & exploit patterns",value:"security"}]});if(o==="doctor"){let{doctor:i}=await Promise.resolve().then(()=>(Uo(),_o));await i({})}else if(o==="loading"){let{auditLoading:i}=await Promise.resolve().then(()=>(Go(),Ho));await i({})}else{let{auditSecurity:i}=await Promise.resolve().then(()=>(Jo(),Wo));await i({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(Io(),Mo));await o();return}}}var ks=k(()=>{"use strict";f();R();z();Be()});f();import Km from"chalk";import{Command as Xm}from"commander";var ti={name:"aem-eds-kit",version:"0.4.33",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","samples","CHANGELOG.md"],scripts:{dev:"tsx src/bin/eds.ts",build:"tsup",test:"vitest run","test:watch":"vitest",lint:"biome check src/ tests/","lint:fix":"biome check --write src/ tests/",typecheck:"tsc --noEmit",prepare:"git config core.hooksPath .githooks || true",prepublishOnly:"npm run build"},keywords:["aem","edge-delivery-services","helix","figma","mcp","cli","adobe"],author:"Piotr Godycki <piotrgodycki@yahoo.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/piotrgodycki/aem-eds-kit.git"},homepage:"https://piotrgodycki.github.io/aem-eds-kit/",bugs:{url:"https://github.com/piotrgodycki/aem-eds-kit/issues"},dependencies:{"@inquirer/prompts":"^7.0.0",chalk:"^5.4.0",commander:"^13.0.0",execa:"^9.5.0","fast-xml-parser":"^5.11.2",ora:"^8.1.0",yaml:"^2.6.0",zod:"^3.24.0"},devDependencies:{"@biomejs/biome":"^1.9.0","@types/node":"^22.0.0",tsup:"^8.3.0",tsx:"^4.19.0",typescript:"^5.7.0",vitest:"^2.1.0"},optionalDependencies:{"@modelcontextprotocol/sdk":"^1.29.0",pixelmatch:"^6.0.0",playwright:"^1.64.0",pngjs:"^7.0.0"}};R();M();var _=new Xm;_.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(ti.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-error output").option("--json","Output in JSON format").option("--no-color","Disable color output").showHelpAfterError("(add --help for usage)").hook("preAction",e=>{let t=e.opts();t.verbose&&r.setLevel("debug"),t.quiet&&r.setQuiet(!0),t.color===!1&&(Km.level=0)});_.addHelpText("beforeAll",()=>C());var Ct=_.command("sandbox").description("Disposable EDS sandbox repos on GitHub");Ct.command("new <name>").description("Create a disposable EDS repo from a boilerplate (GitHub auth, no gh required)").option("--org <org>","Create under a GitHub org (else your account)").option("--boilerplate <repo>","Template repo (default adobe/aem-boilerplate)").option("--ue","Use the crosswalk / Universal Editor boilerplate").option("--private","Create a private repo").option("--yes","Skip the guided prompts (use flags/defaults)").action(async(e,t)=>{let{sandboxNew:n}=await Promise.resolve().then(()=>(Re(),Te));await n(e,t)});Ct.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("rm <name>").description("Delete a sandbox repo (destructive)").option("--org <org>","Owner org (else your account)").option("--yes","Skip the confirmation").action(async(e,t)=>{let{sandboxRm:n}=await Promise.resolve().then(()=>(Re(),Te));await n(e,t)});var Vm=_.command("template").description("Generate page templates / initial content");Vm.command("new <name>").description("Generate EDS page initial content (sections + blocks + metadata), DA push optional").option("--path <path>","Content path (default: /templates/<name>)").option("--title <title>","Page title").option("--description <text>","Page description").option("--blocks <list>","Comma-separated block ids to seed",e=>e.split(",").map(t=>t.trim())).option("--area <area>","Site area / template label (stored in metadata)").option("--authoring <model>","Force authoring model: da | gdrive | sharepoint | ue").option("--push","Push the page to DA (da.live)").option("--org <org>","DA org (else from .edsrc.json)").option("--site <site>","DA site (else from .edsrc.json)").option("--yes","Skip prompts").action(async(e,t)=>{let{templateNew:n}=await Promise.resolve().then(()=>(_n(),In));await n(e,t)});_.command("init").description("Set up a freshly cloned EDS boilerplate for your authoring model (interactive)").option("--name <name>","Project name (kebab-case)").option("--authoring <model>","Authoring model: ue | da | gdrive | sharepoint").option("--mountpoint <url>","Content source URL (document models)").option("--org <org>","DA org (authoring=da)").option("--site <site>","DA site (authoring=da)").option("--no-ci","Skip the GitHub Actions CI workflow").option("--no-env","Skip the local-dev .env (aem up config)").option("--no-xwalk","Skip xwalk.json (UE multi-field)").option("--yes","Skip prompts; apply with flags/defaults").action(async e=>{let{initProject:t}=await Promise.resolve().then(()=>(qt(),Jt));await t(e)});var Ym=_.command("migrate").description("Migrate from classic AEM to EDS");Ym.command("component [dir]").description("Migrate a classic AEM component's dialog into an EDS block + UE model").option("--name <name>","Block name (otherwise inferred from the component)").option("--clientlib <dir>","Path to the component's clientlib (otherwise auto-detected)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(Wn(),zn));await n(e,t)});var Qm=_.command("model").description("Compose Universal Editor models");Qm.command("add <block> [partials...]").description("Add reusable field groups (partials) to a block's UE model").option("--yes","Skip prompts").action(async(e,t,n)=>{let{modelAdd:o}=await Promise.resolve().then(()=>(eo(),Zn));await o(e,t,n)});var Zm=_.command("schema").description("Structured data (JSON-LD) for blocks");Zm.command("block <name>").description("Inject a JSON-LD (schema.org) builder into a block's decorate()").option("--type <type>","schema.org type (Article, FAQPage, Product, ...)").option("--yes","Skip prompts").action(async(e,t)=>{let{schemaBlock:n}=await Promise.resolve().then(()=>(no(),to));await n(e,t)});var ep=_.command("track").description("Instrument blocks for analytics");ep.command("block <name>").description("Add dataLayer tracking (click + form submit) to a block's decorate()").option("--no-click","Skip click tracking").option("--no-submit","Skip form-submit tracking").action(async(e,t)=>{let{trackBlock:n}=await Promise.resolve().then(()=>(ut(),pt));await n(e,t)});var xs=_.command("ue").description("Universal Editor - readiness check + editor deep link");xs.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(wt(),ht));await e()});xs.command("open [path]").description("Open a page in the hosted Universal Editor (preview host from git)").option("--org <slug>","IMS org slug (skips the org picker)").option("--ref <branch>","Branch/ref for the preview host (default: main)").option("--url <host>","Override the delivery host (e.g. main--repo--owner.aem.page)").option("--no-open","Print the link without opening the browser").action(async(e,t)=>{let{ueOpen:n}=await Promise.resolve().then(()=>(wt(),ht));await n(e,t)});var Ze=_.command("block").description("Manage EDS blocks");Ze.command("create <name>").description("Scaffold a new EDS block (with Universal Editor model by default)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").action(async(e,t)=>{let{createBlock:n}=await Promise.resolve().then(()=>(ao(),ro));await n(e,t)});Ze.command("from-design [design]").description("Generate an EDS block from a design: a Figma URL, a Framer/Stitch page (scraped with headless Chromium), or a local SVG/PNG export (quota-free, no MCP). Interactive wizard when run with no argument.").option("--name <name>","Override the inferred block name").option("--provider <type>","Design source: figma | framer | stitch (else detected from the URL)").option("--agent <type>","Force agent type (claude|cursor|codex|none)").option("--dry-run","Generate prompt only, do not invoke agent").option("--source <type>","Content source: document|ue|cf|mixed (default: document)").option("--widths <list>","Design frame widths for preview breakpoints (e.g. 390,768,1440)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").option("--screenshot","Add a screenshot MCP call for pixel verification (opt-in; costs a call)").option("--mcp","Force the Figma MCP adapter even when a REST token is set").option("--refresh","Ignore the cached design snapshot and re-fetch").option("--auth","Scrape with a logged-in session (Framer/Stitch) \u2014 login captured once, then reused").option("--auth-refresh","Force a fresh scrape login even if a session is saved").option("--sample","Use the bundled sample design (Kiri Bloom hero) \u2014 no URL, no token, no MCP").option("--serve","Auto-start the live preview after generating (non-interactive runs only)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(Co(),Eo));await n(e,t)});Ze.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(za(),Ga));await t({...e,json:_.opts().json})});Ze.command("preview [name]").description("Serve a live, breakpoint-switchable preview of a block \u2014 or a gallery of all blocks when no name is given").option("--port <port>","Port to serve on (default: 8777, falls back if taken)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--no-open","Do not open the browser automatically").action(async(e,t)=>{let n=await Promise.resolve().then(()=>(Oe(),xt));e?await n.previewBlock(e,t):await n.galleryPreview(t)});Ze.command("test [name]").description("Visual-regression test a block (or all blocks) against committed baselines").option("--update","(Re)write the baseline screenshots instead of comparing").option("--threshold <ratio>","Max changed-pixel ratio before failing (default 0.01 = 1%)").option("--design","Compare the rendered block against its Figma design image (needs a token)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--port <port>","Port for the internal preview server (default: 8788)").action(async(e,t)=>{let{visualTest:n}=await Promise.resolve().then(()=>(ns(),ts));await n(e,t)});Ze.command("check [name]").description("Content, link and a11y check on a block's rendered DOM (or all blocks)").option("--strict","Fail on warnings too, not just errors").option("--widths <list>","Comma-separated breakpoint widths (uses the widest)").option("--port <port>","Port for the internal preview server (default: 8789)").action(async(e,t)=>{let{blockCheck:n}=await Promise.resolve().then(()=>(as(),rs));await n(e,t)});var et=_.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("blocks [names...]").description("Scaffold standard blocks (hero, cards, columns, accordion, embed) with UE models").action(async e=>{let{scaffoldBlocks:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("env").description("Write a local-dev .env for `aem up` (AEM_OPEN / AEM_PORT / AEM_PAGES_URL)").option("--open <path>","AEM_OPEN - path opened on start (default: /)").option("--port <port>","AEM_PORT - proxy port (default: 3007)").option("--pages-url <url>","AEM_PAGES_URL - content origin (default: from git remote)").option("--yes","Skip prompts; use flags/defaults").action(async e=>{let{scaffoldEnv:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(ce(),me));await e()});_.command("integrate [type]").description("Add a third-party service (GTM, GA4, chat, consent) to scripts/delayed.js").action(async e=>{let{integrate:t}=await Promise.resolve().then(()=>(No(),Oo));await t(e)});var tp=_.command("figma").description("Figma MCP integration");tp.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(Io(),Mo));await e()});_.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(Uo(),_o));await e({json:_.opts().json})});var $s=_.command("audit").description("Run project audits");$s.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(Go(),Ho));await e({json:_.opts().json})});$s.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Jo(),Wo));await e({json:_.opts().json})});_.command("preview [paths...]").description("Preview pages via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(pn(),Vo));await n(e,t)});_.command("publish [paths...]").description("Publish pages to live via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Qo(),Yo));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(ks(),vs));await e()}else _.outputHelp();else await _.parseAsync()}catch(e){r.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();