aem-eds-kit 0.4.25 → 0.4.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +113 -23
- package/dist/bin/eds.js +276 -145
- package/package.json +6 -2
- package/samples/hero.svg +35 -0
package/dist/bin/eds.js
CHANGED
|
@@ -1,20 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function
|
|
4
|
-
${
|
|
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
5
|
|
|
6
|
-
${
|
|
7
|
-
`}function
|
|
6
|
+
${xs(ks(),e)}
|
|
7
|
+
`}function S(e,t){let n=_.red("\u258A"),o=t?` ${D.dim(t)}`:"";return`
|
|
8
8
|
${n} ${D.bold(e)}${o}
|
|
9
|
-
`}function
|
|
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(`
|
|
10
10
|
`);return`${o}
|
|
11
|
-
${
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
|
|
15
|
-
`);let n=r=>r?L.accent("\u258C"):" ",o=14;for(let r=0;r<o;r++)t.write(`\r\x1B[K ${Ie(Ao(r),e)} ${n(r%2===0)}`),await new Promise(s=>setTimeout(s,70));for(let r=0;r<4;r++)t.write(`\r\x1B[K ${Ie(gt(),e)} ${n(r%2===0)}`),await new Promise(s=>setTimeout(s,200));t.write(`\r\x1B[K ${Ie(gt(),e)}
|
|
16
|
-
`)},success(...e){me("info")&&console.error(Be.green("\u2713"),...e)},warn(...e){me("warn")&&console.error(Be.yellow("\u26A0"),...e)},error(...e){me("error")&&console.error(Be.red("\u2717"),...e)}}});function Ee(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 vs(e){return`${$e}/repos/${e}/generate`}async function bt(e){let t=await fetch(`${$e}/user`,{headers:Ee(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function Do(e,t,n){let o=await fetch(`${$e}/repos/${t}/${n}`,{headers:Ee(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 Lo(e,t,n){let o=await fetch(vs(t),{method:"POST",headers:Ee(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 r=await o.json();return{fullName:r.full_name,htmlUrl:r.html_url,cloneUrl:r.clone_url}}async function Ro(e,t,n,o){await fetch(`${$e}/repos/${t}/${n}/topics`,{method:"PUT",headers:Ee(e),body:JSON.stringify({names:o})})}async function Oo(e,t,n){let o=await fetch(`${$e}/repos/${t}/${n}`,{method:"DELETE",headers:Ee(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function Mo(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),r=await fetch(`${$e}/search/repositories?q=${o}&per_page=100`,{headers:Ee(e)});if(!r.ok)throw new Error(`search failed: ${r.status}`);return(await r.json()).items.map(a=>a.full_name)}var $e,_o=b(()=>{"use strict";p();$e="https://api.github.com"});import{existsSync as No}from"fs";import{mkdir as ks,readFile as xs,rm as Ss,writeFile as js}from"fs/promises";import $s from"os";import Uo from"path";async function Bo(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(No(He))try{return JSON.parse(await xs(He,"utf-8")).token??null}catch{return null}return null}async function Qt(e){await ks(Io,{recursive:!0,mode:448}),await js(He,`${JSON.stringify({token:e},null,2)}
|
|
17
|
-
`,{mode:384})}async function Ho(){No(He)&&await Ss(He)}async function Go(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:wt,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function Jo(e,t,n){let o=Math.max(t,1),r=Date.now()+n*1e3;for(;Date.now()<r;){await new Promise(d=>setTimeout(d,o*1e3));let a=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:wt,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(a.access_token)return a.access_token;if(a.error==="slow_down")o+=5;else if(a.error!=="authorization_pending")throw new Error(a.error??"device flow failed")}throw new Error("device flow timed out")}var Io,He,wt,Wo=b(()=>{"use strict";p();Io=Uo.join($s.homedir(),".eds"),He=Uo.join(Io,"github.json"),wt=process.env.EDS_GITHUB_CLIENT_ID??""});function Zt(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function en(){return"https://github.com/apps/aem-code-sync/installations/new"}function zo(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Ce,Ge,qo=b(()=>{"use strict";p();Ce="eds-sandbox",Ge={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});import{z as T}from"zod";var Ed,tn,Ko,Cd,pe,Pe=b(()=>{"use strict";p();Ed=T.object({fileKey:T.string().min(1),nodeId:T.string().optional(),fileName:T.string().optional()}),tn=T.object({agent:T.enum(["claude","cursor","codex"]).optional(),figma:T.object({mcpEndpoint:T.string().url().optional(),token:T.string().optional()}).optional(),admin:T.object({org:T.string().optional(),site:T.string().optional(),ref:T.string().default("main")}).optional()}),Ko=T.object({root:T.string(),hasFstab:T.boolean(),hasBlocks:T.boolean(),hasHeadHtml:T.boolean()}),Cd=T.object({figmaFileKey:T.string(),figmaNodeId:T.string().optional(),lastSyncedAt:T.string().datetime(),promptVersion:T.string(),agentUsed:T.string().optional(),breakpoints:T.array(T.object({width:T.number(),label:T.string().optional(),source:T.enum(["figma","default"]).optional()})).optional()}),pe=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as Je}from"fs";import ie from"path";function E(e=process.cwd()){let t=ie.resolve(e),{root:n}=ie.parse(t);for(;t!==n;){if(Xo.some(o=>Je(ie.join(t,o))))return t;t=ie.dirname(t)}if(Xo.some(o=>Je(ie.join(n,o))))return n}function Vo(e){return Ko.parse({root:e,hasFstab:Je(ie.join(e,"fstab.yaml")),hasBlocks:Je(ie.join(e,"blocks")),hasHeadHtml:Je(ie.join(e,"head.html"))})}var Xo,H=b(()=>{"use strict";p();Pe();Xo=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Es}from"fs";import{mkdir as Cs,writeFile as Ps}from"fs/promises";import Yo from"path";async function yt(e){let t=Yo.join(e,".github","workflows","eds.yml");return Es(t)?{path:Qo,created:!1}:(await Cs(Yo.dirname(t),{recursive:!0}),await Ps(t,As),{path:Qo,created:!0})}var Qo,As,nn=b(()=>{"use strict";p();Qo=".github/workflows/eds.yml",As=`name: EDS checks
|
|
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
|
|
18
14
|
|
|
19
15
|
# Generated by aem-eds-kit (\`eds scaffold ci\`). Runs the project's own
|
|
20
16
|
# lint/build plus the eds audits as a gatekeeper on every PR and push to main.
|
|
@@ -57,18 +53,18 @@ jobs:
|
|
|
57
53
|
run: npx --yes aem-eds-kit@latest audit loading
|
|
58
54
|
- name: Security & exploit scan
|
|
59
55
|
run: npx --yes aem-eds-kit@latest audit security
|
|
60
|
-
`});import{existsSync as
|
|
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}
|
|
61
57
|
AEM_PORT=${n}
|
|
62
58
|
AEM_PAGES_URL=${o}
|
|
63
|
-
`}async function
|
|
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(`
|
|
64
60
|
`)?`
|
|
65
|
-
`:"";return await
|
|
66
|
-
`),!0}async function
|
|
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:
|
|
67
63
|
/: ${e}
|
|
68
|
-
`}async function
|
|
69
|
-
`}async function
|
|
70
|
-
`}async function
|
|
71
|
-
`}function
|
|
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
|
|
72
68
|
export default function decorate(block) {
|
|
73
69
|
block.classList.add('hero');
|
|
74
70
|
const picture = block.querySelector('picture');
|
|
@@ -97,7 +93,7 @@ export default function decorate(block) {
|
|
|
97
93
|
margin: 0 auto;
|
|
98
94
|
padding: 0 var(--spacing-m, 16px);
|
|
99
95
|
}
|
|
100
|
-
`,model:
|
|
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
|
|
101
97
|
export default function decorate(block) {
|
|
102
98
|
const ul = document.createElement('ul');
|
|
103
99
|
[...block.children].forEach((row) => {
|
|
@@ -136,7 +132,7 @@ export default function decorate(block) {
|
|
|
136
132
|
.cards .cards-card-body {
|
|
137
133
|
padding: var(--spacing-m, 16px);
|
|
138
134
|
}
|
|
139
|
-
`,model:
|
|
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
|
|
140
136
|
export default function decorate(block) {
|
|
141
137
|
const cols = [...block.firstElementChild.children];
|
|
142
138
|
block.classList.add(\`columns-\${cols.length}-cols\`);
|
|
@@ -163,7 +159,7 @@ export default function decorate(block) {
|
|
|
163
159
|
}
|
|
164
160
|
|
|
165
161
|
.columns img { width: 100%; height: auto; }
|
|
166
|
-
`,model:
|
|
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
|
|
167
163
|
export default function decorate(block) {
|
|
168
164
|
[...block.children].forEach((row) => {
|
|
169
165
|
const [label, body] = row.children;
|
|
@@ -196,7 +192,7 @@ export default function decorate(block) {
|
|
|
196
192
|
.accordion .accordion-item-body {
|
|
197
193
|
padding-bottom: var(--spacing-m, 16px);
|
|
198
194
|
}
|
|
199
|
-
`,model:
|
|
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
|
|
200
196
|
export default function decorate(block) {
|
|
201
197
|
const link = block.querySelector('a');
|
|
202
198
|
const url = link?.href;
|
|
@@ -225,12 +221,12 @@ export default function decorate(block) {
|
|
|
225
221
|
height: 100%;
|
|
226
222
|
border: 0;
|
|
227
223
|
}
|
|
228
|
-
`,model:
|
|
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\`).
|
|
229
225
|
|
|
230
|
-
${
|
|
226
|
+
${Ui(e).map(o=>_i(o)).filter(o=>!!o).map(o=>o.code).join(`
|
|
231
227
|
|
|
232
228
|
`)}
|
|
233
|
-
`}async function
|
|
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:`/**
|
|
234
230
|
* Reads a page metadata value by name (meta[name] or meta[property]).
|
|
235
231
|
* @param {string} name The metadata name.
|
|
236
232
|
* @returns {string} The value, or an empty string.
|
|
@@ -327,8 +323,8 @@ export function isUEPreview() {
|
|
|
327
323
|
*/
|
|
328
324
|
export function isUE() {
|
|
329
325
|
return isUEEdit() || isUEPreview();
|
|
330
|
-
}`}],
|
|
331
|
-
`}function
|
|
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
|
|
332
328
|
// A living reference of every Universal Editor field type (see _field-reference.json).
|
|
333
329
|
// Authors use it to see what's available; delete it before launch.
|
|
334
330
|
export default function decorate(block) {
|
|
@@ -337,44 +333,44 @@ export default function decorate(block) {
|
|
|
337
333
|
// are what you drop and edit.
|
|
338
334
|
block.classList.add('field-reference');
|
|
339
335
|
}
|
|
340
|
-
`,
|
|
336
|
+
`,Ji=`/* Block: field-reference */
|
|
341
337
|
.field-reference {
|
|
342
338
|
display: grid;
|
|
343
339
|
gap: var(--spacing-m, 16px);
|
|
344
340
|
padding: var(--spacing-l, 32px) 0;
|
|
345
341
|
}
|
|
346
|
-
`});var
|
|
347
|
-
`)}async function
|
|
348
|
-
`),!0}catch{return!1}}async function
|
|
349
|
-
`).filter(Boolean):[]}}catch(o){
|
|
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}">
|
|
350
346
|
<div>
|
|
351
347
|
<div>${e} content</div>
|
|
352
348
|
</div>
|
|
353
|
-
</div>`}function
|
|
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">
|
|
354
350
|
${t.join(`
|
|
355
351
|
`)}
|
|
356
|
-
</div>`}function
|
|
352
|
+
</div>`}function sr(e){let t=e.blocks??[],n=` <div>
|
|
357
353
|
<h1>${e.title}</h1>
|
|
358
354
|
<p>${e.description??"Intro copy goes here."}</p>
|
|
359
|
-
</div>`,o=t.map(
|
|
360
|
-
${
|
|
361
|
-
</div>`),
|
|
362
|
-
${
|
|
355
|
+
</div>`,o=t.map(a=>` <div>
|
|
356
|
+
${Cc(a)}
|
|
357
|
+
</div>`),i=` <div>
|
|
358
|
+
${Ac(e)}
|
|
363
359
|
</div>`;return`<body>
|
|
364
360
|
<header></header>
|
|
365
361
|
<main>
|
|
366
|
-
${[n,...o,
|
|
362
|
+
${[n,...o,i].join(`
|
|
367
363
|
`)}
|
|
368
364
|
</main>
|
|
369
365
|
<footer></footer>
|
|
370
366
|
</body>
|
|
371
|
-
`}var
|
|
372
|
-
`}var
|
|
373
|
-
`),!0}async function
|
|
374
|
-
`).map(
|
|
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(`
|
|
375
371
|
|
|
376
|
-
`),files:o.map(
|
|
377
|
-
`}function
|
|
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.
|
|
378
374
|
// Each child row is one repeated item - enhance them here.
|
|
379
375
|
[...block.children].forEach((row) => {
|
|
380
376
|
row.classList.add('${e}-item');
|
|
@@ -386,25 +382,25 @@ export default function decorate(block) {
|
|
|
386
382
|
block.classList.add('${e}');
|
|
387
383
|
${o}
|
|
388
384
|
}
|
|
389
|
-
`}function
|
|
385
|
+
`}function jr(e){return`/* Block: ${e} */
|
|
390
386
|
/* Migrated from a classic AEM component. Bring the component's styles here */
|
|
391
387
|
/* (from its clientlib or the rendered page) and keep them scoped to the block. */
|
|
392
388
|
.${e} {
|
|
393
389
|
}
|
|
394
|
-
`}var
|
|
395
|
-
`)}function
|
|
396
|
-
${
|
|
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}
|
|
397
393
|
|
|
398
|
-
${
|
|
399
|
-
${
|
|
400
|
-
${
|
|
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)}
|
|
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} */
|
|
401
397
|
/* Migrated from the component clientlib: ${n.join(", ")}. */
|
|
402
398
|
/* TODO: review selectors and scope them under .${e} (and port any LESS/SCSS). */
|
|
403
399
|
|
|
404
400
|
${t.trim()}
|
|
405
|
-
`}function
|
|
406
|
-
`),
|
|
407
|
-
// --- ${
|
|
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}) ---
|
|
408
404
|
{
|
|
409
405
|
const root = ${o};
|
|
410
406
|
const ld = ${t.object};
|
|
@@ -413,7 +409,7 @@ ${t.trim()}
|
|
|
413
409
|
ldScript.textContent = JSON.stringify(ld);
|
|
414
410
|
document.head.append(ldScript);
|
|
415
411
|
}
|
|
416
|
-
`;return{js:`${e.slice(0,
|
|
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:`{
|
|
417
413
|
'@context': 'https://schema.org',
|
|
418
414
|
'@type': 'Article',
|
|
419
415
|
headline: root.querySelector('h1, h2, h3')?.textContent?.trim() || document.title,
|
|
@@ -492,54 +488,58 @@ ${t.trim()}
|
|
|
492
488
|
position: i + 1,
|
|
493
489
|
text: li.textContent?.trim(),
|
|
494
490
|
})),
|
|
495
|
-
}`}]});var
|
|
496
|
-
`}async function
|
|
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) {
|
|
497
493
|
// TODO: implement ${e} block
|
|
498
494
|
}
|
|
499
|
-
`,
|
|
495
|
+
`,a=`.${e} {
|
|
500
496
|
/* TODO: style ${e} block */
|
|
501
497
|
}
|
|
502
|
-
`;await
|
|
503
|
-
`)[0].slice(0,100)
|
|
504
|
-
`)[0].slice(0,70):"";return K.dim(`$ ${r}`)}default:return`${L.blue("\u2192")} ${e}`}}var Pr=b(()=>{"use strict";p();F();I()});import{existsSync as Pc}from"fs";import{readFile as Ac}from"fs/promises";import{homedir as Tc}from"os";import Kn from"path";async function Ar(e){try{let t=await Ac(e,"utf-8");return JSON.parse(t)}catch{return}}async function ae(e){let t=await Ar(Xn),n=e?await Ar(Kn.join(e,Fc)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},r=tn.safeParse(o);return r.success?r.data:(i.debug("Config validation issues:",r.error.flatten()),tn.parse({}))}function Fr(){return Tr}function Vn(){return Xn}function Yn(){return Pc(Xn)}var Tr,Xn,Fc,ve=b(()=>{"use strict";p();F();Pe();Tr=Kn.join(Tc(),".eds"),Xn=Kn.join(Tr,"config.json"),Fc=".edsrc.json"});function Dr(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Dc(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:Dr(n),source:t})):[]}function Lr(e,t){let n=Dc(e,"figma");return n.length?n:Lc(t)}function Lc(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let r=Number(o?.width);if(!Number.isFinite(r)||r<=0||t.has(r))continue;t.add(r);let s=o.source;n.push({width:r,label:Dr(r),source:s==="figma"?"figma":"default"})}return n}var Rr=b(()=>{"use strict";p()});function Nt(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],r,s;n[2]==="branch"&&n[3]?(r=n[3],s=n[4]?decodeURIComponent(n[4]):void 0):(r=n[1],s=n[2]?decodeURIComponent(n[2]):void 0);let a=t.searchParams.get("node-id"),d=a?Rc(a):void 0;return{fileKey:r,nodeId:d,fileName:s}}function Rc(e){return decodeURIComponent(e).replace(/-/g,":")}var Or=b(()=>{"use strict";p()});import{existsSync as Oc}from"fs";import{readFile as Mc}from"fs/promises";import _c from"path";function Nc(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",r="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
|
|
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"?`
|
|
505
501
|
## Content source: Content Fragment
|
|
506
502
|
This block renders an AEM **Content Fragment**${o} - not inline-authored copy.
|
|
507
503
|
- UE model: use an \`aem-content-fragment\` field (e.g. \`name: "fragment"\`) for the CF reference.
|
|
508
|
-
- \`decorate(block)\` must be **async**: read the CF reference from the authored DOM (a link to \`/content/dam/...\`), fetch its fields through an AEM GraphQL **persisted query** (${
|
|
504
|
+
- \`decorate(block)\` must be **async**: read the CF reference from the authored DOM (a link to \`/content/dam/...\`), fetch its fields through an AEM GraphQL **persisted query** (${i}), then build the DOM from the returned fields.
|
|
509
505
|
- Handle loading / empty / error states. Do not hardcode copy that the CF owns.
|
|
510
506
|
- \`.${n}\` styling still follows the EDS conventions below.
|
|
511
507
|
`:`
|
|
512
508
|
## Content source: Mixed (Universal Editor + Content Fragment)
|
|
513
509
|
This block mixes **two sources in one model and one \`decorate(block)\`**:
|
|
514
510
|
- **Inline (UE-authored)** parts \u2192 normal fields (text / richtext / image / select) read straight from the authored DOM cells, with semantic collapsing.
|
|
515
|
-
- **Content Fragment** part${o} \u2192 an \`aem-content-fragment\` field; \`decorate()\` is **async** and also fetches that CF via a GraphQL persisted query (${
|
|
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.
|
|
516
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.
|
|
517
|
-
`}async function
|
|
518
|
-
|
|
519
|
-
1.
|
|
520
|
-
2.
|
|
521
|
-
3.
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
${
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
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)
|
|
514
|
+
Do **exactly one** self-check \u2014 do **not** loop:
|
|
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
|
+
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)
|
|
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
|
+
|
|
520
|
+
\`\`\`json
|
|
521
|
+
${s.spec}
|
|
522
|
+
\`\`\`
|
|
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)
|
|
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
|
+
|
|
527
|
+
\`\`\`json
|
|
528
|
+
${s.spec}
|
|
529
|
+
\`\`\`
|
|
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)
|
|
532
|
+
Read \`${s.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
|
|
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)
|
|
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
|
+
**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
|
+
|
|
538
|
+
${p}`:i==="figma"?m=`## Step 1 \u2014 Fetch the Design (single MCP call)
|
|
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
|
+
|
|
541
|
+
${p}`:m=`## Step 1 \u2014 Read the Design
|
|
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.
|
|
545
545
|
|
|
@@ -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
|
-
${
|
|
617
|
+
${ze.map(y=>`- \`${y.id}\` \u2014 ${y.label}`).join(`
|
|
618
618
|
`)}
|
|
619
|
-
`:""
|
|
619
|
+
`:"",g=s?.mode==="file"?"a design export":a,w=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 ${
|
|
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.
|
|
623
623
|
|
|
624
|
-
${
|
|
624
|
+
${m}
|
|
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:
|
|
@@ -662,20 +662,21 @@ export default function decorate(block) {
|
|
|
662
662
|
/* Map Figma design tokens to CSS custom properties; reuse project tokens below where they match */
|
|
663
663
|
/* Mobile-first; exact values from Step 2 */
|
|
664
664
|
\`\`\`
|
|
665
|
-
${
|
|
665
|
+
${u}${n}
|
|
666
666
|
## Placeholders & assets \u2014 be visible before Universal Editor takes over
|
|
667
|
-
Content images and copy come from **authoring** (the document / DAM via UE), not the repo. Do **not** ship design-tool CDN URLs (Figma
|
|
667
|
+
Content images and copy come from **authoring** (the document / DAM via UE), not the repo. Do **not** ship design-tool / scraped CDN URLs (Figma, Framer and Stitch asset links are short-lived) and do **not** bundle content photos into the repo.
|
|
668
668
|
- In \`decorate()\`, read the image/text from the authored DOM. When none is present yet, render a lightweight **placeholder** so the block is visible *before* an author sets the real content: an inline SVG data-URI grey box (or a CSS placeholder) at the correct \`aspect-ratio\`, and sensible placeholder copy.
|
|
669
|
-
- Provide the mock for the preview in \`blocks/${e.blockName}/_${e.blockName}.preview.html\` (used by \`eds block preview\`). Keep placeholder copy there, not hardcoded in the block.
|
|
669
|
+
- Provide the mock for the preview in \`blocks/${e.blockName}/_${e.blockName}.preview.html\` (used by \`eds block preview\`). Keep placeholder copy there, not hardcoded in the block. **This file must be a bare block fragment only** \u2014 just the authored \`<div class="${e.blockName} block">\u2026</div>\` markup that \`decorate()\` consumes. Do **not** wrap it in \`<!DOCTYPE>\`, \`<html>\`, \`<head>\`, \`<body>\`, \`<link>\`, \`<style>\` or \`<script>\`; the preview harness supplies the page, the block CSS and the \`decorate()\` call itself. A full HTML document here renders as a blank preview.
|
|
670
670
|
- Only bundle genuinely **static, decorative** assets (e.g. a small icon) as an optimized inline/\`icons/\` **SVG**, referenced by project-relative path. Never bundle authorable content images.
|
|
671
671
|
- Always set \`width\`/\`height\` or \`aspect-ratio\` to avoid CLS.
|
|
672
672
|
|
|
673
|
-
${
|
|
673
|
+
${c}
|
|
674
674
|
|
|
675
675
|
## EDS Block Conventions
|
|
676
676
|
- **Full-width by default**: the block/section spans the **full viewport width** (full-bleed) \u2014 never a fixed or centered fixed-width box. Constrain only the *inner content* to a sensible \`max-width\` (centered) for line-length/readability, with fluid horizontal padding. The design frame's width (e.g. 1280px) is the content cap, not the section width.
|
|
677
677
|
- **Mobile-first & fluid**: base styles target the smallest screen; layer breakpoints upward. The section must look right at any width, not only the design frame's.
|
|
678
678
|
- **No frameworks**: vanilla JS and CSS only
|
|
679
|
+
- **Self-contained JS**: the block's \`.js\` must run on its own. Do **not** \`import\` from \`scripts/\` or other blocks (no analytics/tracking/aem helpers) \u2014 a missing module makes the whole block fail to load and renders blank. No analytics/tracking code unless explicitly requested.
|
|
679
680
|
- **\`decorate(block)\`**: enhance the authored DOM; never inject hardcoded copy that should be authored
|
|
680
681
|
- **Semantic HTML**: correct elements and heading hierarchy
|
|
681
682
|
- **Class naming**: prefix all classes with the block name: \`.${e.blockName}-item\`, \`.${e.blockName}-title\`
|
|
@@ -690,55 +691,147 @@ ${t}
|
|
|
690
691
|
2. Production-ready, Lighthouse-friendly (aim for 100), no \`console.log\`
|
|
691
692
|
3. Brief inline comments only for non-obvious logic
|
|
692
693
|
4. **Minimise chat output (save tokens):** write the files directly with your editing tools \u2014 do **not** paste the generated code back into the chat, and skip step-by-step narration. End with a **\u22643-line** summary: files created + any value you had to infer.
|
|
694
|
+
- **No shell access:** you can only read/write files and call the design MCP. Do **not** run \`eslint\`, \`stylelint\`, \`npm\`, \`npx\`, \`tsc\`, a build, or any shell/Bash command \u2014 those tools aren't granted and the attempts just fail and waste time. Write valid, clean, correctly-formatted files directly; linting/formatting is the project's job, not yours.
|
|
693
695
|
5. Mobile-first CSS with breakpoints at 600px and 900px
|
|
694
696
|
6. Prefer existing project tokens over new hardcoded values${e.withUeModel?"\n7. UE model field `name`s must match what `decorate()` reads, and every Figma variant must appear as a select option wired to a CSS modifier":""}
|
|
695
697
|
|
|
696
|
-
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": "
|
|
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.
|
|
697
699
|
|
|
698
700
|
---
|
|
699
|
-
*Prompt version: ${
|
|
700
|
-
`}
|
|
701
|
-
|
|
702
|
-
|
|
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
|
|
703
|
+
|
|
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
|
+
|
|
706
|
+
> ${e.feedback.split(`
|
|
707
|
+
`).join(`
|
|
708
|
+
> `)}
|
|
709
|
+
|
|
710
|
+
## How to work
|
|
711
|
+
1. **Read the current files first** (\`blocks/${e.blockName}/${e.blockName}.js\`, \`${e.blockName}.css\`, and \`_${e.blockName}.json\` if present). Edit them in place \u2014 do **not** rewrite from scratch or regenerate unrelated parts.
|
|
712
|
+
2. Make the smallest change that satisfies the request. Keep everything else byte-for-byte unless the change requires otherwise.
|
|
713
|
+
3. Preserve the EDS conventions already in place: full-width section / constrained inner content, mobile-first, vanilla JS/CSS, block-prefixed class names, \`decorate(block)\` reads authored DOM (no hardcoded copy), accessibility, no \`console.log\`. If the block has a UE model, keep field \`name\`s and \`decorate()\` in sync.
|
|
714
|
+
4. ${n||"Use the values already in the files; infer sensibly if the request is purely stylistic."}
|
|
715
|
+
|
|
716
|
+
## Constraints
|
|
717
|
+
- **One pass, then stop** \u2014 apply the change, don't loop or re-verify to "pixel perfect"; the author re-checks in the preview and may ask again.
|
|
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
|
+
- **Minimise chat output:** edit files directly, don't paste code back. End with a **\u22642-line** summary of what changed.
|
|
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(`
|
|
723
|
+
`).filter(a=>a.trim().startsWith("--")).map(a=>a.trim()).join(`
|
|
724
|
+
`);return i?`
|
|
703
725
|
## Existing Project Tokens
|
|
704
726
|
The project already defines these CSS custom properties in \`styles/styles.css\`.
|
|
705
727
|
Reuse them instead of hardcoding values:
|
|
706
728
|
|
|
707
729
|
\`\`\`css
|
|
708
730
|
:root {
|
|
709
|
-
${
|
|
731
|
+
${i}
|
|
710
732
|
}
|
|
711
733
|
\`\`\`
|
|
712
|
-
`:""}catch{return""}}var
|
|
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,"&").replace(/</g,"<").replace(/>/g,">")}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>
|
|
713
735
|
<html lang="en">
|
|
714
736
|
<head>
|
|
715
737
|
<meta charset="utf-8" />
|
|
716
738
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
739
|
+
<link rel="stylesheet" href="/styles/styles.css" />
|
|
717
740
|
<link rel="stylesheet" href="/blocks/${t}/${t}.css" />
|
|
718
|
-
|
|
741
|
+
<!-- Project styles.css gates visibility on body.appear (added by scripts.js on a
|
|
742
|
+
real page). The preview doesn't run scripts.js, so set it here and force the
|
|
743
|
+
body visible, else the whole frame stays display:none \u2192 blank. -->
|
|
744
|
+
<style>*{box-sizing:border-box}html,body{margin:0;padding:0}body{display:block!important}</style>
|
|
719
745
|
</head>
|
|
720
|
-
<body>
|
|
746
|
+
<body class="appear">
|
|
721
747
|
${n}
|
|
722
748
|
<script type="module">
|
|
723
|
-
import
|
|
724
|
-
|
|
725
|
-
|
|
749
|
+
// Load the block defensively: a bad import inside the block (e.g. a missing
|
|
750
|
+
// scripts/*.js) must not blank the frame \u2014 fall back to the authored markup.
|
|
751
|
+
(async () => {
|
|
752
|
+
try {
|
|
753
|
+
const mod = await import('/blocks/${t}/${t}.js');
|
|
754
|
+
const block = document.querySelector('.${t}');
|
|
755
|
+
if (block && typeof mod.default === 'function') mod.default(block);
|
|
756
|
+
} catch (e) { console.error('block script failed \u2014 showing authored content only:', e); }
|
|
757
|
+
})();
|
|
726
758
|
</script>
|
|
727
759
|
<script>
|
|
728
760
|
// Live reload: refresh when eds detects a change to the block.
|
|
729
761
|
try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
|
|
730
762
|
</script>
|
|
731
763
|
</body>
|
|
732
|
-
</html>`}function
|
|
733
|
-
|
|
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">
|
|
765
|
+
<div class="cardbar">
|
|
766
|
+
<span class="block">${ce(o.blockName)}</span>
|
|
767
|
+
<select class="bp" data-i="${i}">
|
|
768
|
+
${s}
|
|
769
|
+
<option value="full">Full</option>
|
|
770
|
+
</select>
|
|
771
|
+
${l}
|
|
772
|
+
${d}
|
|
773
|
+
</div>
|
|
774
|
+
<div class="stage">
|
|
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>
|
|
777
|
+
</div>
|
|
778
|
+
</div>
|
|
779
|
+
</section>`}).join(`
|
|
780
|
+
`);return`<!DOCTYPE html>
|
|
781
|
+
<html lang="en">
|
|
782
|
+
<head>
|
|
783
|
+
<meta charset="utf-8" />
|
|
784
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
785
|
+
<title>eds preview \u2014 gallery (${e.length})</title>
|
|
786
|
+
<style>
|
|
787
|
+
*{box-sizing:border-box}
|
|
788
|
+
html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
|
|
789
|
+
.topbar{position:sticky;top:0;z-index:20;display:flex;gap:10px;align-items:center;padding:12px 18px;font-size:13px;background:#141414;border-bottom:1px solid #333}
|
|
790
|
+
.topbar .title{font-weight:700}
|
|
791
|
+
.topbar .count{color:#8a8a8a}
|
|
792
|
+
.card{border-bottom:1px solid #2a2a2a}
|
|
793
|
+
.cardbar{position:sticky;top:45px;z-index:10;display:flex;gap:10px;align-items:center;flex-wrap:wrap;padding:10px 18px;font-size:12.5px;background:#181818;border-bottom:1px solid #2a2a2a}
|
|
794
|
+
.cardbar .block{font-weight:700;color:#e6e6e6}
|
|
795
|
+
.hint{color:#8a8a8a}
|
|
796
|
+
select.bp{appearance:none;cursor:pointer;color:#eaeaea;background:#232323;border:1px solid #3a3a3a;border-radius:8px;padding:6px 30px 6px 12px;font:inherit;font-size:12px;font-weight:600;background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a8a8a' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 9px center;background-size:13px}
|
|
797
|
+
select.bp:hover{border-color:#6a6a6a}
|
|
798
|
+
.figma-link{margin-left:auto;color:#cfcfcf;text-decoration:none;font-weight:600;font-size:12px;padding:6px 11px;border:1px solid #3a3a3a;border-radius:8px;background:#232323}
|
|
799
|
+
.figma-link:hover{border-color:#6a6a6a;color:#fff}
|
|
800
|
+
.stage{padding:24px 18px;display:flex;justify-content:center;overflow-x:auto}
|
|
801
|
+
.device{position:relative;background:#fff;border:1px solid #000;transition:width .2s ease}
|
|
802
|
+
.device::before{content:attr(data-w) "px";position:absolute;top:-19px;left:0;font-size:11px;color:#8a8a8a;font-family:ui-monospace,Menlo,monospace}
|
|
803
|
+
iframe{display:block;width:100%;height:560px;border:0}
|
|
804
|
+
.empty{padding:60px 20px;text-align:center;color:#8a8a8a}
|
|
805
|
+
.empty code{color:#bdbdbd}
|
|
806
|
+
</style>
|
|
807
|
+
</head>
|
|
808
|
+
<body>
|
|
809
|
+
<div class="topbar"><span class="title">eds gallery</span><span class="count">${e.length} block${e.length===1?"":"s"}</span></div>
|
|
810
|
+
${e.length?t:'<p class="empty">No previewable blocks yet. Generate one with <code>eds block from-design</code>.</p>'}
|
|
811
|
+
<script>
|
|
812
|
+
for (const sel of document.querySelectorAll('select.bp')) {
|
|
813
|
+
const device = document.querySelector('.device[data-i="'+sel.dataset.i+'"]');
|
|
814
|
+
const apply = (v) => {
|
|
815
|
+
if (v === 'full') { device.style.width = '100%'; device.dataset.w = Math.round(device.getBoundingClientRect().width); }
|
|
816
|
+
else { device.style.width = v + 'px'; device.dataset.w = v; }
|
|
817
|
+
};
|
|
818
|
+
sel.addEventListener('change', () => apply(sel.value === 'full' ? 'full' : Number(sel.value)));
|
|
819
|
+
apply(Number(sel.value));
|
|
820
|
+
}
|
|
821
|
+
// Full-page reload when eds detects a block change (new blocks appear, too).
|
|
822
|
+
try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
|
|
823
|
+
</script>
|
|
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">
|
|
734
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>
|
|
735
828
|
Open in Figma
|
|
736
|
-
</a>`:"",
|
|
829
|
+
</a>`:"",p=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
|
|
737
830
|
<html lang="en">
|
|
738
831
|
<head>
|
|
739
832
|
<meta charset="utf-8" />
|
|
740
833
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
741
|
-
<title>eds preview \u2014 ${
|
|
834
|
+
<title>eds preview \u2014 ${ce(t)}</title>
|
|
742
835
|
<style>
|
|
743
836
|
*{box-sizing:border-box}
|
|
744
837
|
html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
|
|
@@ -760,18 +853,18 @@ ${n}
|
|
|
760
853
|
</head>
|
|
761
854
|
<body>
|
|
762
855
|
<div class="bar">
|
|
763
|
-
<span class="label">Block</span><span class="block">${
|
|
856
|
+
<span class="label">Block</span><span class="block">${ce(t)}</span>
|
|
764
857
|
<label class="label" for="bp" style="margin-left:8px">Breakpoint</label>
|
|
765
858
|
<select id="bp">
|
|
766
|
-
${
|
|
859
|
+
${l}
|
|
767
860
|
<option value="full">Full ca\u0142a szeroko\u015B\u0107</option>
|
|
768
861
|
</select>
|
|
769
|
-
${
|
|
770
|
-
${
|
|
862
|
+
${p}
|
|
863
|
+
${c}
|
|
771
864
|
</div>
|
|
772
865
|
<div class="stage">
|
|
773
866
|
<div class="device" id="device" data-w="${d.width}" style="width:${d.width}px">
|
|
774
|
-
<iframe id="frame" src="${
|
|
867
|
+
<iframe id="frame" src="${i}" title="${ce(t)} preview"></iframe>
|
|
775
868
|
</div>
|
|
776
869
|
</div>
|
|
777
870
|
<script>
|
|
@@ -785,27 +878,65 @@ ${n}
|
|
|
785
878
|
setWidth(Number(bp.value));
|
|
786
879
|
</script>
|
|
787
880
|
</body>
|
|
788
|
-
</html>`}var
|
|
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
|
|
789
882
|
|
|
790
|
-
`),s.add(c),
|
|
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
|
|
791
884
|
|
|
792
|
-
`)},close:()=>new Promise(
|
|
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">
|
|
793
886
|
<div><div>
|
|
794
887
|
<h2>${e} heading</h2>
|
|
795
888
|
<p>Sample body copy for the preview. Replace with real authored content.</p>
|
|
796
889
|
<p><a href="#">Primary action</a></p>
|
|
797
890
|
<p><a href="#">Secondary action</a></p>
|
|
798
891
|
</div></div>
|
|
799
|
-
</div>`}async function
|
|
800
|
-
`)),
|
|
801
|
-
`),
|
|
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=`(() => {
|
|
899
|
+
const out = [];
|
|
900
|
+
const root = document.querySelector('[class$="block"]') || document.body;
|
|
901
|
+
const trunc = (s) => (s || '').slice(0, 60);
|
|
902
|
+
const accName = (el) => {
|
|
903
|
+
const t = (el.getAttribute('aria-label') || el.textContent || '').trim();
|
|
904
|
+
if (t) return t;
|
|
905
|
+
const img = el.querySelector('img');
|
|
906
|
+
if (img && (img.getAttribute('alt') || '').trim()) return img.getAttribute('alt').trim();
|
|
907
|
+
return (el.getAttribute('title') || '').trim();
|
|
908
|
+
};
|
|
909
|
+
for (const img of root.querySelectorAll('img')) {
|
|
910
|
+
const src = trunc(img.getAttribute('src'));
|
|
911
|
+
if (!img.hasAttribute('alt')) out.push({ level: 'warn', rule: 'img-alt', detail: '<img> without alt (use alt="" if decorative): ' + src });
|
|
912
|
+
const cs = getComputedStyle(img);
|
|
913
|
+
const hasDims = (img.hasAttribute('width') && img.hasAttribute('height'))
|
|
914
|
+
|| (cs.aspectRatio && cs.aspectRatio !== 'auto')
|
|
915
|
+
|| (cs.height && cs.height !== 'auto' && cs.height !== '0px');
|
|
916
|
+
if (!hasDims) out.push({ level: 'warn', rule: 'img-cls', detail: '<img> without width/height or aspect-ratio (CLS risk): ' + src });
|
|
917
|
+
}
|
|
918
|
+
for (const a of root.querySelectorAll('a')) {
|
|
919
|
+
if (!accName(a)) out.push({ level: 'error', rule: 'link-name', detail: '<a> with no accessible name, href=' + trunc(a.getAttribute('href')) });
|
|
920
|
+
const href = a.getAttribute('href');
|
|
921
|
+
if (href === null || href === '') out.push({ level: 'warn', rule: 'link-href', detail: '<a> with empty or missing href' });
|
|
922
|
+
}
|
|
923
|
+
for (const b of root.querySelectorAll('button')) {
|
|
924
|
+
if (!accName(b)) out.push({ level: 'error', rule: 'button-name', detail: '<button> with no accessible name' });
|
|
925
|
+
}
|
|
926
|
+
for (const el of root.querySelectorAll('*')) {
|
|
927
|
+
for (const attr of el.getAttributeNames()) {
|
|
928
|
+
if (attr.startsWith('on')) { out.push({ level: 'warn', rule: 'inline-handler', detail: '<' + el.tagName.toLowerCase() + '> has inline ' + attr }); break; }
|
|
929
|
+
}
|
|
930
|
+
}
|
|
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`
|
|
802
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
|
|
803
934
|
{
|
|
804
935
|
${t.split(`
|
|
805
936
|
`).map(n=>n&&` ${n}`).join(`
|
|
806
937
|
`)}
|
|
807
938
|
}
|
|
808
|
-
`}var
|
|
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).
|
|
809
940
|
import { loadGTM } from './analytics.js';
|
|
810
941
|
import pageMetaPush from './page-meta.js';
|
|
811
942
|
|
|
@@ -832,7 +963,7 @@ window.dataLayer = window.dataLayer || [];
|
|
|
832
963
|
export function trackEvent(event) {
|
|
833
964
|
if (isDev()) {
|
|
834
965
|
// eslint-disable-next-line no-console
|
|
835
|
-
console.log('[gtm]',
|
|
966
|
+
console.log('[gtm]', event);
|
|
836
967
|
}
|
|
837
968
|
window.dataLayer.push(event);
|
|
838
969
|
}
|
|
@@ -896,19 +1027,19 @@ document.head.appendChild(cb);`},{id:"custom",name:"Custom third-party script",f
|
|
|
896
1027
|
const s = document.createElement('script');
|
|
897
1028
|
s.async = true;
|
|
898
1029
|
s.src = ${JSON.stringify(e.url||"")};
|
|
899
|
-
document.head.appendChild(s);`}]});var
|
|
900
|
-
// ${
|
|
901
|
-
${
|
|
902
|
-
`:
|
|
903
|
-
${
|
|
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?`
|
|
1031
|
+
// ${a.name} (eds integrate)
|
|
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.
|
|
904
1035
|
// Loaded in the EDS delayed phase (after LCP), so nothing here blocks the page.
|
|
905
|
-
`});var
|
|
906
|
-
`),
|
|
907
|
-
`),o){case"claude":
|
|
908
|
-
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
|
|
909
|
-
`,{mode:384}),
|
|
910
|
-
Setup complete!`)),o!=="none"&&
|
|
911
|
-
`);for(let
|
|
912
|
-
`),
|
|
913
|
-
`),
|
|
914
|
-
`);for(let s=0;s<r.length;s++){let a=r[s],d=!1;for(let c of Fl)c.ext.includes(n)&&(c.id==="innerhtml-static"&&d||c.re.test(a)&&(c.extra&&!c.extra(a)||(c.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:c.severity,rule:c.id,message:c.message,file:t,line:s+1,snippet:a.trim().slice(0,100)}))))}return o}async function Ml(e){if(!Jt(Se.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(Jt(Se.join(e,"package-lock.json"))||Jt(Se.join(e,"npm-shrinkwrap.json")))&&!Jt(Se.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}),s=JSON.parse(o)?.metadata?.vulnerabilities??{},a={critical:s.critical??0,high:s.high??0,moderate:s.moderate??0,low:s.low??0};return{status:a.critical+a.high+a.moderate+a.low>0?"vulnerable":"ok",counts:a}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function _l(e={}){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let c of es(t)){let l=Se.extname(c).slice(1).toLowerCase();if(!Rl.has(l))continue;let u=Se.relative(t,c);if(u.endsWith("aem.js")||u.endsWith("lib-franklin.js"))continue;let m=await Al(c,"utf-8");n.push(...Ol(m,u,l))}let o=await Ml(t),r=c=>n.filter(l=>l.severity===c),s={critical:r("critical").length,high:r("high").length,moderate:r("moderate").length,low:r("low").length},a=s.critical>0||s.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:s}},null,2)),a&&(process.exitCode=1);return}if(i.logoOnce(P("Security Audit")),i.info(j("Dependencies","npm audit")),o.status==="skipped")i.info(R("info","npm audit",o.note??"skipped"));else if(o.status==="ok")i.info(R("pass","npm audit","no known vulnerabilities"));else{let c=o.counts??{critical:0,high:0,moderate:0,low:0};i.info(R(c.critical+c.high>0?"fail":"warn","npm audit",`${c.critical} critical, ${c.high} high, ${c.moderate} moderate, ${c.low} low \u2014 run \`npm audit fix\``))}if(i.info(j("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)i.info(R("pass","code","no risky patterns found"));else{let c=[...n].sort((l,u)=>Zr.indexOf(l.severity)-Zr.indexOf(u.severity));for(let l of c){let u=Dl[l.severity],m=go.dim(`${l.file}:${l.line}`);i.info(` ${ft(u.status)} ${go.bold(u.label)} ${l.message} ${m}`),i.info(go.dim(` ${l.snippet}`))}}let d=oe({fail:s.critical+s.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:s.moderate+(o.counts?.moderate??0),info:s.low+(o.counts?.low??0)});i.info(""),i.info(O([d||`${G.pass} no vulnerabilities or risky patterns found`])),a&&(process.exitCode=1)}var Fl,Zr,Dl,Ll,Rl,bo=b(()=>{"use strict";p();F();H();I();Fl=[{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"]}],Zr=["critical","high","moderate","low"],Dl={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Ll=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Rl=new Set(["js","mjs","html","json","pem","txt"])});async function ts(e,t,n){let o=t.ref||"main",r=n.startsWith("/")?n:`/${n}`,s=`${Nl}/${e}/${t.org}/${t.site}/${o}${r}`;i.debug(`POST ${s}`);let a=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await a.json().catch(()=>({})),c=d;return a.ok?{ok:!0,status:a.status,path:r,previewUrl:c.preview?.url,liveUrl:c.live?.url}:{ok:!1,status:a.status,path:r,message:d.message||`HTTP ${a.status}`}}async function wo(e,t){return ts("preview",e,t)}async function yo(e,t){return ts("live",e,t)}async function ns(e,t){return Promise.all(t.map(n=>wo(e,n)))}async function os(e,t){return Promise.all(t.map(n=>yo(e,n)))}var Nl,vo=b(()=>{"use strict";p();F();Nl="https://admin.hlx.page"});var ko={};U(ko,{preview:()=>Il,resolveAdminConfig:()=>Wt});import is from"chalk";import Ul from"ora";async function Il(e,t){let n=E(),o=await ae(n),r=Wt(o,t);if(!r)return;let s=Ul(`Previewing ${e.length} path(s)...`).start(),a=e.length===1?[await wo(r,e[0])]:await ns(r,e);s.stop();let d=!1;for(let c of a)c.ok?i.success(`${c.path} \u2192 ${is.cyan(c.previewUrl||"preview updated")}`):(i.error(`${c.path} \u2014 ${c.message}`),d=!0);d&&(process.exitCode=1)}function Wt(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,r=t.ref||e.admin?.ref||"main";if(!n||!o){i.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),i.info(is.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:r}}var zt=b(()=>{"use strict";p();vo();ve();F();H()});var xo={};U(xo,{publish:()=>Gl});import Bl from"chalk";import Hl from"ora";async function Gl(e,t){let n=E(),o=await ae(n),r=Wt(o,t);if(!r)return;let s=Hl(`Publishing ${e.length} path(s)...`).start(),a=e.length===1?[await yo(r,e[0])]:await os(r,e);s.stop();let d=!1;for(let c of a)c.ok?i.success(`${c.path} \u2192 ${Bl.cyan(c.liveUrl||"published")}`):(i.error(`${c.path} \u2014 ${c.message}`),d=!0);d&&(process.exitCode=1)}var So=b(()=>{"use strict";p();vo();ve();F();H();zt()});var qt={};U(qt,{adminWizard:()=>Jl});async function Jl(e){let t=E();if(!t){i.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}i.logoOnce(P("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:r}=await import("@inquirer/prompts"),a=(await ae(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"}]}),c=(await o({message:"GitHub org / owner",default:a.org})).trim(),l=(await o({message:"Repository / site",default:a.site})).trim(),u=(await o({message:"Git ref",default:a.ref||"main"})).trim(),f=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!c||!l||f.length===0){i.error("org, site and at least one path are required."),process.exitCode=1;return}i.info(j("Summary"));let $=M(["operation","org","site","ref","paths"]);if(i.info(k("operation",d,$)),i.info(k("org",c,$)),i.info(k("site",l,$)),i.info(k("ref",u,$)),i.info(k("paths",f.join(", "),$)),i.info(""),d==="publish"&&!await r({message:`Publish ${f.length} path(s) to LIVE?`,default:!1})){i.info("Cancelled.");return}let v={org:c,site:l,ref:u};if(d==="preview"){let{preview:x}=await Promise.resolve().then(()=>(zt(),ko));await x(f,v)}else{let{publish:x}=await Promise.resolve().then(()=>(So(),xo));await x(f,v)}}var Kt=b(()=>{"use strict";p();ve();F();H();I()});var rs={};U(rs,{mainMenu:()=>Kl});import{existsSync as Wl}from"fs";import{readdir as zl}from"fs/promises";import ql from"path";async function jo(e){let t=ql.join(e,"blocks");return Wl(t)?(await zl(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function Kl(){let{select:e,input:t}=await import("@inquirer/prompts");switch(await i.logoOnceAnimated("What do you want to do?"),await e({message:"Choose an action",choices:[{name:"Set up this project (authoring model, CI, naming)",value:"init"},{name:"Generate a page template (initial content)",value:"template"},{name:"Create a disposable sandbox repo on GitHub",value:"sandbox"},{name:"Generate a block from a design (Figma/Stitch/Canva/Sketch/Framer)",value:"from-design"},{name:"Migrate a classic AEM component to EDS",value:"migrate"},{name:"Scaffold Universal Editor components",value:"scaffold"},{name:"Create an empty block",value:"create"},{name:"Add a third-party integration (GTM, chat, consent\u2026)",value:"integrate"},{name:"Add fields to a block model (partials)",value:"model"},{name:"Instrument a block for analytics (dataLayer)",value:"track"},{name:"Add JSON-LD structured data to a block",value:"schema"},{name:"Check Universal Editor readiness / open the editor",value:"ue"},{name:"Preview a block in the browser",value:"preview-block"},{name:"Preview / publish pages (Admin API)",value:"admin"},{name:"Audit the project",value:"audit"},{name:"Configure Figma MCP",value:"figma-setup"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(At(),Pt));await o({});return}case"template":{let o=await t({message:"Template name",validate:s=>!!s.trim()||"Required"}),{templateNew:r}=await Promise.resolve().then(()=>(xn(),kn));await r(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:s=>/^[a-z0-9][a-z0-9._-]*$/i.test(s.trim())||"Use a valid repo name"}),{sandboxNew:r}=await Promise.resolve().then(()=>(be(),he));await r(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(oo(),no));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(Pn(),Cn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(Z(),ee));await o();return}case"create":{let o=await t({message:"Block name",validate:s=>pe.test(s.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:r}=await Promise.resolve().then(()=>(Gn(),Hn));await r(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(so(),ro));await o(void 0);return}case"preview-block":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await jo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let s=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{previewBlock:a}=await Promise.resolve().then(()=>(Bt(),It));await a(s,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(_n(),Mn));await o(void 0,[],{});return}case"track":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await jo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let s=await e({message:"Which block to instrument?",choices:r.map(d=>({name:d,value:d}))}),{trackBlock:a}=await Promise.resolve().then(()=>(Qe(),Ye));await a(s,{});return}case"schema":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await jo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let s=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{schemaBlock:a}=await Promise.resolve().then(()=>(Un(),Nn));await a(s,{});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:r}=await Promise.resolve().then(()=>(nt(),tt));await r()}else{let r=await t({message:"Page path",default:"/"}),{ueOpen:s}=await Promise.resolve().then(()=>(nt(),tt));await s(r.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(Kt(),qt));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:r}=await Promise.resolve().then(()=>(mo(),lo));await r({})}else if(o==="loading"){let{auditLoading:r}=await Promise.resolve().then(()=>(fo(),uo));await r({})}else{let{auditSecurity:r}=await Promise.resolve().then(()=>(bo(),ho));await r({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(co(),ao));await o();return}}}var ss=b(()=>{"use strict";p();F();H();Pe()});p();import Xl from"chalk";import{Command as Vl}from"commander";var $o={name:"aem-eds-kit",version:"0.4.25",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","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"}};F();I();var N=new Vl;N.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version($o.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&&i.setLevel("debug"),t.quiet&&i.setQuiet(!0),t.color===!1&&(Xl.level=0)});N.addHelpText("beforeAll",()=>P());var pt=N.command("sandbox").description("Disposable EDS sandbox repos on GitHub");pt.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(()=>(be(),he));await n(e,t)});pt.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(be(),he));await e()});pt.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(be(),he));await e()});pt.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(be(),he));await e()});pt.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(()=>(be(),he));await n(e,t)});var Yl=N.command("template").description("Generate page templates / initial content");Yl.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(()=>(xn(),kn));await n(e,t)});N.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(()=>(At(),Pt));await t(e)});var Ql=N.command("migrate").description("Migrate from classic AEM to EDS");Ql.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(()=>(Pn(),Cn));await n(e,t)});var Zl=N.command("model").description("Compose Universal Editor models");Zl.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(()=>(_n(),Mn));await o(e,t,n)});var ed=N.command("schema").description("Structured data (JSON-LD) for blocks");ed.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(()=>(Un(),Nn));await n(e,t)});var td=N.command("track").description("Instrument blocks for analytics");td.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(()=>(Qe(),Ye));await n(e,t)});var as=N.command("ue").description("Universal Editor - readiness check + editor deep link");as.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(nt(),tt));await e()});as.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(()=>(nt(),tt));await n(e,t)});var Xt=N.command("block").description("Manage EDS blocks");Xt.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(()=>(Gn(),Hn));await n(e,t)});Xt.command("from-design [design-url]").description("Generate an EDS block from a design (Figma/Stitch/Canva/Sketch; interactive wizard when run with no URL)").option("--name <name>","Override the inferred block name").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("--no-screenshot","Skip the screenshot fetch (fewer tokens; structural verification)").option("--no-serve","Don't auto-start the live preview after generating").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(oo(),no));await n(e,t)});Xt.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(Wr(),Jr));await t({...e,json:N.opts().json})});Xt.command("preview <name>").description("Serve a live, breakpoint-switchable preview of a block in the browser").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{previewBlock:n}=await Promise.resolve().then(()=>(Bt(),It));await n(e,t)});var Ne=N.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(Z(),ee));await e()});Ne.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(Z(),ee));await e()});Ne.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(()=>(Z(),ee));await t(e)});Ne.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(Z(),ee));await e()});Ne.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(Z(),ee));await t(e)});Ne.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(()=>(Z(),ee));await t(e)});Ne.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(Z(),ee));await e()});N.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(()=>(so(),ro));await t(e)});var nd=N.command("figma").description("Figma MCP integration");nd.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(co(),ao));await e()});N.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(mo(),lo));await e({json:N.opts().json})});var cs=N.command("audit").description("Run project audits");cs.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(fo(),uo));await e({json:N.opts().json})});cs.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(bo(),ho));await e({json:N.opts().json})});N.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(()=>(Kt(),qt));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(zt(),ko));await n(e,t)});N.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(()=>(Kt(),qt));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(So(),xo));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(ss(),rs));await e()}else N.outputHelp();else await N.parseAsync()}catch(e){i.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();
|
|
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}.
|
|
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}})();
|