aem-eds-kit 0.4.26 → 0.4.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +80 -8
- package/dist/bin/eds.js +158 -116
- package/package.json +6 -2
- package/samples/hero.svg +35 -0
package/dist/bin/eds.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
`)}function
|
|
4
|
-
${
|
|
5
|
-
|
|
6
|
-
${
|
|
7
|
-
`}function
|
|
8
|
-
${n} ${
|
|
9
|
-
`}function
|
|
2
|
+
var Ps=Object.defineProperty;var k=(e,t)=>()=>(e&&(t=e(e=0)),t);var O=(e,t)=>{for(var n in t)Ps(e,n,{get:t[n],enumerable:!0})};import sp from"path";import{fileURLToPath as lp}from"url";var f=k(()=>{"use strict"});import L from"chalk";function Rt(e){return W[e]}function ri(e){return e.replace(Cs,"").length}function nt(e,t){let n=t-ri(e);return n>0?e+" ".repeat(n):e}function As(){return L.bgHex("#ff5a36").hex("#0d0d0c").bold(" >_ ")}function ni(){return`${As()} ${L.bold("aem-eds-kit")}`}function Rs(){return Array.from({length:Ts},()=>U.accent("\u25CF")).join(" ")}function Fs(e,t=""){return t?`${ni()} ${e} ${L.dim(t)}`:`${ni()} ${e}`}function oi(e){let t=e.replace("#","");return[Number.parseInt(t.slice(0,2),16),Number.parseInt(t.slice(2,4),16),Number.parseInt(t.slice(4,6),16)]}function Ds(e,t,n){let[o,i,a]=oi(e),[s,d,l]=oi(t),c=Math.round(o+(s-o)*n),m=Math.round(i+(d-i)*n),p=Math.round(a+(l-a)*n);return`#${[c,m,p].map(u=>u.toString(16).padStart(2,"0")).join("")}`}function Ls(e,t,n){let o=[...e],i=Math.max(n-1,1);return o.map((a,s)=>{if(a===" ")return a;let d=s/i*(t.length-1),l=Math.min(Math.floor(d),t.length-2);return L.hex(Ds(t[l],t[l+1],d-l))(a)}).join("")}function Ns(){let e=I(ii);return ii.map(t=>` ${Ls(t,Os,e)}`).join(`
|
|
3
|
+
`)}function C(e="AEM Edge Delivery Services"){return`
|
|
4
|
+
${Ns()}
|
|
5
|
+
|
|
6
|
+
${Fs(Rs(),e)}
|
|
7
|
+
`}function S(e,t){let n=U.red("\u258A"),o=t?` ${L.dim(t)}`:"";return`
|
|
8
|
+
${n} ${L.bold(e)}${o}
|
|
9
|
+
`}function A(e,t,n,o=0){let i=o?nt(t,o):t,a=n?` ${L.dim(n)}`:"";return` ${W[e]} ${i}${a}`}function j(e,t,n=0){let o=n?nt(e,n):e,i=t?` ${L.dim(t)}`:"";return` ${U.accent("\u2714")} ${o}${i}`}function I(e){return e.reduce((t,n)=>Math.max(t,ri(n)),0)}function N(e,t=U.red){let n=I(e),o=t(`\u256D${"\u2500".repeat(n+2)}\u256E`),i=t(`\u2570${"\u2500".repeat(n+2)}\u256F`),a=e.map(s=>`${t("\u2502")} ${nt(s,n)} ${t("\u2502")}`).join(`
|
|
10
10
|
`);return`${o}
|
|
11
11
|
${a}
|
|
12
|
-
${
|
|
13
|
-
`,{mode:384})}async function
|
|
12
|
+
${i}`}function ge(e){let t=[];return e.pass&&t.push(`${W.pass} ${e.pass} passed`),e.warn&&t.push(`${W.warn} ${e.warn} ${Ms(e.warn,"warning")}`),e.fail&&t.push(`${W.fail} ${e.fail} failed`),e.info&&t.push(`${W.info} ${e.info} info`),t.join(L.dim(" "))}function Ms(e,t){return e===1?t:`${t}s`}var U,W,Cs,Ts,ai,ii,Os,M=k(()=>{"use strict";f();U={red:L.hex("#FA0F00"),ember:L.hex("#FF4B1F"),orange:L.hex("#FF7B00"),blue:L.hex("#2680EB"),accent:L.hex("#ff5a36"),dotOrange:L.hex("#F24E1E"),dotPurple:L.hex("#A259FF"),dotBlue:L.hex("#1ABCFE"),dotGreen:L.hex("#0ACF83"),dotPink:L.hex("#FF7262"),ok:L.hex("#2D9D78"),warn:L.hex("#E68619"),err:L.hex("#D7373F"),info:L.hex("#2680EB")},W={pass:U.ok("\u2713"),warn:U.warn("\u26A0"),fail:U.err("\u2717"),info:U.info("\u2139"),bullet:L.dim("\u2022"),arrow:L.dim("\u21B3"),figma:U.dotPurple("\u25C6")};Cs=/\[[0-9;]*m/g;Ts=5;ai={prefix:"",style:{highlight:e=>L.hex("#ff5a36").bold(e)}};ii=["\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588 ","\u2588\u2588\u2588\u2588 \u2588 \u2588 \u2588\u2588\u2588\u2588\u2588","\u2588 \u2588 \u2588 \u2588","\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588"],Os=["#ff3b1e","#ff5a36","#ff7d52"]});import Ft from"chalk";function Is(){let e=process.env.EDS_LOG_LEVEL?.toLowerCase();return e&&e in gn?e:"info"}function je(e){return ci?e==="error":gn[e]>=gn[si]}var gn,si,ci,Dt,r,R=k(()=>{"use strict";f();M();gn={debug:0,info:1,warn:2,error:3,silent:4};si=Is(),ci=!1,Dt=!1;r={setLevel(e){si=e},setQuiet(e){ci=e},debug(...e){je("debug")&&console.error(Ft.gray("[debug]"),...e)},info(...e){je("info")&&console.error(...e)},logoOnce(e){Dt||(Dt=!0,je("info")&&console.error(e))},async logoOnceAnimated(e){Dt||(Dt=!0,je("info")&&console.error(C(e)))},success(...e){je("info")&&console.error(Ft.green("\u2713"),...e)},warn(...e){je("warn")&&console.error(Ft.yellow("\u26A0"),...e)},error(...e){je("error")&&console.error(Ft.red("\u2717"),...e)}}});function _e(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"aem-eds-kit","Content-Type":"application/json"}}function _s(e){return`${Ie}/repos/${e}/generate`}async function Lt(e){let t=await fetch(`${Ie}/user`,{headers:_e(e)});if(!t.ok)throw new Error(`GitHub auth failed: ${t.status}`);return(await t.json()).login}async function li(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{headers:_e(e)});if(o.status===404)return!1;if(o.ok)return!0;throw new Error(`existence check failed: ${o.status} ${await o.text()}`)}async function di(e,t,n){let o=await fetch(_s(t),{method:"POST",headers:_e(e),body:JSON.stringify({owner:n.owner,name:n.name,private:!!n.private,include_all_branches:!1})});if(!o.ok)throw new Error(`create failed: ${o.status} ${await o.text()}`);let i=await o.json();return{fullName:i.full_name,htmlUrl:i.html_url,cloneUrl:i.clone_url}}async function mi(e,t,n,o){await fetch(`${Ie}/repos/${t}/${n}/topics`,{method:"PUT",headers:_e(e),body:JSON.stringify({names:o})})}async function pi(e,t,n){let o=await fetch(`${Ie}/repos/${t}/${n}`,{method:"DELETE",headers:_e(e)});if(!o.ok&&o.status!==204)throw new Error(`delete failed: ${o.status} ${await o.text()}`)}async function ui(e,t,n){let o=encodeURIComponent(`user:${t} topic:${n} fork:true`),i=await fetch(`${Ie}/search/repositories?q=${o}&per_page=100`,{headers:_e(e)});if(!i.ok)throw new Error(`search failed: ${i.status}`);return(await i.json()).items.map(s=>s.full_name)}var Ie,fi=k(()=>{"use strict";f();Ie="https://api.github.com"});import{existsSync as gi}from"fs";import{mkdir as Us,readFile as Bs,rm as Hs,writeFile as Gs}from"fs/promises";import zs from"os";import hi from"path";async function bi(){let e=process.env.GITHUB_TOKEN||process.env.GH_TOKEN;if(e)return e;if(gi(ot))try{return JSON.parse(await Bs(ot,"utf-8")).token??null}catch{return null}return null}async function hn(e){await Us(wi,{recursive:!0,mode:448}),await Gs(ot,`${JSON.stringify({token:e},null,2)}
|
|
13
|
+
`,{mode:384})}async function yi(){gi(ot)&&await Hs(ot)}async function vi(e){let t=await fetch("https://github.com/login/device/code",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Ot,scope:e.join(" ")})});if(!t.ok)throw new Error(`device code request failed: ${t.status}`);return await t.json()}async function ki(e,t,n){let o=Math.max(t,1),i=Date.now()+n*1e3;for(;Date.now()<i;){await new Promise(d=>setTimeout(d,o*1e3));let s=await(await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({client_id:Ot,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})})).json();if(s.access_token)return s.access_token;if(s.error==="slow_down")o+=5;else if(s.error!=="authorization_pending")throw new Error(s.error??"device flow failed")}throw new Error("device flow timed out")}var wi,ot,Ot,xi=k(()=>{"use strict";f();wi=hi.join(zs.homedir(),".eds"),ot=hi.join(wi,"github.json"),Ot=process.env.EDS_GITHUB_CLIENT_ID??""});function wn(e,t,n="main"){return`https://${n}--${t}--${e}.aem.page/`}function bn(){return"https://github.com/apps/aem-code-sync/installations/new"}function $i(e,t){return["repo","create",e,"--template",t.template,t.private?"--private":"--public",...t.clone?["--clone"]:[]]}var Ue,it,Si=k(()=>{"use strict";f();Ue="eds-sandbox",it={document:"adobe/aem-boilerplate",ue:"adobe/aem-boilerplate-xwalk"}});var H={};O(H,{checkbox:()=>Qs,confirm:()=>Ys,input:()=>Vs,select:()=>Xs});import{checkbox as Ws,confirm as Js,input as qs,select as Ks}from"@inquirer/prompts";function Nt(e){let t={...ai,...e.theme??{}};return{...e,theme:t}}var Xs,Vs,Ys,Qs,G=k(()=>{"use strict";f();M();Xs=(e,t)=>Ks(Nt(e),t),Vs=(e,t)=>qs(Nt(e),t),Ys=(e,t)=>Js(Nt(e),t),Qs=(e,t)=>Ws(Nt(e),t)});import{z as F}from"zod";var Rp,yn,ji,Fp,Pe,Be=k(()=>{"use strict";f();Rp=F.object({fileKey:F.string().min(1),nodeId:F.string().optional(),fileName:F.string().optional()}),yn=F.object({agent:F.enum(["claude","cursor","codex"]).optional(),model:F.string().optional(),figma:F.object({mcpEndpoint:F.string().url().optional(),token:F.string().optional()}).optional(),admin:F.object({org:F.string().optional(),site:F.string().optional(),ref:F.string().default("main")}).optional()}),ji=F.object({root:F.string(),hasFstab:F.boolean(),hasBlocks:F.boolean(),hasHeadHtml:F.boolean()}),Fp=F.object({figmaFileKey:F.string(),figmaNodeId:F.string().optional(),lastSyncedAt:F.string().datetime(),promptVersion:F.string(),agentUsed:F.string().optional(),breakpoints:F.array(F.object({width:F.number(),label:F.string().optional(),source:F.enum(["figma","default"]).optional()})).optional()}),Pe=/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/});import{existsSync as rt}from"fs";import he from"path";function P(e=process.cwd()){let t=he.resolve(e),{root:n}=he.parse(t);for(;t!==n;){if(Pi.some(o=>rt(he.join(t,o))))return t;t=he.dirname(t)}if(Pi.some(o=>rt(he.join(n,o))))return n}function Ei(e){return ji.parse({root:e,hasFstab:rt(he.join(e,"fstab.yaml")),hasBlocks:rt(he.join(e,"blocks")),hasHeadHtml:rt(he.join(e,"head.html"))})}var Pi,z=k(()=>{"use strict";f();Be();Pi=["fstab.yaml","head.html","helix-query.yaml","component-definition.json","paths.json","scripts/scripts.js","scripts/aem.js"]});import{existsSync as Zs}from"fs";import{mkdir as ec,writeFile as tc}from"fs/promises";import Ci from"path";async function Mt(e){let t=Ci.join(e,".github","workflows","eds.yml");return Zs(t)?{path:Ai,created:!1}:(await ec(Ci.dirname(t),{recursive:!0}),await tc(t,nc),{path:Ai,created:!0})}var Ai,nc,vn=k(()=>{"use strict";f();Ai=".github/workflows/eds.yml",nc=`name: EDS checks
|
|
14
14
|
|
|
15
15
|
# Generated by aem-eds-kit (\`eds scaffold ci\`). Runs the project's own
|
|
16
16
|
# lint/build plus the eds audits as a gatekeeper on every PR and push to main.
|
|
@@ -53,18 +53,18 @@ jobs:
|
|
|
53
53
|
run: npx --yes aem-eds-kit@latest audit loading
|
|
54
54
|
- name: Security & exploit scan
|
|
55
55
|
run: npx --yes aem-eds-kit@latest audit security
|
|
56
|
-
`});import{existsSync as
|
|
56
|
+
`});import{existsSync as Ti}from"fs";import{readFile as oc,writeFile as Ri}from"fs/promises";import Fi from"path";function ic(e={}){let t=e.open??"/",n=e.port??3007,o=e.pagesUrl??"";return`AEM_OPEN=${t}
|
|
57
57
|
AEM_PORT=${n}
|
|
58
58
|
AEM_PAGES_URL=${o}
|
|
59
|
-
`}async function
|
|
59
|
+
`}async function rc(e){let t=Fi.join(e,".gitignore"),n="";if(Ti(t)&&(n=await oc(t,"utf-8")),n.split(/\r?\n/).some(i=>i.trim()===".env"))return!1;let o=n&&!n.endsWith(`
|
|
60
60
|
`)?`
|
|
61
|
-
`:"";return await
|
|
62
|
-
`),!0}async function
|
|
61
|
+
`:"";return await Ri(t,`${n}${o}.env
|
|
62
|
+
`),!0}async function It(e,t={}){let n=Fi.join(e,".env"),o=!Ti(n);o&&await Ri(n,ic(t));let i=await rc(e);return{path:".env",created:o,gitignoreUpdated:i}}var kn=k(()=>{"use strict";f()});import{writeFile as Di}from"fs/promises";import Li from"path";function _t(e){return e!=="ue"}function Oi(e,t){return`https://content.da.live/${e}/${t}/`}function ac(e){return`mountpoints:
|
|
63
63
|
/: ${e}
|
|
64
|
-
`}async function
|
|
65
|
-
`}async function
|
|
66
|
-
`}async function
|
|
67
|
-
`}function
|
|
64
|
+
`}async function Ni(e,t){return await Di(Li.join(e,"fstab.yaml"),ac(t)),"fstab.yaml"}function sc(e){return`${JSON.stringify({mappings:[`/content/${e}/:/`],includes:[`/content/${e}/`]},null,2)}
|
|
65
|
+
`}async function Mi(e,t){return await Di(Li.join(e,"paths.json"),sc(t)),"paths.json"}var Ee,Ii=k(()=>{"use strict";f();Ee={ue:"Universal Editor (crosswalk)",da:"Document Authoring (da.live)",gdrive:"Document Authoring (Google Drive)",sharepoint:"Document Authoring (SharePoint)"}});import{existsSync as cc}from"fs";import{writeFile as lc}from"fs/promises";import dc from"path";function pc(){return`${JSON.stringify(mc,null,2)}
|
|
66
|
+
`}async function Ut(e){let t=dc.join(e,"xwalk.json");return cc(t)?{path:"xwalk.json",created:!1}:(await lc(t,pc()),{path:"xwalk.json",created:!0})}var mc,xn=k(()=>{"use strict";f();mc={public:{xwalk:{"multi-field":{enabled:!0}}}}});function He(e){let t=e.trim().match(/github\.com[:/]([^/]+)\/(.+?)(?:\.git)?\/?$/i);return t?{owner:t[1],repo:t[2]}:null}function Ge(e,t,n="main"){return`${n}--${t}--${e}.aem.page`}function _i({host:e,path:t="/",org:n}){let o=e.replace(/^https?:\/\//,"").replace(/\/+$/,""),i=t.startsWith("/")?t:`/${t}`;return`https://experience.adobe.com/#/${n?`@${n}/`:""}aem/editor/canvas/${o}${i}`}var Bt=k(()=>{"use strict";f()});function at(e){return`${JSON.stringify(e,null,2)}
|
|
67
|
+
`}function Sn(e){return Ce.find(t=>t.id===e)}var $n,Ui,Bi,Ce,jn=k(()=>{"use strict";f();$n=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,model:n}}}}}),Ui=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:e,filter:n}}}}}),Bi=(e,t,n)=>({title:e,id:t,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block/item",template:{name:e,model:n}}}}}),Ce=[{id:"hero",title:"Hero",js:`// Block: hero
|
|
68
68
|
export default function decorate(block) {
|
|
69
69
|
block.classList.add('hero');
|
|
70
70
|
const picture = block.querySelector('picture');
|
|
@@ -93,7 +93,7 @@ export default function decorate(block) {
|
|
|
93
93
|
margin: 0 auto;
|
|
94
94
|
padding: 0 var(--spacing-m, 16px);
|
|
95
95
|
}
|
|
96
|
-
`,model:
|
|
96
|
+
`,model:at({definitions:[$n("Hero","hero","hero")],models:[{id:"hero",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"}]}],filters:[]})},{id:"cards",title:"Cards",js:`// Block: cards
|
|
97
97
|
export default function decorate(block) {
|
|
98
98
|
const ul = document.createElement('ul');
|
|
99
99
|
[...block.children].forEach((row) => {
|
|
@@ -132,7 +132,7 @@ export default function decorate(block) {
|
|
|
132
132
|
.cards .cards-card-body {
|
|
133
133
|
padding: var(--spacing-m, 16px);
|
|
134
134
|
}
|
|
135
|
-
`,model:
|
|
135
|
+
`,model:at({definitions:[Ui("Cards","cards","cards"),Bi("Card","card","card")],models:[{id:"card",fields:[{component:"reference",valueType:"string",name:"image",label:"Image"},{component:"text",valueType:"string",name:"imageAlt",label:"Alt"},{component:"text",valueType:"string",name:"title",label:"Title"},{component:"richtext",valueType:"string",name:"text",value:"",label:"Text"},{component:"aem-content",name:"link",label:"Link"}]}],filters:[{id:"cards",components:["card"]}]})},{id:"columns",title:"Columns",js:`// Block: columns
|
|
136
136
|
export default function decorate(block) {
|
|
137
137
|
const cols = [...block.firstElementChild.children];
|
|
138
138
|
block.classList.add(\`columns-\${cols.length}-cols\`);
|
|
@@ -159,7 +159,7 @@ export default function decorate(block) {
|
|
|
159
159
|
}
|
|
160
160
|
|
|
161
161
|
.columns img { width: 100%; height: auto; }
|
|
162
|
-
`,model:
|
|
162
|
+
`,model:at({definitions:[$n("Columns","columns","columns")],models:[{id:"columns",fields:[{component:"richtext",valueType:"string",name:"content",value:"",label:"Content"}]}],filters:[]})},{id:"accordion",title:"Accordion",js:`// Block: accordion
|
|
163
163
|
export default function decorate(block) {
|
|
164
164
|
[...block.children].forEach((row) => {
|
|
165
165
|
const [label, body] = row.children;
|
|
@@ -192,7 +192,7 @@ export default function decorate(block) {
|
|
|
192
192
|
.accordion .accordion-item-body {
|
|
193
193
|
padding-bottom: var(--spacing-m, 16px);
|
|
194
194
|
}
|
|
195
|
-
`,model:
|
|
195
|
+
`,model:at({definitions:[Ui("Accordion","accordion","accordion"),Bi("Accordion Item","accordion-item","accordion-item")],models:[{id:"accordion-item",fields:[{component:"text",valueType:"string",name:"label",label:"Label"},{component:"richtext",valueType:"string",name:"body",value:"",label:"Body"}]}],filters:[{id:"accordion",components:["accordion-item"]}]})},{id:"embed",title:"Embed",js:`// Block: embed
|
|
196
196
|
export default function decorate(block) {
|
|
197
197
|
const link = block.querySelector('a');
|
|
198
198
|
const url = link?.href;
|
|
@@ -221,12 +221,12 @@ export default function decorate(block) {
|
|
|
221
221
|
height: 100%;
|
|
222
222
|
border: 0;
|
|
223
223
|
}
|
|
224
|
-
`,model:
|
|
224
|
+
`,model:at({definitions:[$n("Embed","embed","embed")],models:[{id:"embed",fields:[{component:"aem-content",name:"link",label:"Embed URL"}]}],filters:[]})}]});import{existsSync as uc}from"fs";import{mkdir as fc,writeFile as gc}from"fs/promises";import Hi from"path";function zi(e){return st.find(t=>t.id===e)}function Wi(e){let t=new Set,n=o=>{if(t.has(o))return;let i=zi(o);if(i){for(let a of i.deps??[])n(a);t.add(o)}};for(let o of e)n(o);return st.filter(o=>t.has(o.id)).map(o=>o.id)}function hc(e){return`// scripts/utils.js - common EDS helpers (generated by \`eds scaffold helpers\`).
|
|
225
225
|
|
|
226
|
-
${
|
|
226
|
+
${Wi(e).map(o=>zi(o)).filter(o=>!!o).map(o=>o.code).join(`
|
|
227
227
|
|
|
228
228
|
`)}
|
|
229
|
-
`}async function
|
|
229
|
+
`}async function Ji(e,t=Pn){let n=Wi(t),o=Hi.join(e,"scripts","utils.js");return uc(o)?{path:Gi,created:!1,helpers:n}:(await fc(Hi.dirname(o),{recursive:!0}),await gc(o,hc(t)),{path:Gi,created:!0,helpers:n})}var Gi,st,Pn,qi=k(()=>{"use strict";f();Gi="scripts/utils.js",st=[{id:"getMetadata",label:"getMetadata (read a page meta value)",code:`/**
|
|
230
230
|
* Reads a page metadata value by name (meta[name] or meta[property]).
|
|
231
231
|
* @param {string} name The metadata name.
|
|
232
232
|
* @returns {string} The value, or an empty string.
|
|
@@ -323,8 +323,8 @@ export function isUEPreview() {
|
|
|
323
323
|
*/
|
|
324
324
|
export function isUE() {
|
|
325
325
|
return isUEEdit() || isUEPreview();
|
|
326
|
-
}`}],
|
|
327
|
-
`}function
|
|
326
|
+
}`}],Pn=st.map(e=>e.id)});function wc(){return[{component:"tab",name:"basics",label:"Basics"},{component:"text",valueType:"string",name:"text",label:"Text (single line)"},{component:"textarea",valueType:"string",name:"textarea",label:"Textarea (multi-line)"},{component:"richtext",valueType:"string",name:"richtext",value:"",label:"Rich text"},{component:"number",valueType:"number",name:"number",label:"Number"},{component:"boolean",valueType:"boolean",name:"boolean",value:!1,label:"Boolean"},{component:"date-time",valueType:"date",name:"date",label:"Date / time"},{component:"tab",name:"selection",label:"Selection"},{component:"select",valueType:"string",name:"select",label:"Select",value:"a",options:[{name:"Option A",value:"a"},{name:"Option B",value:"b"}]},{component:"radio-group",valueType:"string",name:"radio",label:"Radio group",value:"x",options:[{name:"X",value:"x"},{name:"Y",value:"y"}]},{component:"multiselect",valueType:"string",name:"classes",label:"Multiselect (CSS classes)",options:[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"}]},{component:"checkbox-group",valueType:"string[]",name:"toggles",label:"Checkbox group",options:[{name:"Show title",value:"show-title"},{name:"Show image",value:"show-image"}]},{component:"tab",name:"media",label:"Media & content"},{component:"reference",valueType:"string",name:"image",label:"Image (DAM asset)"},{component:"text",valueType:"string",name:"imageAlt",label:"Image alt"},{component:"aem-content",name:"link",label:"Link (page / URL)"},{component:"aem-content-fragment",name:"contentFragment",label:"Content Fragment"},{component:"aem-experience-fragment",name:"experienceFragment",label:"Experience Fragment"},{component:"aem-tag",valueType:"string",name:"tags",label:"Tags"},{component:"tab",name:"repeatable",label:"Multifield"},{component:"container",name:"items",label:"Items (repeatable)",multi:!0,collapsible:!0,fields:[{component:"text",valueType:"string",name:"itemTitle",label:"Title"},{component:"richtext",valueType:"string",name:"itemText",value:"",label:"Text"},{component:"aem-content",name:"itemLink",label:"Link"}]}]}function En(){let e={definitions:[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],models:[{id:"field-reference",fields:wc()}],filters:[]};return`${JSON.stringify(e,null,2)}
|
|
327
|
+
`}function Cn(e,t){let n=new Set(e.map(o=>o.id));return[...e,...t.filter(o=>!n.has(o.id))]}function Qi(e,t,n){let o=e?.groups?[...e.groups]:[],i=(a,s,d)=>{let l=o.find(c=>c.id===a);l||(l={id:a,title:s,components:[]},o.push(l)),l.components=Cn(l.components,d)};return i("default","Default Content",t),i("blocks","Blocks",n),{groups:o}}function ct(e,t){let n=e?[...e]:[],o=n.find(i=>i.id==="section");return o||(o={id:"section",components:["text","image","button","title"]},n.push(o)),o.components=[...new Set([...o.components,...t])],n}var Ki,Xi,Vi,Yi,An=k(()=>{"use strict";f();Ki=[{title:"Text",id:"text",plugins:{xwalk:{page:{resourceType:"core/franklin/components/text/v1/text",template:{text:"<p>Text</p>"}}}}},{title:"Image",id:"image",plugins:{xwalk:{page:{resourceType:"core/franklin/components/image/v1/image",template:{image:"",imageAlt:""}}}}},{title:"Button",id:"button",plugins:{xwalk:{page:{resourceType:"core/franklin/components/button/v1/button",template:{text:"Button",href:"",type:""}}}}},{title:"Title",id:"title",plugins:{xwalk:{page:{resourceType:"core/franklin/components/title/v1/title",template:{title:"Title",type:"h2"}}}}}],Xi=[{id:"title",fields:[{component:"text",valueType:"string",name:"title",label:"Title"},{component:"select",valueType:"string",name:"type",label:"Type",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}]}]},{id:"image",fields:[{component:"reference",valueType:"string",name:"image",label:"Image",multi:!1},{component:"text",valueType:"string",name:"imageAlt",label:"Alt Text"}]},{id:"button",fields:[{component:"text",valueType:"string",name:"text",label:"Text"},{component:"aem-content",name:"href",label:"Link"},{component:"select",valueType:"string",name:"type",label:"Type",options:[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}]}]}];Vi=`// Block: field-reference
|
|
328
328
|
// A living reference of every Universal Editor field type (see _field-reference.json).
|
|
329
329
|
// Authors use it to see what's available; delete it before launch.
|
|
330
330
|
export default function decorate(block) {
|
|
@@ -333,44 +333,44 @@ export default function decorate(block) {
|
|
|
333
333
|
// are what you drop and edit.
|
|
334
334
|
block.classList.add('field-reference');
|
|
335
335
|
}
|
|
336
|
-
`,
|
|
336
|
+
`,Yi=`/* Block: field-reference */
|
|
337
337
|
.field-reference {
|
|
338
338
|
display: grid;
|
|
339
339
|
gap: var(--spacing-m, 16px);
|
|
340
340
|
padding: var(--spacing-l, 32px) 0;
|
|
341
341
|
}
|
|
342
|
-
`});var
|
|
343
|
-
`)}async function
|
|
344
|
-
`),!0}catch{return!1}}async function
|
|
345
|
-
`).filter(Boolean):[]}}catch(o){
|
|
342
|
+
`});var me={};O(me,{scaffoldBlocks:()=>tr,scaffoldCi:()=>nr,scaffoldEnv:()=>ir,scaffoldHelpers:()=>or,scaffoldInteractive:()=>yc,scaffoldUe:()=>zt,scaffoldXwalk:()=>rr});import{existsSync as Zi}from"fs";import{mkdir as er,readFile as bc,writeFile as Ae}from"fs/promises";import oe from"path";async function Ht(e){if(!Zi(e))return null;try{return JSON.parse(await bc(e,"utf-8"))}catch{return null}}async function Gt(e,t){await Ae(e,`${JSON.stringify(t,null,2)}
|
|
343
|
+
`)}async function zt(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - Universal Editor"));let t=[],n=oe.join(e,"blocks","field-reference");await er(n,{recursive:!0}),await Ae(oe.join(n,"field-reference.js"),Vi),await Ae(oe.join(n,"field-reference.css"),Yi),await Ae(oe.join(n,"_field-reference.json"),En()),t.push("blocks/field-reference/ (all 17 fields + multifield)");let o=oe.join(e,"component-definition.json"),i=oe.join(e,"component-models.json"),a=oe.join(e,"component-filters.json"),s=[{title:"Field Reference",id:"field-reference",plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:"Field Reference",model:"field-reference"}}}}}],d=Qi(await Ht(o),Ki,s);await Gt(o,d),t.push("component-definition.json (default content + field-reference)");let l=await Ht(i)??[],c=JSON.parse(En()).models[0],m=Cn(l,[...Xi,c]);await Gt(i,m),t.push("component-models.json (title / image / button / field-reference)");let p=ct(await Ht(a),["field-reference"]);await Gt(a,p),t.push("component-filters.json (section filter)"),r.info(S("Created / merged"));let u=t.map(h=>h.split(" ")[0]),g=I(u);for(let h of t){let[b,...w]=h.split(" ");r.info(j(b,w.join(" ").replace(/^\((.*)\)$/,"$1"),g))}r.info(""),r.info(N(["Universal Editor scaffold ready"]))}async function tr(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold \u2014 standard blocks"));let n;if(e?.length){n=e.map(c=>Sn(c.trim())).filter(c=>!!c);let l=e.filter(c=>!Sn(c.trim()));l.length&&r.warn(`Unknown block(s): ${l.join(", ")}. Available: ${Ce.map(c=>c.id).join(", ")}`)}else n=Ce;let o=[],i=[];for(let l of n){let c=oe.join(t,"blocks",l.id);if(Zi(c)){i.push(l.id);continue}await er(c,{recursive:!0}),await Ae(oe.join(c,`${l.id}.js`),l.js),await Ae(oe.join(c,`${l.id}.css`),l.css),await Ae(oe.join(c,`_${l.id}.json`),l.model),o.push(l.id)}let a=oe.join(t,"component-filters.json"),s=ct(await Ht(a),n.map(l=>l.id));await Gt(a,s),r.info(S("Blocks"));let d=I([...o,...i,"component-filters"]);for(let l of o)r.info(j(l,"created",d));for(let l of i)r.info(A("warn",l,"already exists \u2014 skipped",d));r.info(""),r.info(N([`${o.length} block(s) scaffolded + registered`]))}async function nr(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - CI workflow"));let t=await Mt(e);r.info(S("GitHub Actions")),t.created?r.info(j(t.path,"doctor + audit loading + audit security + lint/build")):r.info(A("warn",t.path,"already exists - skipped")),r.info(""),r.info(N([t.created?"CI workflow scaffolded - commit it and it runs on every PR":"CI workflow left untouched"]))}async function or(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - helpers"));let n=e?.length?e:void 0;if(!n)if(process.stdout.isTTY){let{checkbox:i}=await Promise.resolve().then(()=>(G(),H));n=await i({message:"Which helpers?",choices:st.map(a=>({name:a.label,value:a.id,checked:!0}))})}else n=Pn;if(!n.length){r.info("Nothing selected.");return}let o=await Ji(t,n);r.info(S("Helpers")),o.created?r.info(j(o.path,o.helpers.join(", "))):r.info(A("warn",o.path,"already exists - skipped")),r.info(""),r.info(N([o.created?`${o.helpers.length} helper(s) -> scripts/utils.js`:"Helpers left untouched"]))}async function ir(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - .env"));let n=e.pagesUrl;if(n===void 0)try{let{execa:s}=await import("execa"),d=await s("git",["remote","get-url","origin"],{cwd:t}),l=He(d.stdout.trim());n=l?`https://${Ge(l.owner,l.repo)}`:""}catch{n=""}let o=e.open??"/",i=e.port??"3007";if(!e.yes&&process.stdout.isTTY){let{input:s}=await Promise.resolve().then(()=>(G(),H));o=await s({message:"AEM_OPEN (path opened on start)",default:o}),i=await s({message:"AEM_PORT",default:String(i)}),n=await s({message:"AEM_PAGES_URL (content origin)",default:n})}let a=await It(t,{open:o,port:i,pagesUrl:n});r.info(S(".env")),a.created?r.info(j(a.path,`AEM_OPEN=${o} AEM_PORT=${i}`)):r.info(A("warn",a.path,"already exists - left untouched")),a.gitignoreUpdated&&r.info(j(".gitignore","added .env")),r.info(""),r.info(N([a.created?".env ready for `aem up`":".env left untouched"]))}async function rr(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Scaffold - xwalk.json"));let t=await Ut(e);r.info(S("xwalk.json")),t.created?r.info(j(t.path,"multi-field enabled")):r.info(A("warn",t.path,"already exists - left untouched")),r.info(""),r.info(N([t.created?"xwalk.json ready (UE multi-field)":"xwalk.json left untouched"]))}async function yc(){let{select:e,checkbox:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(C("Scaffold"));let n=await e({message:"What do you want to scaffold?",choices:[{name:"Universal Editor config + field-reference (all 17 field types)",value:"ue"},{name:"Standard blocks (hero, cards, columns, accordion, embed)",value:"blocks"},{name:"GitHub Actions CI (doctor + audits + lint/build)",value:"ci"},{name:"Helper functions (scripts/utils.js)",value:"helpers"},{name:"Local-dev .env (aem up: port / open / pages URL)",value:"env"},{name:"xwalk.json (enable Universal Editor multi-field)",value:"xwalk"},{name:"UE config + standard blocks",value:"both"}]});if(n==="env")return ir();if(n==="xwalk")return rr();if((n==="ue"||n==="both")&&await zt(),n==="blocks"||n==="both"){let o=await t({message:"Which blocks?",choices:Ce.map(i=>({name:i.title,value:i.id,checked:!0}))});await tr(o)}n==="ci"&&await nr(),n==="helpers"&&await or()}var ce=k(()=>{"use strict";f();R();z();jn();vn();kn();qi();An();xn();Bt();M()});var Jt={};O(Jt,{initProject:()=>Sc});import{existsSync as Rn}from"fs";import{readFile as Fn,writeFile as ar}from"fs/promises";import Wt from"path";import Tn from"chalk";async function vc(e){try{let{execa:t}=await import("execa"),n=await t("git",["remote","get-url","origin"],{cwd:e}),o=He(n.stdout.trim());return o?`https://${Ge(o.owner,o.repo)}`:""}catch{return""}}async function kc(e,t){let n=Wt.join(e,"package.json");if(!Rn(n))return!1;try{let o=JSON.parse(await Fn(n,"utf-8"));return o.name=t,await ar(n,`${JSON.stringify(o,null,2)}
|
|
344
|
+
`),!0}catch{return!1}}async function xc(e,t){let n=[];for(let o of["README.md","index.html","head.html"]){let i=Wt.join(e,o);if(Rn(i))try{let a=await Fn(i,"utf-8"),s=a.replace(/aem-boilerplate/gi,t);s!==a&&(await ar(i,s),n.push(o))}catch{}}return n}async function $c(e){let{confirm:t}=await Promise.resolve().then(()=>(G(),H)),n=[{title:"Install the AEM Code Sync GitHub app",url:"https://github.com/apps/aem-code-sync/installations/new",note:"Connects your repo to the Edge Delivery pipeline (preview/publish)."}];e==="gdrive"&&n.push({title:"Share your content folder",note:"Share the Google Drive folder with the AEM service and set it as the mountpoint."}),e==="sharepoint"&&n.push({title:"Share your content folder",note:"Grant the SharePoint/OneDrive folder to the AEM service account."}),e==="da"&&n.push({title:"Author in DA",url:"https://da.live",note:"Create documents at da.live."}),e==="ue"&&n.push({title:"Open the Universal Editor",url:"https://experience.adobe.com",note:"Author in-context once the repo is connected to AEM."}),n.push({title:"Install the AEM Sidekick extension",url:"https://chromewebstore.google.com/detail/aem-sidekick/igkmdomcgoebiipaifhmpfjhbjccggml",note:"Preview and publish from the browser."}),n.push({title:"Run the local dev server",note:"npm install, then `aem up` (from @adobe/aem-cli)."}),r.info(S("Next steps (outside the repo)"));for(let o=0;o<n.length;o++){let i=n[o];r.info(` ${U.accent(String(o+1))} ${Tn.bold(i.title)}`),i.url&&r.info(` ${Tn.cyan(i.url)}`),r.info(` ${Tn.dim(i.note)}`),await t({message:" Done / skip?",default:!0})}}async function Sc(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found). Clone an EDS boilerplate first, then run this from its root."),process.exitCode=1;return}await r.logoOnceAnimated("Project setup");let{input:n,select:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!e.yes,s=Wt.basename(t),d=Wt.join(t,"package.json");if(Rn(d))try{s=JSON.parse(await Fn(d,"utf-8")).name||s}catch{}let l=e.name&<(e.name)||lt(await n({message:"1/4 Project name",default:lt(s),validate:b=>!!lt(b)||"Use letters, numbers and dashes"})),c=e.authoring??await o({message:"2/4 Authoring model",choices:[{name:Ee.ue,value:"ue"},{name:Ee.da,value:"da"},{name:Ee.gdrive,value:"gdrive"},{name:Ee.sharepoint,value:"sharepoint"}]}),m=e.mountpoint;if(_t(c)&&!m)if(c==="da"&&(e.org||a)){let b=e.org??await n({message:" DA org",validate:y=>!!y.trim()||"Required"}),w=e.site??(a?await n({message:" DA site",default:l}):l);m=Oi(b.trim(),lt(w))}else c!=="da"&&a&&(m=(await n({message:` ${c==="gdrive"?"Google Drive folder URL":"SharePoint folder URL"}`,validate:w=>/^https?:\/\//.test(w.trim())||"Paste the folder URL"})).trim());let p=e.ci??(a?await i({message:"4/4 Add GitHub Actions CI (audits gatekeeper)?",default:!0}):!0);r.info(S("Summary"));let u=I(["name","authoring","mountpoint","ci"]);if(r.info(j("name",l,u)),r.info(j("authoring",Ee[c],u)),m?r.info(j("mountpoint",m,u)):_t(c)&&r.info(j("mountpoint","(skipped - set it in fstab.yaml later)",u)),r.info(j("ci",p?"yes":"no",u)),r.info(""),a&&!await i({message:"Apply this setup?",default:!0})){r.info("Cancelled.");return}let g=[];await kc(t,l)&&g.push("package.json (name)");for(let b of await xc(t,l))g.push(`${b} (renamed)`);if(_t(c)&&m&&g.push(await Ni(t,m)),c==="ue"&&(await zt(),g.push(await Mi(t,l))),p){let b=await Mt(t);g.push(b.created?b.path:`${b.path} (exists, skipped)`)}if(e.env!==!1){let b=await It(t,{pagesUrl:await vc(t)});g.push(b.created?".env (aem up config)":".env (exists, skipped)")}if(e.xwalk!==!1&&c==="ue"){let b=await Ut(t);g.push(b.created?`${b.path} (UE multi-field)`:`${b.path} (exists, skipped)`)}r.info(S("Configured"));let h=I(g.map(b=>b.split(" ")[0]));for(let b of g){let[w,...y]=b.split(" ");r.info(j(w,y.join(" ").replace(/^\((.*)\)$/,"$1"),h))}r.info(""),a&&await $c(c),r.info(N([`"${l}" set up for ${Ee[c]}`]))}var lt,qt=k(()=>{"use strict";f();R();z();vn();kn();Ii();xn();Bt();M();ce();lt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});var Te={};O(Te,{sandboxList:()=>Rc,sandboxLogin:()=>Cc,sandboxLogout:()=>Ac,sandboxNew:()=>Tc,sandboxRm:()=>Fc});import jc from"path";import ee from"chalk";async function pe(e,t,n={}){let{execa:o}=await import("execa");return((await o(e,t,n)).stdout??"").toString().trim()}async function Dn(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{await pe(t,[e],{stdio:"ignore"})}catch{}}async function Pc(){try{return await pe("gh",["auth","status"]),await pe("gh",["api","user","-q",".login"])}catch{return null}}async function Ln(){let e=await bi();if(e)try{return{mode:"api",token:e,login:await Lt(e)}}catch{}let t=await Pc();return t?{mode:"gh",login:t}:null}async function Ec(e,t,n){if(e.mode==="api")return li(e.token,t,n);try{return await pe("gh",["repo","view",`${t}/${n}`,"--json","name"]),!0}catch{return!1}}function On(){r.error("Not authenticated with GitHub."),r.info(" Run `eds sandbox login` to authorize GitHub, or install + `gh auth login`."),process.exitCode=1}async function Cc(){await r.logoOnceAnimated("Sandbox - GitHub login");let{input:e}=await Promise.resolve().then(()=>(G(),H));if(Ot){let n=await vi(["repo","delete_repo"]);r.info(S("Authorize GitHub")),r.info(j("code",n.user_code)),r.info(j("open",n.verification_uri)),r.info(""),await Dn(n.verification_uri),r.info(ee.dim(" Waiting for you to authorize in the browser..."));try{let o=await ki(n.device_code,n.interval,n.expires_in);await hn(o),r.success(`Authorized as ${await Lt(o)}.`)}catch(o){r.error(`Device flow failed: ${o.message}`),process.exitCode=1}return}r.info(S("Authorize GitHub (least-privilege token)")),r.info(" Create a fine-grained token limited to your sandboxes only:"),r.info(` ${ee.cyan("https://github.com/settings/personal-access-tokens/new")}`),r.info(ee.dim(" - Resource owner: a dedicated sandbox org (recommended) or your account")),r.info(ee.dim(" - Repository access: All repositories in that org (to create new sandboxes),")),r.info(ee.dim(" or Only select repositories to manage existing ones")),r.info(ee.dim(" - Permissions: Administration = Read and write, Contents = Read and write,")),r.info(ee.dim(" Metadata = Read. Set a short expiry.")),r.info(ee.dim(" Tip: `eds sandbox new --org <sandbox-org>` so nothing in your personal account is touched.")),r.info(""),await(await Promise.resolve().then(()=>(G(),H))).confirm({message:"Open the token page?",default:!0})&&await Dn("https://github.com/settings/personal-access-tokens/new");let t=(await e({message:"Paste the token",validate:n=>!!n.trim()||"Required"})).trim();try{let n=await Lt(t);await hn(t),r.success(`Authorized as ${n}.`)}catch{r.error("That token didn't work (check the scopes)."),process.exitCode=1}}async function Ac(){await yi(),r.success("Signed out (stored GitHub token removed).")}async function Tc(e,t={}){let n=await Ln();if(!n)return On();await r.logoOnceAnimated("Sandbox");let o=!t.yes,{select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=t.boilerplate;s||(t.ue?s=it.ue:o?s=await i({message:"Which boilerplate?",choices:[{name:"Document Authoring (adobe/aem-boilerplate)",value:it.document},{name:"Universal Editor / crosswalk (adobe/aem-boilerplate-xwalk)",value:it.ue}]}):s=it.document);let d=t.private??!1;t.private===void 0&&o&&(d=await i({message:"Visibility?",choices:[{name:"Public",value:!1},{name:"Private",value:!0}],default:!1}));let l=t.org??n.login;if(await Ec(n,l,e)){r.error(`A repository ${l}/${e} already exists - refusing to touch it.`),r.info(ee.dim(" Pick another name, or remove it first (e.g. `eds sandbox rm` for a sandbox).")),process.exitCode=1;return}r.info(S("Creating sandbox",`${l}/${e} \xB7 ${s}`));try{if(n.mode==="api"){let c=await di(n.token,s,{owner:l,name:e,private:d});await mi(n.token,l,e,[Ue]),r.info(ee.dim(" Cloning...")),await pe("git",["clone",c.cloneUrl,e],{stdio:"inherit"})}else{let c=t.org?`${t.org}/${e}`:e;await pe("gh",$i(c,{template:s,private:d,clone:!0}),{stdio:"inherit"});try{await pe("gh",["repo","edit",`${l}/${e}`,"--add-topic",Ue])}catch{}}}catch(c){r.error(`Create failed: ${c.message}`),process.exitCode=1;return}if(r.info(""),r.info(S("Sandbox ready")),r.info(j("repo",`https://github.com/${l}/${e}`)),r.info(j("preview",wn(l,e))),r.info(""),o){if(await a({message:"Open the AEM Code Sync install page now?",default:!0})&&await Dn(bn()),await a({message:`Configure authoring now (eds init in ./${e})?`,default:!0})){let c=process.cwd();try{process.chdir(jc.join(c,e));let{initProject:m}=await Promise.resolve().then(()=>(qt(),Jt));await m({})}finally{process.chdir(c)}}}else r.info(ee.dim(` Install AEM Code Sync: ${bn()}`)),r.info(ee.dim(` Configure authoring: cd ${e} && eds init`));r.info(""),r.info(N([`Sandbox "${e}" ready - tear down with \`eds sandbox rm ${e}\``]))}async function Rc(){let e=await Ln();if(!e)return On();let t=[];try{if(e.mode==="api")t=await ui(e.token,e.login,Ue);else{let o=await pe("gh",["repo","list","--topic",Ue,"--limit","100","--json","nameWithOwner","-q",".[].nameWithOwner"]);t=o?o.split(`
|
|
345
|
+
`).filter(Boolean):[]}}catch(o){r.error(`List failed: ${o.message}`),process.exitCode=1;return}if(r.info(S("Sandboxes",`${t.length} tagged ${Ue}`)),t.length===0){r.info(ee.dim(" None yet. Create one with `eds sandbox new <name>`."));return}let n=I(t);for(let o of t){let[i,a]=o.split("/");r.info(j(o,wn(i,a),n))}}async function Fc(e,t={}){let n=await Ln();if(!n)return On();let o=t.org??n.login,i=`${o}/${e}`;if(!t.yes){let{confirm:a}=await Promise.resolve().then(()=>(G(),H));if(!await a({message:`Permanently delete ${i}? This cannot be undone.`,default:!1})){r.info("Cancelled.");return}}try{n.mode==="api"?await pi(n.token,o,e):await pe("gh",["repo","delete",i,"--yes"])}catch(a){r.error(`Delete failed: ${a.message}`),r.info(ee.dim(" Deleting needs the delete_repo scope (re-run `eds sandbox login`, or `gh auth refresh -s delete_repo`).")),process.exitCode=1;return}r.info(S("Deleted")),r.info(j(i,"removed"))}var Re=k(()=>{"use strict";f();R();fi();xi();Si();M()});import{existsSync as Dc}from"fs";import{readFile as Lc}from"fs/promises";import Oc from"path";import{parse as Nc}from"yaml";async function sr(e){let t=Oc.join(e,"fstab.yaml");if(Dc(t))try{let o=(Nc(await Lc(t,"utf-8"))??{}).mountpoints?.["/"],i=typeof o=="string"?o:o?.url??"",a=i.match(/content\.da\.live\/([^/]+)\/([^/]+)/);return a?{model:"da",org:a[1],site:a[2],mountpoint:i}:/drive\.google\.com/.test(i)?{model:"gdrive",mountpoint:i}:/sharepoint\.com|-my\.sharepoint/.test(i)?{model:"sharepoint",mountpoint:i}:{model:"document",mountpoint:i}}catch{}return{model:"ue"}}var cr=k(()=>{"use strict";f()});function Mc(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://admin.da.live/source/${e}/${t}/${o}.html`}function lr(e,t,n){let o=n.replace(/^\/+/,"").replace(/\.html$/i,"");return`https://da.live/edit#/${e}/${t}/${o}`}async function dr(e,t,n,o,i){let a=Mc(e,t,n),s=new FormData;s.append("data",new Blob([o],{type:"text/html"}),"content.html");let d={};i&&(d.Authorization=`Bearer ${i}`);let l=await fetch(a,{method:"POST",body:s,headers:d});if(!l.ok)throw new Error(`DA push failed: ${l.status} ${l.statusText}`);return a}var mr=k(()=>{"use strict";f()});function Ic(e){return` <div class="${e}">
|
|
346
346
|
<div>
|
|
347
347
|
<div>${e} content</div>
|
|
348
348
|
</div>
|
|
349
|
-
</div>`}function
|
|
349
|
+
</div>`}function _c(e){let t=[` <div><div>Title</div><div>${e.title}</div></div>`,` <div><div>Description</div><div>${e.description??""}</div></div>`];return e.area&&t.push(` <div><div>Template</div><div>${e.area}</div></div>`),` <div class="metadata">
|
|
350
350
|
${t.join(`
|
|
351
351
|
`)}
|
|
352
|
-
</div>`}function
|
|
352
|
+
</div>`}function pr(e){let t=e.blocks??[],n=` <div>
|
|
353
353
|
<h1>${e.title}</h1>
|
|
354
354
|
<p>${e.description??"Intro copy goes here."}</p>
|
|
355
355
|
</div>`,o=t.map(a=>` <div>
|
|
356
|
-
${
|
|
357
|
-
</div>`),
|
|
358
|
-
${
|
|
356
|
+
${Ic(a)}
|
|
357
|
+
</div>`),i=` <div>
|
|
358
|
+
${_c(e)}
|
|
359
359
|
</div>`;return`<body>
|
|
360
360
|
<header></header>
|
|
361
361
|
<main>
|
|
362
|
-
${[n,...o,
|
|
362
|
+
${[n,...o,i].join(`
|
|
363
363
|
`)}
|
|
364
364
|
</main>
|
|
365
365
|
<footer></footer>
|
|
366
366
|
</body>
|
|
367
|
-
`}var
|
|
368
|
-
`}var
|
|
369
|
-
`),!0}async function
|
|
370
|
-
`).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let
|
|
367
|
+
`}var ur=k(()=>{"use strict";f()});import{existsSync as Uc}from"fs";import{readFile as Bc}from"fs/promises";import Hc from"path";function Gc(e){if(e.value!==void 0)return e.value;switch(e.valueType){case"boolean":return!1;case"number":return 0;case"string[]":return[];default:return""}}async function zc(e,t){let n=Hc.join(e,"blocks",t,`_${t}.json`);if(!Uc(n))return{};try{let o=JSON.parse(await Bc(n,"utf-8")),i=Array.isArray(o.models)?o.models:[],s=(i.find(l=>l.id===t)??i[0])?.fields??[],d={};for(let l of s)l.component!=="tab"&&(d[l.name]=l.component==="container"?[]:Gc(l));return d}catch{return{}}}async function fr(e,t){let n=[];for(let i of t.blocks)n.push({name:i,model:i,fields:await zc(e,i)});let o={title:t.title,template:t.name,components:n};return`${JSON.stringify(o,null,2)}
|
|
368
|
+
`}var gr=k(()=>{"use strict";f()});var In={};O(In,{templateNew:()=>Yc});import{existsSync as Mn}from"fs";import{mkdir as Wc,readFile as hr,readdir as Jc,writeFile as Nn}from"fs/promises";import we from"path";import dt from"chalk";async function Kc(e){let t=we.join(e,"blocks");return Mn(t)?(await Jc(t,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name):[]}async function Xc(e){let t=we.join(e,".edsrc.json");if(!Mn(t))return{};try{return JSON.parse(await hr(t,"utf-8")).admin??{}}catch{return{}}}async function Vc(e,t){if(!t.length)return!1;let n=we.join(e,"component-filters.json"),o=null;if(Mn(n))try{o=JSON.parse(await hr(n,"utf-8"))}catch{o=null}let i=ct(o,t);return await Nn(n,`${JSON.stringify(i,null,2)}
|
|
369
|
+
`),!0}async function Yc(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Page template");let{input:o,select:i,confirm:a}=await Promise.resolve().then(()=>(G(),H)),s=!t.yes,d=await sr(n),l=t.authoring??d.model,c=qc(e),m=t.title??(s?await o({message:"Page title",default:e}):e),p=t.description??(s?await o({message:"Description (optional)"}):""),u=t.path??`/templates/${c}`,g=t.blocks;if(!g&&s){let y=await Kc(n),v=y.length?y:Ce.map(J=>J.id),T=[],K=!0;for(;K;){let J=await i({message:`Add a block in order (${T.length} so far)`,choices:[...v.map(Se=>({name:Se,value:Se})),{name:T.length?"- done -":"- done (empty page) -",value:"__done"}]});J==="__done"?K=!1:T.push(J)}g=T}let h=g??[],b=pr({title:m,description:p||void 0,blocks:h,area:t.area}),w=we.join("templates",`${c}.html`);if(await Wc(we.join(n,"templates"),{recursive:!0}),await Nn(we.join(n,w),b),r.info(S("Page template",`${u} \xB7 ${l}`)),r.info(j(w,`${h.length} block(s) + metadata`)),l==="da"){let y=await Xc(n),v=t.org??y.org??d.org,T=t.site??y.site??d.site;if(t.push??(s?await a({message:"Push to DA (da.live)?",default:!0}):!0))if(!v||!T)r.warn("No DA org/site. Pass --org/--site or set admin in .edsrc.json.");else try{await dr(v,T,u,b,process.env.DA_TOKEN),r.info(j("pushed to DA",lr(v,T,u)))}catch(J){r.error(`DA push failed: ${J.message}`),r.info(dt.dim(" Open projects allow anonymous writes; others need DA_TOKEN."))}}else if(l==="gdrive"||l==="sharepoint"){let y=l==="gdrive"?"a Google Doc":"a Word doc";r.info(""),r.info(dt.dim(` Document model: import ${w} into ${y} in your mounted folder,`)),r.info(dt.dim(" then preview/publish. (Share the folder + install aem-code-sync first.)"))}else if(l==="ue"){let y=we.join("templates",`${c}.json`);await Nn(we.join(n,y),await fr(n,{title:m,name:c,blocks:h})),r.info(j(y,`initial content (${h.length} component(s), in order)`)),await Vc(n,h)&&r.info(j("component-filters.json","seeded blocks allowed in Universal Editor")),r.info(""),r.info(dt.dim(" Universal Editor: use the template JSON as the page's initial content, then")),r.info(dt.dim(" author it in the Universal Editor (wire the repo to AEM)."))}r.info(""),r.info(N([`"${c}" template (${l}) - preview with \`eds preview ${u}\``]))}var qc,_n=k(()=>{"use strict";f();R();z();jn();An();cr();mr();ur();gr();M();qc=e=>e.trim().toLowerCase().replace(/[^a-z0-9-/]+/g,"-").replace(/^-+|-+$/g,"")});import{existsSync as Kt}from"fs";import{readFile as wr,readdir as br}from"fs/promises";import Fe from"path";async function Qc(e){let t=[],n=async o=>{for(let i of await br(o,{withFileTypes:!0})){let a=Fe.join(o,i.name);i.isDirectory()?await n(a):t.push(a)}};return Kt(e)&&await n(e),t}async function yr(e){if(!Kt(e))return null;let t=await br(e,{withFileTypes:!0}),n=t.find(i=>i.isDirectory()&&/clientlib/i.test(i.name));return n?Fe.join(e,n.name):t.some(i=>i.isFile()&&i.name.endsWith(".css"))?e:null}async function vr(e){let t=await Qc(e),n=t.filter(s=>/\.(less|scss|sass)$/i.test(s)).map(s=>Fe.relative(e,s)),o,i=Fe.join(e,"css.txt");if(Kt(i)){let s=(await wr(i,"utf-8")).split(`
|
|
370
|
+
`).map(c=>c.trim()),d=e,l=[];for(let c of s){if(!c)continue;let m=c.match(/^#base\s*=\s*(.+)$/);m?d=Fe.join(e,m[1].trim()):c.startsWith("#")||l.push(c)}o=l.map(c=>Fe.join(d,c)).filter(c=>Kt(c)&&c.endsWith(".css"))}else o=t.filter(s=>s.endsWith(".css"));let a=[];for(let s of o)a.push(await wr(s,"utf-8"));return{css:a.join(`
|
|
371
371
|
|
|
372
|
-
`),files:o.map(s=>
|
|
373
|
-
`}function
|
|
372
|
+
`),files:o.map(s=>Fe.relative(e,s)),preprocessed:n}}var kr=k(()=>{"use strict";f()});import{XMLParser as Zc}from"fast-xml-parser";function mt(e){return Object.keys(e).find(t=>t!==":@")??""}function be(e){let t=mt(e),n=e[t];return Array.isArray(n)?n:[]}function el(e){return e[":@"]??{}}function tl(e){return typeof e=="string"?e.replace(/^\{[^}]+\}/,""):e}function Q(e,t){return tl(el(e)[`@_${t}`])}function nl(e,t){let n=Q(t,"multiple")==="true"||Q(t,"multiple")==="{Boolean}true";return e.endsWith("/form/textfield")?"text":e.endsWith("/form/textarea")?"textarea":e.includes("/richtext")?"richtext":e.endsWith("/form/numberfield")?"number":e.endsWith("/form/checkbox")?"boolean":e.endsWith("/form/radiogroup")?"radio-group":e.endsWith("/form/select")?n?"multiselect":"select":e.endsWith("/form/datepicker")?"date-time":e.endsWith("/form/pathfield")||e.endsWith("/form/pathbrowser")?"aem-content":e.includes("/fileupload")||e.endsWith("/form/fileupload")?"reference":e.includes("tagfield")||e.includes("tagpicker")||e.includes("tagbrowser")?"aem-tag":e.includes("contentfragment")?"aem-content-fragment":e.includes("experiencefragment")?"aem-experience-fragment":null}function ol(e){return e.includes("/foundation/container")||e.includes("/foundation/fixedcolumns")||e.includes("/foundation/well")||e.includes("/foundation/tabs")||e.includes("/foundation/form/fieldset")||e.includes("/foundation/accordion")}function il(e){switch(e){case"number":return"number";case"boolean":return"boolean";case"date-time":return"date";case"checkbox-group":return"string[]";case"aem-content":case"aem-content-fragment":case"aem-experience-fragment":return;default:return"string"}}function Un(e,t){return(e??"").replace(/^\.\//,"").trim()||t}function rl(e){let t=be(e).find(n=>mt(n)==="items");return t?be(t).map(n=>{let o=Q(n,"value")??"";return{name:Q(n,"text")??Q(n,"jcr:title")??o,value:o}}):[]}function Xt(e,t,n,o){for(let i of e){let a=Q(i,"sling:resourceType")??"";if(a.endsWith("/foundation/tabs")){let d=be(i).find(l=>mt(l)==="items");for(let l of d?be(d):[]){let c=Q(l,"jcr:title");t.push({component:"tab",name:Un(void 0,mt(l)),label:c}),Xt(be(l),t,n,o)}continue}if(a.endsWith("/form/multifield")){let d=[];Xt(be(i),d,n,o);let l=Un(Q(i,"name"),`items${o.i++}`);t.push({component:"container",name:l,label:Q(i,"fieldLabel")??"Items",multi:!0,collapsible:!0,fields:d});continue}let s=a?nl(a,i):null;if(s){let d=Un(Q(i,"name"),`field${o.i++}`),l={component:s,name:d},c=il(s);c&&(l.valueType=c);let m=Q(i,"fieldLabel")??Q(i,"text");if(m&&(l.label=m),s==="select"||s==="radio-group"||s==="multiselect"){let u=rl(i);u.length&&(l.options=u)}let p=Q(i,"value")??(s==="boolean"?Q(i,"checked"):void 0);p!==void 0&&p!==""&&(l.value=s==="boolean"?p==="true":p),t.push(l);continue}a&&Q(i,"name")&&!ol(a)&&n.add(a),Xt(be(i),t,n,o)}}function xr(e){let o=new Zc({ignoreAttributes:!1,attributeNamePrefix:"@_",preserveOrder:!0,removeNSPrefix:!1,trimValues:!0}).parse(e).find(s=>mt(s)==="jcr:root"),i=[],a=new Set;return o&&Xt(be(o),i,a,{i:1}),{fields:i,unmapped:[...a]}}var $r=k(()=>{"use strict";f()});import{existsSync as Sr}from"fs";import{readFile as jr}from"fs/promises";import Vt from"path";import{XMLParser as al}from"fast-xml-parser";function Bn(e){return[Vt.join(e,"_cq_dialog",".content.xml"),Vt.join(e,"_cq_dialog.xml"),Vt.join(e,"cq:dialog",".content.xml")].find(n=>Sr(n))??null}async function Pr(e){let t=Vt.join(e,".content.xml");if(Sr(t))try{let a=(new al({ignoreAttributes:!1,attributeNamePrefix:"@_"}).parse(await jr(t,"utf-8"))["jcr:root"]??{})["@_jcr:title"];return typeof a=="string"?a.replace(/^\{[^}]+\}/,""):void 0}catch{return}}async function Er(e){let t=Bn(e);return t?xr(await jr(t,"utf-8")):null}function Cr(e,t,n){return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:n}],filters:[]},null,2)}
|
|
373
|
+
`}function Ar(e,t){let o=t.some(i=>i.component==="container"&&i.multi)?` // This block was migrated from a classic AEM component with a multifield.
|
|
374
374
|
// Each child row is one repeated item - enhance them here.
|
|
375
375
|
[...block.children].forEach((row) => {
|
|
376
376
|
row.classList.add('${e}-item');
|
|
@@ -382,25 +382,25 @@ export default function decorate(block) {
|
|
|
382
382
|
block.classList.add('${e}');
|
|
383
383
|
${o}
|
|
384
384
|
}
|
|
385
|
-
`}function
|
|
385
|
+
`}function Tr(e){return`/* Block: ${e} */
|
|
386
386
|
/* Migrated from a classic AEM component. Bring the component's styles here */
|
|
387
387
|
/* (from its clientlib or the rendered page) and keep them scoped to the block. */
|
|
388
388
|
.${e} {
|
|
389
389
|
}
|
|
390
|
-
`}var
|
|
391
|
-
`)}function
|
|
392
|
-
${
|
|
390
|
+
`}var Rr=k(()=>{"use strict";f();$r()});function sl(e,t,n){let o=[` // --- ${Dr} ---`];return n.click&&o.push(` ${t}.addEventListener('click', (ev) => {`," const el = ev.target.closest('a, button');"," if (!el) return;",` trackEvent({ event: 'block_click', block: '${e}', label: el.dataset.track || el.textContent.trim() });`," });"),n.submit&&o.push(` ${t}.addEventListener('submit', () => {`,` trackEvent({ event: 'form_submit', block: '${e}' });`," });"),o.join(`
|
|
391
|
+
`)}function Lr(e,t,n){if(e.includes(Dr))return{js:e,changed:!1,reason:"already instrumented"};if(!n.click&&!n.submit)return{js:e,changed:!1,reason:"no events selected"};let o=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!o||o.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let i=o[1]||"block",a=e;if(!a.includes("scripts/analytics.js")){let c=[...a.matchAll(/^import .*$/gm)];if(c.length){let m=c[c.length-1],p=(m.index??0)+m[0].length;a=`${a.slice(0,p)}
|
|
392
|
+
${Fr}${a.slice(p)}`}else a=`${Fr}
|
|
393
393
|
|
|
394
|
-
${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=
|
|
394
|
+
${a}`}let s=a.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!s||s.index===void 0)return{js:a,changed:!1,reason:"decorate not found"};let d=s.index+s[0].length,l=sl(t,i,n);return a=`${a.slice(0,d)}
|
|
395
395
|
${l}
|
|
396
|
-
${a.slice(d)}`,{js:a,changed:!0}}var
|
|
396
|
+
${a.slice(d)}`,{js:a,changed:!0}}var Dr,Fr,Or=k(()=>{"use strict";f();Dr="analytics (eds track)",Fr="import { trackEvent } from '../../scripts/analytics.js';"});var pt={};O(pt,{trackBlock:()=>ml});import{existsSync as Nr}from"fs";import{readFile as cl,writeFile as ll}from"fs/promises";import Mr from"path";import dl from"chalk";async function ml(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Track block"));let o=Mr.join(n,"blocks",e,`${e}.js`);if(!Nr(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i={click:t.click!==!1,submit:t.submit!==!1},a=Lr(await cl(o,"utf-8"),e,i);if(!a.changed){r.warn(`Not instrumented: ${a.reason}.`);return}await ll(o,a.js),r.info(S("Instrumented"));let s=[i.click?"block_click":null,i.submit?"form_submit":null].filter(Boolean);r.info(j(`blocks/${e}/${e}.js`,s.join(" + "))),Nr(Mr.join(n,"scripts","analytics.js"))||(r.info(""),r.warn("scripts/analytics.js is missing - run `eds integrate gtm` to create it.")),r.info(""),r.info(dl.dim(" Events push to window.dataLayer via trackEvent - GTM picks them up."))}var ut=k(()=>{"use strict";f();R();z();Or();M()});var zn={};O(zn,{migrateComponent:()=>fl});import{existsSync as Hn}from"fs";import{mkdir as pl,writeFile as Gn}from"fs/promises";import De from"path";function ul(e,t,n){return`/* Block: ${e} */
|
|
397
397
|
/* Migrated from the component clientlib: ${n.join(", ")}. */
|
|
398
398
|
/* TODO: review selectors and scope them under .${e} (and port any LESS/SCSS). */
|
|
399
399
|
|
|
400
400
|
${t.trim()}
|
|
401
|
-
`}function
|
|
402
|
-
`),
|
|
403
|
-
// --- ${
|
|
401
|
+
`}function Ir(e,t=0){let n=[];for(let o of e){let i=" ".repeat(t);if(o.component==="tab")n.push(`${i}${U.blue("\u25B8")} ${o.label??o.name}`);else{let a=o.options?.length?` (${o.options.length} options)`:"",s=o.multi?" \xB7multi":"",d=o.label?`- ${o.label}`:"";n.push(`${i}${U.accent(o.component)}${s} ${o.name}${a} ${d}`),o.fields?.length&&n.push(...Ir(o.fields,t+1))}}return n}function _r(e){let t=0;for(let n of e)n.component!=="tab"&&(t+=1,n.fields&&(t+=_r(n.fields)));return t}async function fl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}await r.logoOnceAnimated("Migrate component");let{input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),a=!t.yes,s=e;if(!s&&a&&(s=await o({message:"Path to the classic component folder",validate:y=>Hn(y.trim())||"Folder not found"})),!s){r.error("Provide the path to the classic component folder."),process.exitCode=1;return}if(s=De.resolve(s.trim()),!Bn(s)){r.error(`No Touch UI dialog (_cq_dialog/.content.xml) found in ${s}.`),process.exitCode=1;return}let d=await Er(s);if(!d||d.fields.length===0){r.warn("Dialog found but no mappable fields were detected."),d?.unmapped.length&&r.info(`Unmapped resourceTypes: ${d.unmapped.join(", ")}`),process.exitCode=1;return}let l=await Pr(s)??De.basename(s),c=t.name&&Yt(t.name)||Yt(a?await o({message:"Block name",default:Yt(l)}):l);r.info(S("Mapped fields",`${_r(d.fields)} from dialog`));for(let y of Ir(d.fields))r.info(` ${y}`);if(d.unmapped.length&&(r.info(""),r.warn(`Skipped (unrecognised): ${d.unmapped.join(", ")}`)),r.info(""),a&&!await i({message:`Generate block "${c}"?`,default:!0})){r.info("Cancelled.");return}let m=De.join(n,"blocks",c);if(Hn(m)){r.error(`Block "${c}" already exists at blocks/${c}. Use --name to pick another.`),process.exitCode=1;return}let p=t.clientlib?De.resolve(t.clientlib.trim()):await yr(s),u=Tr(c),g="empty - add styles from clientlib / rendered CSS",h=[];if(p&&Hn(p)){let y=await vr(p);y.css.trim()&&(u=ul(c,y.css,y.files),g=`from clientlib (${y.files.length} file(s)) - review & scope`),h=y.preprocessed}await pl(m,{recursive:!0}),await Gn(De.join(m,`${c}.js`),Ar(c,d.fields)),await Gn(De.join(m,`${c}.css`),u),await Gn(De.join(m,`_${c}.json`),Cr(c,l,d.fields)),r.info(S("Created"));let b=[`${c}.js`,`${c}.css`,`_${c}.json`],w=I(b);if(r.info(j(`${c}.js`,"decorator stub (port HTL logic)",w)),r.info(j(`${c}.css`,g,w)),r.info(j(`_${c}.json`,"Universal Editor model",w)),h.length&&(r.info(""),r.warn(`LESS/SCSS found (needs a build, not copied): ${h.join(", ")}`)),r.info(""),a&&await i({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:v}=await Promise.resolve().then(()=>(ut(),pt));await v(c,{})}r.info(N([`"${c}" migrated. Next: add CSS, then \`eds block preview ${c}\``]))}var Yt,Wn=k(()=>{"use strict";f();R();kr();Rr();z();M();Yt=e=>e.trim().toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"")});function V(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t}var X,Ur=k(()=>{"use strict";f();X={text:(e,t)=>({component:"text",valueType:"string",name:e,label:t}),textarea:(e,t)=>({component:"textarea",valueType:"string",name:e,label:t}),richtext:(e,t)=>({component:"richtext",valueType:"string",name:e,value:"",label:t}),number:(e,t)=>({component:"number",valueType:"number",name:e,label:t}),boolean:(e,t,n=!1)=>({component:"boolean",valueType:"boolean",name:e,value:n,label:t}),dateTime:(e,t)=>({component:"date-time",valueType:"date",name:e,label:t}),select:(e,t,n,o)=>({component:"select",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),multiselect:(e,t,n)=>({component:"multiselect",valueType:"string",name:e,label:t,options:n}),radioGroup:(e,t,n,o)=>({component:"radio-group",valueType:"string",name:e,label:t,options:n,...o!==void 0?{value:o}:{}}),checkboxGroup:(e,t,n)=>({component:"checkbox-group",valueType:"string[]",name:e,label:t,options:n}),reference:(e,t)=>({component:"reference",valueType:"string",name:e,label:t}),aemContent:(e,t)=>({component:"aem-content",name:e,label:t}),aemContentFragment:(e,t)=>({component:"aem-content-fragment",name:e,label:t}),aemExperienceFragment:(e,t)=>({component:"aem-experience-fragment",name:e,label:t}),aemTag:(e,t)=>({component:"aem-tag",valueType:"string",name:e,label:t}),tab:(e,t)=>({component:"tab",name:e,label:t}),container:(e,t,n,o=!0)=>({component:"container",name:e,label:t,multi:!0,collapsible:o,fields:n})}});function Xn(e){return ze.find(t=>t.id===e)}var gl,hl,wl,bl,Br,Hr,Jn,Gr,qn,Kn,yl,vl,kl,xl,$l,ze,Vn=k(()=>{"use strict";f();Ur();gl=[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"},{name:"H5",value:"h5"},{name:"H6",value:"h6"}],hl=[{name:"Same tab",value:"_self"},{name:"New tab",value:"_blank"}],wl=[{name:"Default",value:""},{name:"Primary",value:"primary"},{name:"Secondary",value:"secondary"}],bl=[{name:"Highlight",value:"highlight"},{name:"Dark",value:"dark"},{name:"Centered",value:"centered"},{name:"Full width",value:"full-width"}],Br=(e="")=>[X.text(V(e,"title"),"Title"),X.select(V(e,"titleType"),"Heading level",gl,"h2")],Hr=(e="")=>[X.text(V(e,"eyebrow"),"Eyebrow")],Jn=(e="")=>[X.reference(V(e,"image"),"Image"),X.text(V(e,"imageAlt"),"Alt text")],Gr=(e="")=>[X.richtext(V(e,"text"),"Text")],qn=(e="")=>[X.text(V(e,"linkText"),"Link text"),X.aemContent(V(e,"link"),"Link"),X.select(V(e,"linkTarget"),"Open in",hl,"_self")],Kn=(e="")=>[...qn(e),X.select(V(e,"ctaStyle"),"Style",wl,"")],yl=(e="")=>[X.container(V(e,"ctas")||"ctas","Buttons",Kn())],vl=(e="")=>[X.multiselect(V(e,"classes"),"Styles",bl)],kl=(e="")=>[X.aemContent(V(e,"url"),"URL (video / embed)")],xl=(e="")=>[...Jn(e),...Hr(e),...Br(e),...Gr(e),...Kn(e)],$l=(e="")=>[...Jn(e),X.text(V(e,"title"),"Title"),X.richtext(V(e,"description"),"Description"),...qn(e)],ze=[{id:"heading",label:"Heading (title + level)",build:Br},{id:"eyebrow",label:"Eyebrow (kicker line)",build:Hr},{id:"image",label:"Image (reference + alt)",build:Jn},{id:"richtext",label:"Rich text body",build:Gr},{id:"link",label:"Link (text + url + target)",build:qn},{id:"cta",label:"CTA (link + style)",build:Kn},{id:"cta-group",label:"CTA group (repeatable buttons)",build:yl},{id:"classes",label:"Section styles (CSS modifiers)",build:vl},{id:"embed",label:"Embed / video (URL)",build:kl},{id:"teaser",label:"Teaser (image + eyebrow + title + text + CTA)",build:xl},{id:"card",label:"Card (image + title + description + link)",build:$l}]});var Zn={};O(Zn,{modelAdd:()=>Pl});import{existsSync as Yn}from"fs";import{readFile as Sl,writeFile as jl}from"fs/promises";import Qn from"path";async function Pl(e,t,n={}){let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Model - add partials"));let{select:i,checkbox:a}=await Promise.resolve().then(()=>(G(),H)),s=!n.yes,d=e;if(!d&&s){let{readdir:v}=await import("fs/promises"),T=Qn.join(o,"blocks"),K=Yn(T)?(await v(T,{withFileTypes:!0})).filter(J=>J.isDirectory()&&Yn(Qn.join(T,J.name,`_${J.name}.json`))).map(J=>J.name):[];if(K.length===0){r.error("No block with a _<name>.json model found. Create one with `eds block create`."),process.exitCode=1;return}d=await i({message:"Which block's model?",choices:K.map(J=>({name:J,value:J}))})}if(!d){r.error("Provide a block name."),process.exitCode=1;return}let l=Qn.join(o,"blocks",d,`_${d}.json`);if(!Yn(l)){r.error(`No model at blocks/${d}/_${d}.json. Create the block first.`),process.exitCode=1;return}let c=t;c.length===0&&s&&(c=await a({message:"Which partials to add?",choices:ze.map(v=>({name:v.label,value:v.id}))}));let m=c.map(v=>Xn(v.trim())).filter(v=>!!v),p=c.filter(v=>!Xn(v.trim()));if(p.length&&r.warn(`Unknown partial(s): ${p.join(", ")}. Available: ${ze.map(v=>v.id).join(", ")}`),m.length===0){r.info("Nothing to add.");return}let u;try{u=JSON.parse(await Sl(l,"utf-8"))}catch{r.error(`Could not parse ${l}.`),process.exitCode=1;return}let g=Array.isArray(u.models)?u.models:[],h=g.find(v=>v.id===d)??g[0];if(!h){r.error("Model has no `models[]` entry to add fields to."),process.exitCode=1;return}h.fields=Array.isArray(h.fields)?h.fields:[];let b=new Set(h.fields.map(v=>v.name)),w=[],y=[];for(let v of m)for(let T of v.build()){if(b.has(T.name)){y.push(T.name);continue}b.add(T.name),h.fields.push(T),w.push(T.name)}await jl(l,`${JSON.stringify(u,null,2)}
|
|
402
|
+
`),r.info(S("Model updated",`blocks/${d}/_${d}.json`)),r.info(j("partials",m.map(v=>v.id).join(", "))),r.info(j("fields added",w.length?w.join(", "):"(none)")),y.length&&r.info(A("warn","skipped (exists)",y.join(", "))),r.info(""),r.info(N([`${w.length} field(s) added to "${d}"`]))}var eo=k(()=>{"use strict";f();R();Vn();z();M()});function Wr(e){return Qt.find(t=>t.id.toLowerCase()===e.toLowerCase())}function Jr(e,t){if(e.includes(zr))return{js:e,changed:!1,reason:"already has JSON-LD"};let n=e.match(/export default (?:async )?function decorate\s*\(\s*([A-Za-z_$][\w$]*)?[^)]*\)\s*\{/);if(!n||n.index===void 0)return{js:e,changed:!1,reason:"no `export default function decorate(...)` found"};let o=n[1]||"block",i=n.index+n[0].length,a=`
|
|
403
|
+
// --- ${zr}: ${t.id}) ---
|
|
404
404
|
{
|
|
405
405
|
const root = ${o};
|
|
406
406
|
const ld = ${t.object};
|
|
@@ -409,7 +409,7 @@ ${t.trim()}
|
|
|
409
409
|
ldScript.textContent = JSON.stringify(ld);
|
|
410
410
|
document.head.append(ldScript);
|
|
411
411
|
}
|
|
412
|
-
`;return{js:`${e.slice(0,
|
|
412
|
+
`;return{js:`${e.slice(0,i)}${a}${e.slice(i)}`,changed:!0}}var zr,Qt,qr=k(()=>{"use strict";f();zr="json-ld (eds schema",Qt=[{id:"Article",label:"Article / BlogPosting",object:`{
|
|
413
413
|
'@context': 'https://schema.org',
|
|
414
414
|
'@type': 'Article',
|
|
415
415
|
headline: root.querySelector('h1, h2, h3')?.textContent?.trim() || document.title,
|
|
@@ -488,52 +488,58 @@ ${t.trim()}
|
|
|
488
488
|
position: i + 1,
|
|
489
489
|
text: li.textContent?.trim(),
|
|
490
490
|
})),
|
|
491
|
-
}`}]});var
|
|
492
|
-
`}async function
|
|
491
|
+
}`}]});var to={};O(to,{schemaBlock:()=>Fl});import{existsSync as El}from"fs";import{readFile as Cl,writeFile as Al}from"fs/promises";import Tl from"path";import Rl from"chalk";async function Fl(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Schema - JSON-LD"));let o=Tl.join(n,"blocks",e,`${e}.js`);if(!El(o)){r.error(`Block "${e}" not found (no blocks/${e}/${e}.js).`),process.exitCode=1;return}let i=t.type;if(!i&&!t.yes){let{select:d}=await Promise.resolve().then(()=>(G(),H));i=await d({message:"Which schema.org type?",choices:Qt.map(l=>({name:`${l.id} - ${l.label}`,value:l.id}))})}let a=i?Wr(i):void 0;if(!a){r.error(`Unknown schema type "${i}". Options: ${Qt.map(d=>d.id).join(", ")}`),process.exitCode=1;return}let s=Jr(await Cl(o,"utf-8"),a);if(!s.changed){r.warn(`Not added: ${s.reason}.`);return}await Al(o,s.js),r.info(S("JSON-LD added")),r.info(j(`blocks/${e}/${e}.js`,`${a.id} (${a.label})`)),r.info(""),r.info(Rl.dim(" Review the generated object - some fields are heuristic or TODO. Validate at search.google.com/test/rich-results."))}var no=k(()=>{"use strict";f();R();z();qr();M()});function Ll(e,t){for(let n of e.match(/<meta\b[^>]*>/gi)??[])if(n.match(/\bname=["']([^"']+)["']/i)?.[1]===t)return n.match(/\bcontent=["']([^"']*)["']/i)?.[1]??"";return null}function Kr(e){return Ll(e,Dl)!==null}function Xr(e){return Array.isArray(e)?e.map(t=>t&&typeof t=="object"?t.id:void 0).filter(t=>typeof t=="string"):[]}function Vr(e){let t=!!e.configPresent["component-definition.json"]&&!!e.configPresent["component-models.json"],n=new Set(e.modelIds),o=e.blocks.map(i=>{let a=i.hasModelFile||n.has(i.name);return{name:i.name,editable:a,reason:a?void 0:"no UE model (_<name>.json or component-models entry)"}});return{isUeProject:t,blocks:o}}var oo,Dl,Yr=k(()=>{"use strict";f();oo=["component-definition.json","component-models.json","component-filters.json"],Dl="urn:adobe:aue:system:aemconnection"});var ht={};O(ht,{ueCheck:()=>Ul,ueOpen:()=>Bl});import{existsSync as gt}from"fs";import{readFile as Qr,readdir as Ol}from"fs/promises";import ft from"path";import Zt from"chalk";async function Nl(e){if(!gt(e))return null;try{return JSON.parse(await Qr(e,"utf-8"))}catch{return null}}async function Ml(e){let t=ft.join(e,"blocks");return gt(t)?(await Ol(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>({name:o.name,hasModelFile:gt(ft.join(t,o.name,`_${o.name}.json`))})):[]}async function Il(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore"})}catch{}}async function _l(e){try{let{execa:t}=await import("execa");return(await t("git",["remote","get-url","origin"],{cwd:e})).stdout.trim()||null}catch{return null}}async function Ul(){let e=P();if(!e){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Universal Editor - readiness"));let t={};for(let p of oo)t[p]=gt(ft.join(e,p));let n=await Nl(ft.join(e,"component-models.json")),o=await Ml(e),{isUeProject:i,blocks:a}=Vr({configPresent:t,blocks:o,modelIds:Xr(n)});r.info(S("Universal Editor config"));let s=[...oo],d=I(s);for(let p of s)r.info(A(t[p]?"pass":"fail",p,void 0,d));if(!i){r.info(""),r.warn("This doesn't look like a Universal Editor (crosswalk) project - run `eds scaffold ue` first."),process.exitCode=1;return}let l=ft.join(e,"head.html");if(gt(l)){let p=Kr(await Qr(l,"utf-8"));r.info(A(p?"pass":"info","head.html",p?"aemconnection present":"no aemconnection (fine for cloud author)"))}if(r.info(S("Blocks",`${a.length} found`)),a.length===0)r.info(Zt.dim(" No blocks yet."));else{let p=I(a.map(u=>u.name));for(let u of a)r.info(A(u.editable?"pass":"warn",u.name,u.reason,p))}let c=a.filter(p=>p.editable).length,m=a.length-c;r.info(""),r.info(ge({pass:c,warn:m})),r.info(Zt.dim(" Open a page in the editor with `eds ue open <path>`."))}async function Bl(e,t={}){let n=P()??process.cwd(),o=e??t.path??"/",i=t.url;if(!i){let s=await _l(n),d=s?He(s):null;if(!d){r.error("Couldn't determine the preview host from git."),r.info(Zt.dim(" Pass it explicitly: `eds ue open <path> --url main--<repo>--<owner>.aem.page`")),process.exitCode=1;return}i=Ge(d.owner,d.repo,t.ref??"main")}let a=_i({host:i,path:o,org:t.org});r.info(S("Universal Editor")),r.info(j("page",`${i}${o.startsWith("/")?"":"/"}${o}`)),r.info(j("open",a)),t.open!==!1?await Il(a):r.info(Zt.dim(" (use without --no-open to launch the browser)"))}var wt=k(()=>{"use strict";f();R();z();Yr();Bt();M()});var ro={};O(ro,{createBlock:()=>Wl,ueModelFor:()=>ea});import{existsSync as Hl}from"fs";import{mkdir as Gl,writeFile as io}from"fs/promises";import bt from"path";import Zr from"chalk";function zl(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function ea(e){let t=zl(e);return`${JSON.stringify({definitions:[{title:t,id:e,plugins:{xwalk:{page:{resourceType:"core/franklin/components/block/v1/block",template:{name:t,model:e}}}}}],models:[{id:e,fields:[{component:"text",name:"title",label:"Title",valueType:"string"},{component:"select",name:"titleType",label:"Title Type",valueType:"string",value:"h2",options:[{name:"H1",value:"h1"},{name:"H2",value:"h2"},{name:"H3",value:"h3"},{name:"H4",value:"h4"}]},{component:"richtext",name:"text",value:"",label:"Text",valueType:"string"}]}],filters:[]},null,2)}
|
|
492
|
+
`}async function Wl(e,t={}){if(!Pe.test(e)){r.error(`Invalid block name "${e}". Use kebab-case (e.g., "hero-banner", "card-list").`),process.exitCode=1;return}let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}let o=bt.join(n,"blocks",e);if(Hl(o)){r.error(`Block "${e}" already exists at ${o}`),process.exitCode=1;return}await Gl(o,{recursive:!0});let i=`export default function decorate(block) {
|
|
493
493
|
// TODO: implement ${e} block
|
|
494
494
|
}
|
|
495
495
|
`,a=`.${e} {
|
|
496
496
|
/* TODO: style ${e} block */
|
|
497
497
|
}
|
|
498
|
-
`;await
|
|
499
|
-
`)[0].slice(0,100);
|
|
500
|
-
`)[0].slice(0,70):"";return ee.dim(`$ ${r}`)}default:return`${_.blue("\u2192")} ${e}`}}var Nr=w(()=>{"use strict";m();R();I()});import{existsSync as ul}from"fs";import{readFile as fl}from"fs/promises";import{homedir as gl}from"os";import to from"path";async function _r(e){try{let t=await fl(e,"utf-8");return JSON.parse(t)}catch{return}}async function fe(e){let t=await _r(no),n=e?await _r(to.join(e,hl)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},r=sn.safeParse(o);return r.success?r.data:(i.debug("Config validation issues:",r.error.flatten()),sn.parse({}))}function Ur(){return Ir}function oo(){return no}function io(){return ul(no)}var Ir,no,hl,Pe=w(()=>{"use strict";m();R();Me();Ir=to.join(gl(),".eds"),no=to.join(Ir,"config.json"),hl=".edsrc.json"});function Br(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function bl(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:Br(n),source:t})):[]}function Hr(e,t){let n=bl(e,"figma");return n.length?n:wl(t)}function wl(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 a=o.source;n.push({width:r,label:Br(r),source:a==="figma"?"figma":"default"})}return n}var Gr=w(()=>{"use strict";m()});async function qr(e){let{fileKey:t,nodeId:n,token:o}=e,r=n?`${zr}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${zr}/files/${t}`,a=await fetch(r,{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()}function ro(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 Wr(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return ro(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>ro(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function Kr(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=Wr(e.fills);o&&(n.fill=o);let r=Wr(e.strokes);r&&(n.stroke={color:r,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} ${ro(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<yl){let s=e.children.slice(0,Jr).map(d=>Kr(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>Jr&&(n.childrenTruncated=e.children.length)}return n}function Xr(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 r={source:"figma-rest",file:n.name,root:Kr(o,0)};return JSON.stringify(r,null,2)}var zr,yl,Jr,Vr=w(()=>{"use strict";m();zr="https://api.figma.com/v1";yl=12,Jr=60});import{existsSync as vl}from"fs";import{mkdir as kl,readFile as xl,writeFile as $l}from"fs/promises";import ao from"path";function Sl(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),r=`${o(t)}__${o(n??"file")}.json`;return ao.join(e,"tmp","eds-cli","design-cache",r)}async function jl(e){if(!vl(e))return null;try{return await xl(e,"utf-8")}catch{return null}}async function El(e,t){await kl(ao.dirname(e),{recursive:!0}),await $l(e,t,"utf-8")}async function Yr(e){if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};let{figma:t,projectRoot:n}=e;if(!t?.fileKey)return{summary:"provider MCP"};let o=Sl(n,t.fileKey,t.nodeId),r=ao.relative(n,o);if(!e.refresh){let a=await jl(o);if(a)return{design:{mode:"spec",spec:a,cachePath:r},summary:`cache ${r}`}}if(e.token&&!e.preferMcp)try{let a=await qr({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=Xr(a,t.nodeId);return await El(o,s),{design:{mode:"spec",spec:s,cachePath:r},summary:`REST \u2192 ${r}`}}catch(a){return{design:{mode:"mcp",cachePath:r},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:r},summary:"MCP (1 call, cached)"}}var Qr=w(()=>{"use strict";m();Vr()});function Jt(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,a;n[2]==="branch"&&n[3]?(r=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(r=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?Pl(s):void 0;return{fileKey:r,nodeId:d,fileName:a}}function Pl(e){return decodeURIComponent(e).replace(/-/g,":")}var Zr=w(()=>{"use strict";m()});import{existsSync as Cl}from"fs";import{readFile as Al}from"fs/promises";import Tl from"path";function Rl(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 io(bt.join(o,`${e}.js`),i),await io(bt.join(o,`${e}.css`),a);let s=t.ueModel!==!1;s&&await io(bt.join(o,`_${e}.json`),ea(e)),r.success(`Block "${e}" created at ${Zr.cyan(bt.relative(n,o))}${s?Zr.dim(" (+ Universal Editor model)"):""}`)}var ao=k(()=>{"use strict";f();R();z();Be()});import{existsSync as en}from"fs";import{readFile as Jl}from"fs/promises";import{homedir as We}from"os";import Je from"path";async function co(e){let{execaCommand:t}=await import("execa");try{return(await t(`which ${e}`)).stdout.trim()||void 0}catch{return}}function ta(e){if(!e||typeof e!="object")return;let t=e,n=t.mcpServers;if(n&&typeof n=="object"){for(let o of Object.keys(n))if(o.toLowerCase().includes("figma"))return o}for(let o of Object.values(t)){let i=ta(o);if(i)return i}}async function lo(e){for(let t of e)try{if(!en(t))continue;let n=await Jl(t,"utf-8");try{let o=ta(JSON.parse(n));if(o)return o}catch{}if(n.toLowerCase().includes("figma"))return"figma"}catch{}}async function na(e){if(e){let t=so.find(n=>n.type===e);if(t){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);return{type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}r.warn(`Preferred agent "${e}" not found in PATH`)}}for(let t of so){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);return{type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o}}}}async function tn(){let e=[];for(let t of so){let n=await co(t.binary);if(n){let o=await lo(t.mcpConfigPaths);e.push({type:t.type,path:n,configDir:en(t.configDir)?t.configDir:void 0,hasFigmaMcp:!!o,figmaMcpServerName:o})}}return e}var so,mo=k(()=>{"use strict";f();R();so=[{type:"claude",binary:"claude",configDir:Je.join(We(),".claude"),mcpConfigPaths:[Je.join(We(),".claude","plugins.json"),Je.join(We(),".claude.json")]},{type:"cursor",binary:"cursor",configDir:Je.join(We(),".cursor"),mcpConfigPaths:[Je.join(We(),".cursor","mcp.json")]},{type:"codex",binary:"codex",configDir:Je.join(We(),".codex"),mcpConfigPaths:[]}]});import{mkdir as ql,readFile as Kl,writeFile as Xl}from"fs/promises";import{tmpdir as Vl}from"os";import yt from"path";import Yl from"readline";import te from"chalk";async function po(e,t){let n=t?yt.join(t,"tmp"):Vl(),o=yt.join(n,"eds-cli");await ql(o,{recursive:!0});let i=`from-design-${Date.now()}.md`,a=yt.join(o,i);return await Xl(a,e,"utf-8"),a}async function uo(e,t,n,o){let{execa:i}=await import("execa"),a=await Kl(t,"utf-8");try{switch(e.type){case"claude":{r.info(`Running Claude Code ${te.dim("- live log:")}`);let s=[...e.figmaMcpServerName?[e.figmaMcpServerName]:[],"figma-sse","figma-desktop","figma","Figma","plugin_figma_figma"],d=[...new Set(s.map(m=>`mcp__${m}`)),"Edit","Write","Read"].join(","),c=i("claude",["-p",a,"--model",o??"haiku","--output-format","stream-json","--verbose","--allowedTools",d],{cwd:n,buffer:!1,stdio:["ignore","pipe","inherit"]});await Zl(c,n);break}case"cursor":{r.info("Running Cursor agent..."),await i("cursor",["--prompt",a],{cwd:n,stdio:"inherit"});break}case"codex":{r.info("Running Codex..."),await i("codex",[a],{cwd:n,stdio:"inherit"});break}}return!0}catch(s){let d=s instanceof Error?s.message:String(s);return r.error(`Agent ${e.type} failed: ${d}`),!1}}function Ql(e){return e.includes("figma")?e.split("__").pop()??e:e.toLowerCase()}async function Zl(e,t){let n=(await import("ora")).default,o=Date.now(),i=()=>`${Math.round((Date.now()-o)/1e3)}s`,a=n({text:`thinking ${te.dim(i())}`,color:"yellow"}).start(),s="thinking",d=setInterval(()=>{a.text=`${s} ${te.dim(i())}`},300),l=new Map,c=p=>{a.stop(),r.info(` ${p}`),a.start()},m;try{if(e.stdout){let p=Yl.createInterface({input:e.stdout});for await(let u of p){let g=u.trim();if(!g)continue;let h;try{h=JSON.parse(g)}catch{continue}let b=Array.isArray(h.message?.content)?h.message.content:[];if(h.type==="assistant"){for(let w of b)if(w.type==="text"&&"text"in w){let y=w.text.trim().split(`
|
|
499
|
+
`)[0].slice(0,100);y&&c(te.dim(y))}else if(w.type==="tool_use"&&"name"in w){let y="id"in w&&w.id?w.id:`${Math.random()}`;l.set(y,{label:ed(w.name,w.input,t),start:Date.now()}),s=Ql(w.name)}}else if(h.type==="user"){for(let w of b)if(w.type==="tool_result"&&"tool_use_id"in w&&w.tool_use_id){let y=l.get(w.tool_use_id);if(y){let v=`${((Date.now()-y.start)/1e3).toFixed(1)}s`,T="is_error"in w&&w.is_error?` ${te.red("failed")}`:"";c(`${y.label} ${te.dim(v)}${T}`),l.delete(w.tool_use_id)}}}else if(h.type==="result"){let w=typeof h.duration_ms=="number"?`${(h.duration_ms/1e3).toFixed(1)}s`:"",y=typeof h.total_cost_usd=="number"?`$${h.total_cost_usd.toFixed(3)}`:"";m=[w,y].filter(Boolean).join(" \xB7 ")||"done"}}}for(let p of l.values())c(`${p.label} ${te.dim("\u2026")}`);clearInterval(d),m?a.succeed(`${U.accent("agent finished")} ${te.dim(m)}`):a.stop()}catch(p){throw clearInterval(d),a.stop(),p}await e}function ed(e,t,n){let o=i=>{let a=t?.[i];return typeof a!="string"?"":a.startsWith(n)?yt.relative(n,a):yt.basename(a)};if(e.includes("figma")){let i=e.split("__").pop()??e;return`${W.figma} ${te.bold(i)} ${te.dim("Figma MCP")}`}switch(e){case"Write":case"Edit":case"NotebookEdit":return`${U.accent("\u270E")} ${te.cyan(o("file_path"))}`;case"Read":return te.dim(`\xB7 read ${o("file_path")}`);case"Bash":{let i=typeof t?.command=="string"?t.command.split(`
|
|
500
|
+
`)[0].slice(0,70):"";return te.dim(`$ ${i}`)}default:return`${U.blue("\u2192")} ${e}`}}var oa=k(()=>{"use strict";f();R();M()});import{existsSync as td}from"fs";import{readFile as nd}from"fs/promises";import{homedir as od}from"os";import fo from"path";async function ia(e){try{let t=await nd(e,"utf-8");return JSON.parse(t)}catch{return}}async function le(e){let t=await ia(go),n=e?await ia(fo.join(e,id)):void 0,o={...typeof t=="object"&&t!==null?t:{},...typeof n=="object"&&n!==null?n:{}},i=yn.safeParse(o);return i.success?i.data:(r.debug("Config validation issues:",i.error.flatten()),yn.parse({}))}function aa(){return ra}function ho(){return go}function wo(){return td(go)}var ra,go,id,ye=k(()=>{"use strict";f();R();Be();ra=fo.join(od(),".eds"),go=fo.join(ra,"config.json"),id=".edsrc.json"});function sa(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function rd(e,t="figma"){return e?e.split(",").map(n=>Number.parseInt(n.trim(),10)).filter(n=>Number.isFinite(n)&&n>0).map(n=>({width:n,label:sa(n),source:t})):[]}function ca(e,t){let n=rd(e,"figma");return n.length?n:ad(t)}function ad(e){if(!Array.isArray(e))return[];let t=new Set,n=[];for(let o of e){let i=Number(o?.width);if(!Number.isFinite(i)||i<=0||t.has(i))continue;t.add(i);let a=o.source;n.push({width:i,label:sa(i),source:a==="figma"?"figma":"default"})}return n}var la=k(()=>{"use strict";f()});import{existsSync as sd}from"fs";import{createRequire as cd}from"module";import ld from"path";import{pathToFileURL as da}from"url";async function ma(e){try{return(await import("playwright")).chromium}catch{}let t=[e,process.cwd()].filter(n=>!!n);if(t.length)try{let o=cd(da(ld.join(t[0],"package.json")).href).resolve("playwright",{paths:t});return(await import(da(o).href)).chromium}catch{}throw new Error("Scraping needs Playwright. Install it in your project (`npm i -D playwright`) or globally (`npm i -g playwright`), then `npx playwright install chromium`.")}async function pa(e){let t=e.width??1440,n=await ma(e.projectRoot),o;try{o=await n.launch({headless:!0})}catch(i){let a=i instanceof Error?i.message:String(i);throw/Executable doesn't exist|install/i.test(a)?new Error("Chromium isn't installed for Playwright. Run `npx playwright install chromium`."):i}try{let i=e.storageStatePath&&sd(e.storageStatePath),s=await(await o.newContext({viewport:{width:t,height:900},deviceScaleFactor:1,...i?{storageState:e.storageStatePath}:{}})).newPage();await s.goto(e.url,{waitUntil:"networkidle",timeout:45e3}),await s.waitForTimeout(700);let d=await s.evaluate(dd,{maxNodes:320,maxDepth:14,textCap:200}),l={source:`scrape:${e.provider}`,url:e.url,viewport:t,authenticated:!!i,title:d.title,root:d.root,nodeCount:d.nodeCount,truncated:d.truncated};return JSON.stringify(l,null,2)}finally{await o.close()}}async function ua(e){let n=await(await ma(e.projectRoot)).launch({headless:!1});try{let o=await n.newContext();await(await o.newPage()).goto(e.loginUrl,{waitUntil:"domcontentloaded",timeout:6e4}),await e.waitForUser(),await o.storageState({path:e.statePath})}finally{await n.close()}}function dd(e){let t=new Set(["SCRIPT","STYLE","NOSCRIPT","LINK","META","HEAD","BR","TEMPLATE"]),n=0,o=!1,i=c=>!c||c==="none"||c==="normal"||c==="auto"||c==="0px"||c==="rgba(0, 0, 0, 0)"||c==="transparent";function a(c){let m="";for(let p of Array.from(c.childNodes))p.nodeType===3&&(m+=p.textContent??"");return m=m.replace(/\s+/g," ").trim(),m.length>e.textCap?`${m.slice(0,e.textCap)}\u2026`:m}function s(c){let m=getComputedStyle(c),p={},u=(g,h)=>{i(h)||(p[g]=h)};return u("display",m.display),(m.display.includes("flex")||m.display.includes("grid"))&&(u("flexDirection",m.flexDirection),u("justifyContent",m.justifyContent),u("alignItems",m.alignItems),u("gap",m.gap)),u("padding",m.padding),u("margin",m.margin),u("color",m.color),u("background",m.backgroundColor),m.backgroundImage&&m.backgroundImage!=="none"&&(p.backgroundImage=m.backgroundImage.slice(0,160)),u("fontFamily",m.fontFamily),u("fontSize",m.fontSize),u("fontWeight",m.fontWeight),u("lineHeight",m.lineHeight),u("letterSpacing",m.letterSpacing),u("textAlign",m.textAlign),u("border",m.border),u("borderRadius",m.borderRadius),u("boxShadow",m.boxShadow),m.opacity&&m.opacity!=="1"&&(p.opacity=m.opacity),m.position&&m.position!=="static"&&(p.position=m.position),p}function d(c,m){if(n>=e.maxNodes)return o=!0,null;if(t.has(c.tagName))return null;let p=c.getBoundingClientRect(),u=getComputedStyle(c);if(u.display==="none"||u.visibility==="hidden"||u.opacity==="0"||p.width<1||p.height<1)return null;n++;let h={tag:c.tagName.toLowerCase(),rect:{x:Math.round(p.x),y:Math.round(p.y),w:Math.round(p.width),h:Math.round(p.height)}},b=(c.getAttribute("class")||"").trim().split(/\s+/).filter(Boolean).slice(0,3);b.length&&(h.class=b.join(" "));let w=s(c);if(Object.keys(w).length&&(h.style=w),c.tagName==="IMG"){let v=c;h.img={src:(v.currentSrc||v.src||"").slice(0,200),alt:v.alt||"",w:v.naturalWidth,h:v.naturalHeight}}let y=a(c);if(y&&(h.text=y),m<e.maxDepth){let v=[];for(let T of Array.from(c.children)){let K=d(T,m+1);K&&v.push(K)}v.length&&(h.children=v)}return h}let l=d(document.body,0);return{title:document.title,root:l,nodeCount:n,truncated:o}}var bo=k(()=>{"use strict";f()});async function ha(e){let{fileKey:t,nodeId:n,token:o}=e,i=n?`${yo}/files/${t}/nodes?ids=${encodeURIComponent(n)}`:`${yo}/files/${t}`,a=await fetch(i,{headers:{"X-Figma-Token":o}});if(!a.ok){let s=await a.text().catch(()=>""),d=a.status===403?" (check the token scope: it needs file_content:read, and access to this file)":a.status===404?" (file or node not found \u2014 check the URL)":"";throw new Error(`Figma REST ${a.status} ${a.statusText}${d}${s?` \u2014 ${s.slice(0,200)}`:""}`)}return a.json()}async function wa(e){let{fileKey:t,nodeId:n,token:o,scale:i=1}=e;if(!n)throw new Error("A node id is required to render a Figma image.");let a=`${yo}/images/${t}?ids=${encodeURIComponent(n)}&format=png&scale=${i}`,s=await fetch(a,{headers:{"X-Figma-Token":o}});if(!s.ok){let m=await s.text().catch(()=>"");throw new Error(`Figma images ${s.status} ${s.statusText}${m?` \u2014 ${m.slice(0,200)}`:""}`)}let d=await s.json();if(d.err)throw new Error(`Figma images: ${d.err}`);let l=d.images?.[n]??Object.values(d.images??{}).find(Boolean);if(!l)throw new Error("Figma returned no image URL for that node.");let c=await fetch(l);if(!c.ok)throw new Error(`Fetching the rendered image failed: ${c.status} ${c.statusText}`);return Buffer.from(await c.arrayBuffer())}function vo(e){if(!e)return;let t=o=>Math.round(Math.max(0,Math.min(1,o))*255).toString(16).padStart(2,"0"),n=`#${t(e.r)}${t(e.g)}${t(e.b)}`;return e.a!==void 0&&e.a<1?`${n}${t(e.a)}`:n}function ga(e){let t=e?.find(n=>n.visible!==!1);if(t){if(t.type==="SOLID")return vo(t.color);if(t.type?.startsWith("GRADIENT")){let n=(t.gradientStops??[]).map(o=>vo(o.color)).filter(Boolean);return n.length?`gradient(${n.join(" \u2192 ")})`:"gradient"}return t.type==="IMAGE"?"image(placeholder)":t.type?.toLowerCase()}}function ba(e,t){if(!e||typeof e!="object")return null;let n={name:e.name,type:e.type};if(e.absoluteBoundingBox){let{width:s,height:d}=e.absoluteBoundingBox;s!=null&&d!=null&&(n.size={w:Math.round(s),h:Math.round(d)})}e.layoutMode&&e.layoutMode!=="NONE"&&(n.layout={direction:e.layoutMode==="HORIZONTAL"?"row":"column",gap:e.itemSpacing,padding:[e.paddingTop,e.paddingRight,e.paddingBottom,e.paddingLeft],align:[e.primaryAxisAlignItems,e.counterAxisAlignItems].filter(Boolean).join("/")});let o=ga(e.fills);o&&(n.fill=o);let i=ga(e.strokes);i&&(n.stroke={color:i,weight:e.strokeWeight}),e.cornerRadius&&(n.radius=e.cornerRadius);let a=(e.effects??[]).filter(s=>s.visible!==!1&&(s.type==="DROP_SHADOW"||s.type==="INNER_SHADOW")).map(s=>`${s.type==="INNER_SHADOW"?"inset ":""}${s.offset?.x??0} ${s.offset?.y??0} ${s.radius??0} ${vo(s.color)??""}`.trim());if(a.length&&(n.shadows=a),e.type==="TEXT"&&e.characters!==void 0){n.text=e.characters;let s=e.style??{};n.font={family:s.fontFamily,size:s.fontSize,weight:s.fontWeight,lineHeight:s.lineHeightPx,letterSpacing:s.letterSpacing,align:s.textAlignHorizontal}}if(e.children?.length&&t<md){let s=e.children.slice(0,fa).map(d=>ba(d,t+1)).filter(Boolean);s.length&&(n.children=s),e.children.length>fa&&(n.childrenTruncated=e.children.length)}return n}function ya(e,t){let n=e,o;if(t&&n.nodes){let a=Object.keys(n.nodes)[0];o=a?n.nodes[a]?.document:void 0}if(o??=n.document,!o)throw new Error("Figma REST response had no document node to serialize.");let i={source:"figma-rest",file:n.name,root:ba(o,0)};return JSON.stringify(i,null,2)}var yo,md,fa,ko=k(()=>{"use strict";f();yo="https://api.figma.com/v1";md=12,fa=60});import{existsSync as pd}from"fs";import{mkdir as ud,readFile as fd,writeFile as gd}from"fs/promises";import vt from"path";function hd(e,t,n){let o=a=>a.replace(/[^a-z0-9._-]/gi,"-"),i=`${o(t)}__${o(n??"file")}.json`;return vt.join(e,"tmp","eds-cli","design-cache",i)}function wd(e,t){let n=`scrape__${t.replace(/[^a-z0-9._-]/gi,"-").slice(0,120)}.json`;return vt.join(e,"tmp","eds-cli","design-cache",n)}function xo(e){return e==="framer"||e==="stitch"}async function va(e){if(!pd(e))return null;try{return await fd(e,"utf-8")}catch{return null}}async function ka(e,t){await ud(vt.dirname(e),{recursive:!0}),await gd(e,t,"utf-8")}async function xa(e){let{figma:t,projectRoot:n}=e;if(e.localFile)return{design:{mode:"file",filePath:e.localFile},summary:`local file ${e.localFile}`};if(xo(e.provider)&&e.designUrl){let a=wd(n,e.designUrl),s=vt.relative(n,a);if(e.dryRun)return{design:{mode:"scrape",spec:`{ "note": "dry run \u2014 the live ${e.provider} page is scraped at generate time", "url": "${e.designUrl}" }`,cachePath:s},summary:`scrape (dry run) ${e.designUrl}`};if(!e.refresh){let d=await va(a);if(d)return{design:{mode:"scrape",spec:d,cachePath:s},summary:`cache ${s}`}}try{let d=await pa({url:e.designUrl,provider:e.provider,projectRoot:n,storageStatePath:e.storageStatePath});return await ka(a,d),{design:{mode:"scrape",spec:d,cachePath:s},summary:`scrape \u2192 ${s}`}}catch(d){return{summary:"scrape failed",scrapeError:d instanceof Error?d.message:String(d)}}}if(!t?.fileKey)return{summary:"no design source"};let o=hd(n,t.fileKey,t.nodeId),i=vt.relative(n,o);if(!e.refresh){let a=await va(o);if(a)return{design:{mode:"spec",spec:a,cachePath:i},summary:`cache ${i}`}}if(e.token&&!e.preferMcp)try{let a=await ha({fileKey:t.fileKey,nodeId:t.nodeId,token:e.token}),s=ya(a,t.nodeId);return await ka(o,s),{design:{mode:"spec",spec:s,cachePath:i},summary:`REST \u2192 ${i}`}}catch(a){return{design:{mode:"mcp",cachePath:i},summary:"MCP (REST failed \u2014 1 call)",restError:a instanceof Error?a.message:String(a)}}return{design:{mode:"mcp",cachePath:i},summary:"MCP (1 call, cached)"}}var $a=k(()=>{"use strict";f();bo();ko()});function nn(e){if(/^\d+[-:]\d+$/.test(e.trim()))throw new Error(`Input "${e}" looks like a node-id but not a full URL. Provide a Figma URL or use --file-key.`);let t;try{t=new URL(e.trim())}catch{throw new Error(`Invalid Figma URL: "${e}"`)}if(!t.hostname.endsWith("figma.com"))throw new Error(`Not a Figma URL: "${e}"`);let n=t.pathname.split("/").filter(Boolean);if(n.length<2)throw new Error(`Cannot extract fileKey from URL: "${e}"`);let o=n[0],i,a;n[2]==="branch"&&n[3]?(i=n[3],a=n[4]?decodeURIComponent(n[4]):void 0):(i=n[1],a=n[2]?decodeURIComponent(n[2]):void 0);let s=t.searchParams.get("node-id"),d=s?bd(s):void 0;return{fileKey:i,nodeId:d,fileName:a}}function bd(e){return decodeURIComponent(e).replace(/-/g,":")}var Sa=k(()=>{"use strict";f()});import{existsSync as yd}from"fs";import{readFile as vd}from"fs/promises";import kd from"path";function xd(e,t,n){if(!e||e==="document"||e==="ue")return"";let o=t?` (model / persisted query: \`${t}\`)`:"",i="`${window.location.origin}/graphql/execute.json/<project>/<query>;path=<cfPath>`";return e==="cf"?`
|
|
501
501
|
## Content source: Content Fragment
|
|
502
502
|
This block renders an AEM **Content Fragment**${o} - not inline-authored copy.
|
|
503
503
|
- UE model: use an \`aem-content-fragment\` field (e.g. \`name: "fragment"\`) for the CF reference.
|
|
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** (${
|
|
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.
|
|
505
505
|
- Handle loading / empty / error states. Do not hardcode copy that the CF owns.
|
|
506
506
|
- \`.${n}\` styling still follows the EDS conventions below.
|
|
507
507
|
`:`
|
|
508
508
|
## Content source: Mixed (Universal Editor + Content Fragment)
|
|
509
509
|
This block mixes **two sources in one model and one \`decorate(block)\`**:
|
|
510
510
|
- **Inline (UE-authored)** parts \u2192 normal fields (text / richtext / image / select) read straight from the authored DOM cells, with semantic collapsing.
|
|
511
|
-
- **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.
|
|
512
512
|
- Field order in the model = cell order in the authored DOM. Read the inline cells by position; detect the CF reference by its \`/content/dam/\` link. Merge both into the final markup, and handle the CF loading/empty/error states.
|
|
513
|
-
`}async function
|
|
513
|
+
`}async function ja(e){let t=await $d(e.projectRoot),n=xd(e.contentSource,e.cfHint,e.blockName),o=e.screenshot===!0,i=e.provider??"figma",a=qe[i],s=e.design,d=s?.mode==="file"?/\.(png|jpe?g|webp)$/i.test(s.filePath):!1,c=`## Step 5 \u2014 One Verification Pass (single pass, then stop)
|
|
514
514
|
Do **exactly one** self-check \u2014 do **not** loop:
|
|
515
|
-
1. Compare your implementation to ${s?.mode==="spec"?"the exact values in the embedded 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.
|
|
515
|
+
1. Compare your implementation to ${s?.mode==="spec"?"the exact values in the embedded design data from Step 1":s?.mode==="scrape"?"the exact values in the scraped design data from Step 1":s?.mode==="file"?d?"the local design image":"the exact values in the local SVG":s?.mode==="mcp"?"the exact values from the `get_design_context` you cached":o?"the `get_screenshot` image":"the exact values from `get_design_context`"} once, across: spacing, fonts, colors, radius, shadows, alignment and proportions.
|
|
516
516
|
2. Apply **one** round of corrections, then **stop** \u2014 don't iterate to "pixel perfect". The author reviews the result in the live preview (\`eds block preview\`) and will request another pass with specific feedback if needed.
|
|
517
|
-
3. Briefly state what you checked and any value you had to infer.`,
|
|
517
|
+
3. Briefly state what you checked and any value you had to infer.`,m=`Target: fileKey \`${e.figma?.fileKey}\`${e.figma?.nodeId?`, node \`${e.figma.nodeId}\``:" (no node selected \u2014 use the full page)"}.`,p;s?.mode==="spec"?p=`## Step 1 \u2014 Use the Provided Design Data (no MCP)
|
|
518
518
|
The design was already fetched for you and is embedded below \u2014 **do not call any Figma MCP tool** (\`get_design_context\`, \`get_variable_defs\`, \`get_screenshot\`). Parse it for the exact structure, layout, spacing, colors, typography, radius and effects.
|
|
519
519
|
|
|
520
520
|
\`\`\`json
|
|
521
521
|
${s.spec}
|
|
522
522
|
\`\`\`
|
|
523
523
|
|
|
524
|
-
Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="
|
|
524
|
+
Image fills are placeholders (the data references assets, not pixels) \u2014 render a placeholder at the right aspect-ratio per the Placeholders section; authors supply the real image.`:s?.mode==="scrape"?p=`## Step 1 \u2014 Use the Scraped Design Data (no MCP)
|
|
525
|
+
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"?p=`## Step 1 \u2014 Read the Local Design Export (no MCP)
|
|
525
532
|
Read \`${s.filePath}\` with your **Read** tool. Do **not** call any Figma MCP tool.
|
|
526
533
|
|
|
527
534
|
${d?"It's a raster image (PNG/JPG) \u2014 open it and reproduce it visually: infer spacing, colors, typography, radius, shadows and layout as precisely as you can from the pixels.":"It's an **SVG** \u2014 read it as text and parse the **exact** values: geometry and positions (x/y/width/height, `viewBox`), text and typography (font-family / font-size / font-weight on `<text>`/`<tspan>`), fills and gradients, strokes, and effects. Use the numbers verbatim, converting px\u2192rem where appropriate. The SVG is flattened \u2014 regroup into semantic structure yourself (Step 3), don't mirror raw `<g>`/`<path>` nesting."}`:s?.mode==="mcp"?p=`## Step 1 \u2014 Fetch the Design Once, Then Cache It (single MCP call)
|
|
528
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.
|
|
529
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.
|
|
530
537
|
|
|
531
|
-
${
|
|
538
|
+
${m}`:i==="figma"?p=`## Step 1 \u2014 Fetch the Design (single MCP call)
|
|
532
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.":""}
|
|
533
540
|
|
|
534
|
-
${
|
|
535
|
-
|
|
536
|
-
Extract the **exact** structure, layout, colours, typography, spacing, radius and effects \u2014 do not approximate. Fetch once for the target only.`;let f=e.withUeModel?`
|
|
541
|
+
${m}`:p=`## 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?`
|
|
537
543
|
## Step 4b \u2014 Universal Editor Authoring (REQUIRED, not optional)
|
|
538
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.
|
|
539
545
|
|
|
@@ -608,12 +614,12 @@ Rules:
|
|
|
608
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\`.
|
|
609
615
|
|
|
610
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:
|
|
611
|
-
${
|
|
617
|
+
${ze.map(b=>`- \`${b.id}\` \u2014 ${b.label}`).join(`
|
|
612
618
|
`)}
|
|
613
|
-
`:"",g=s?.mode==="file"?"a design export":a,
|
|
619
|
+
`:"",g=s?.mode==="file"?"a design export":a,h=s?.mode==="file"?"design":`${a} design`;return`# Pixel-Perfect EDS Block from ${g}
|
|
614
620
|
|
|
615
621
|
## Task
|
|
616
|
-
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 ${h} **1:1 \u2014 pixel perfect**. Exact spacing, colors, typography, and layout. Not "close enough" \u2014 identical.
|
|
617
623
|
|
|
618
624
|
${p}
|
|
619
625
|
|
|
@@ -656,9 +662,9 @@ export default function decorate(block) {
|
|
|
656
662
|
/* Map Figma design tokens to CSS custom properties; reuse project tokens below where they match */
|
|
657
663
|
/* Mobile-first; exact values from Step 2 */
|
|
658
664
|
\`\`\`
|
|
659
|
-
${
|
|
665
|
+
${u}${n}
|
|
660
666
|
## Placeholders & assets \u2014 be visible before Universal Editor takes over
|
|
661
|
-
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.
|
|
662
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.
|
|
663
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.
|
|
664
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.
|
|
@@ -689,11 +695,11 @@ ${t}
|
|
|
689
695
|
5. Mobile-first CSS with breakpoints at 600px and 900px
|
|
690
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":""}
|
|
691
697
|
|
|
692
|
-
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.
|
|
693
699
|
|
|
694
700
|
---
|
|
695
|
-
*Prompt version: ${
|
|
696
|
-
`}function
|
|
701
|
+
*Prompt version: ${kt}*
|
|
702
|
+
`}function Pa(e){let t=e.provider??"figma",n=t==="figma"&&e.figma?.fileKey?`If the change needs design values, re-read **only what you need** from Figma (fileKey \`${e.figma.fileKey}\`${e.figma.nodeId?`, node \`${e.figma.nodeId}\``:""}) \u2014 don't re-fetch the whole design.`:"Use the values already in the files (and the cached design snapshot under `tmp/eds-cli/design-cache/` if present); infer sensibly if the request is purely stylistic.";return`# Refine the \`${e.blockName}\` EDS block
|
|
697
703
|
|
|
698
704
|
The block already exists in \`blocks/${e.blockName}/\` and the author reviewed it in the live preview. Apply **this change** and nothing else:
|
|
699
705
|
|
|
@@ -712,20 +718,20 @@ The block already exists in \`blocks/${e.blockName}/\` and the author reviewed i
|
|
|
712
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.
|
|
713
719
|
- **Minimise chat output:** edit files directly, don't paste code back. End with a **\u22642-line** summary of what changed.
|
|
714
720
|
|
|
715
|
-
*Prompt version: ${
|
|
716
|
-
`}async function
|
|
721
|
+
*Prompt version: ${kt}*
|
|
722
|
+
`}async function $d(e){let t=kd.join(e,"styles","styles.css");if(!yd(t))return"";try{let o=(await vd(t,"utf-8")).match(/:root\s*\{([^}]+)\}/);if(!o)return"";let i=o[1].split(`
|
|
717
723
|
`).filter(a=>a.trim().startsWith("--")).map(a=>a.trim()).join(`
|
|
718
|
-
`);return
|
|
724
|
+
`);return i?`
|
|
719
725
|
## Existing Project Tokens
|
|
720
726
|
The project already defines these CSS custom properties in \`styles/styles.css\`.
|
|
721
727
|
Reuse them instead of hardcoding values:
|
|
722
728
|
|
|
723
729
|
\`\`\`css
|
|
724
730
|
:root {
|
|
725
|
-
${
|
|
731
|
+
${i}
|
|
726
732
|
}
|
|
727
733
|
\`\`\`
|
|
728
|
-
`:""}catch{return""}}var
|
|
734
|
+
`:""}catch{return""}}var kt,qe,Ea=k(()=>{"use strict";f();Vn();kt="0.7.0",qe={figma:"Figma",framer:"Framer",stitch:"Google Stitch"}});import{existsSync as Sd}from"fs";import{chmod as jd,mkdir as Pd}from"fs/promises";import{homedir as Ed}from"os";import Ca from"path";function $o(e){return Ca.join(Ed(),".eds","auth",`${e}.json`)}function Aa(e){return Sd($o(e))}async function Ta(e){await Pd(Ca.dirname(e),{recursive:!0,mode:448})}async function Ra(e){try{await jd(e,384)}catch{}}var Fa=k(()=>{"use strict";f()});function de(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function Cd(e){let t=e,n=t.match(/<body[^>]*>([\s\S]*?)<\/body>/i);return n&&(t=n[1]),t.replace(/<!DOCTYPE[^>]*>/gi,"").replace(/<\/?(?:html|head|body)[^>]*>/gi,"").replace(/<link\b[^>]*>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<!--[\s\S]*?-->/g,"").trim()}function on(e){let{blockName:t}=e,n=Cd(e.sampleContent);return`<!DOCTYPE html>
|
|
729
735
|
<html lang="en">
|
|
730
736
|
<head>
|
|
731
737
|
<meta charset="utf-8" />
|
|
@@ -755,10 +761,10 @@ ${n}
|
|
|
755
761
|
try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
|
|
756
762
|
</script>
|
|
757
763
|
</body>
|
|
758
|
-
</html>`}function
|
|
764
|
+
</html>`}function Ad(e){let t=e.filter(n=>n.figma);return(t.length?t:e).reduce((n,o)=>o.width>n.width?o:n,e[0])}function Da(e){let t=e.map((o,i)=>{let a=Ad(o.breakpoints),s=o.breakpoints.map(c=>`<option value="${c.width}"${c.width===a.width?" selected":""}>${de(c.label)}</option>`).join(""),d=o.figmaUrl?`<a class="figma-link" href="${de(o.figmaUrl)}" target="_blank" rel="noopener">Figma \u2197</a>`:"",l=o.placeholder?'<span class="hint">placeholder content</span>':"";return`<section class="card">
|
|
759
765
|
<div class="cardbar">
|
|
760
|
-
<span class="block">${
|
|
761
|
-
<select class="bp" data-i="${
|
|
766
|
+
<span class="block">${de(o.blockName)}</span>
|
|
767
|
+
<select class="bp" data-i="${i}">
|
|
762
768
|
${s}
|
|
763
769
|
<option value="full">Full</option>
|
|
764
770
|
</select>
|
|
@@ -766,8 +772,8 @@ ${n}
|
|
|
766
772
|
${d}
|
|
767
773
|
</div>
|
|
768
774
|
<div class="stage">
|
|
769
|
-
<div class="device" data-i="${
|
|
770
|
-
<iframe src="${
|
|
775
|
+
<div class="device" data-i="${i}" data-w="${a.width}" style="width:${a.width}px">
|
|
776
|
+
<iframe src="${de(o.frameRoute)}" title="${de(o.blockName)} preview" loading="lazy"></iframe>
|
|
771
777
|
</div>
|
|
772
778
|
</div>
|
|
773
779
|
</section>`}).join(`
|
|
@@ -816,16 +822,16 @@ ${n}
|
|
|
816
822
|
try { new EventSource('/__eds_events').onmessage = () => location.reload(); } catch (e) { /* no SSE */ }
|
|
817
823
|
</script>
|
|
818
824
|
</body>
|
|
819
|
-
</html>`}function
|
|
820
|
-
`),c=o?`<a class="figma-link" href="${
|
|
825
|
+
</html>`}function La(e){let{blockName:t,breakpoints:n,figmaUrl:o,frameRoute:i,placeholder:a}=e,s=n.filter(p=>p.figma),d=(s.length?s:n).reduce((p,u)=>u.width>p.width?u:p,n[0]),l=n.map(p=>`<option value="${p.width}"${p.width===d.width?" selected":""}>${de(p.label)}</option>`).join(`
|
|
826
|
+
`),c=o?`<a class="figma-link" href="${de(o)}" target="_blank" rel="noopener">
|
|
821
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>
|
|
822
828
|
Open in Figma
|
|
823
|
-
</a>`:"",
|
|
829
|
+
</a>`:"",m=a?`<span class="hint">placeholder content \u2014 add <code>blocks/${t}/_${t}.preview.html</code></span>`:"";return`<!DOCTYPE html>
|
|
824
830
|
<html lang="en">
|
|
825
831
|
<head>
|
|
826
832
|
<meta charset="utf-8" />
|
|
827
833
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
828
|
-
<title>eds preview \u2014 ${
|
|
834
|
+
<title>eds preview \u2014 ${de(t)}</title>
|
|
829
835
|
<style>
|
|
830
836
|
*{box-sizing:border-box}
|
|
831
837
|
html,body{margin:0;padding:0;background:#1f1f1f;color:#eaeaea;font-family:ui-sans-serif,-apple-system,"Segoe UI",sans-serif}
|
|
@@ -847,18 +853,18 @@ ${n}
|
|
|
847
853
|
</head>
|
|
848
854
|
<body>
|
|
849
855
|
<div class="bar">
|
|
850
|
-
<span class="label">Block</span><span class="block">${
|
|
856
|
+
<span class="label">Block</span><span class="block">${de(t)}</span>
|
|
851
857
|
<label class="label" for="bp" style="margin-left:8px">Breakpoint</label>
|
|
852
858
|
<select id="bp">
|
|
853
859
|
${l}
|
|
854
860
|
<option value="full">Full ca\u0142a szeroko\u015B\u0107</option>
|
|
855
861
|
</select>
|
|
856
|
-
${
|
|
862
|
+
${m}
|
|
857
863
|
${c}
|
|
858
864
|
</div>
|
|
859
865
|
<div class="stage">
|
|
860
866
|
<div class="device" id="device" data-w="${d.width}" style="width:${d.width}px">
|
|
861
|
-
<iframe id="frame" src="${
|
|
867
|
+
<iframe id="frame" src="${i}" title="${de(t)} preview"></iframe>
|
|
862
868
|
</div>
|
|
863
869
|
</div>
|
|
864
870
|
<script>
|
|
@@ -872,29 +878,65 @@ ${n}
|
|
|
872
878
|
setWidth(Number(bp.value));
|
|
873
879
|
</script>
|
|
874
880
|
</body>
|
|
875
|
-
</html>`}var
|
|
881
|
+
</html>`}var Oa=k(()=>{"use strict";f()});import{createReadStream as Td,existsSync as Rd,statSync as Fd}from"fs";import Dd from"http";import So from"path";function rn(e,t,n,o="127.0.0.1",i){let a=So.resolve(e),s=new Set,d=Dd.createServer(async(l,c)=>{let m=decodeURIComponent((l.url??"/").split("?")[0]);if(m===Od){c.writeHead(200,{"content-type":"application/json"}),c.end(JSON.stringify({eds:!0}));return}if(m===Nd){c.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),c.write(`: connected
|
|
876
882
|
|
|
877
|
-
`),s.add(c),l.on("close",()=>s.delete(c));return}let p=t[
|
|
883
|
+
`),s.add(c),l.on("close",()=>s.delete(c));return}let p=t[m];if(p){c.writeHead(200,{"content-type":p.type}),c.end(p.body);return}if(i)try{let g=await i(m);if(g){c.writeHead(200,{"content-type":g.type}),c.end(g.body);return}}catch(g){c.writeHead(500,{"content-type":"text/plain"}),c.end(`Preview error: ${g instanceof Error?g.message:String(g)}`);return}let u=So.join(a,m);if(!u.startsWith(a)){c.writeHead(403),c.end("Forbidden");return}if(!Rd(u)||!Fd(u).isFile()){c.writeHead(404,{"content-type":"text/plain"}),c.end(`Not found: ${m}`);return}c.writeHead(200,{"content-type":Ld[So.extname(u).toLowerCase()]??"application/octet-stream"}),Td(u).pipe(c)});return new Promise((l,c)=>{let m=0,p=u=>{d.once("error",g=>{g.code==="EADDRINUSE"&&m<10?(m++,p(u+1)):c(g)}),d.listen(u,o,()=>{l({url:`http://${o}:${u}/`,port:u,reload:()=>{for(let g of s)g.write(`data: reload
|
|
878
884
|
|
|
879
|
-
`)},close:()=>new Promise(g=>{for(let
|
|
885
|
+
`)},close:()=>new Promise(g=>{for(let h of s)h.end();d.close(()=>g())})})})};p(n)})}var Ld,Od,Nd,Na=k(()=>{"use strict";f();Ld={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".json":"application/json; charset=utf-8",".svg":"image/svg+xml",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".avif":"image/avif",".woff":"font/woff",".woff2":"font/woff2",".ico":"image/x-icon"},Od="/__eds_ping",Nd="/__eds_events"});var xt={};O(xt,{FRAME_PREFIX:()=>ke,galleryPreview:()=>Bd,listPreviewableBlocks:()=>Le,loadBlockForPreview:()=>ue,previewBlock:()=>Ud,startFrameServer:()=>Ke,startPreview:()=>Ha});import{existsSync as ie,watch as Ma}from"fs";import{readFile as an,readdir as Md}from"fs/promises";import Z from"path";import ve from"chalk";function jo(e){return e<=480?`${e} mobile`:e<=1024?`${e} tablet`:`${e} desktop`}function Ia(e,t){if(e){let o=e.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isFinite(i)&&i>0);if(o.length)return o.map(i=>({width:i,label:jo(i),figma:!1}))}let n=t?.breakpoints;return Array.isArray(n)&&n.length?n.map(o=>({width:Number(o.width),label:typeof o.label=="string"?o.label:jo(Number(o.width)),figma:o.source==="figma"})).filter(o=>Number.isFinite(o.width)&&o.width>0):_d.map(o=>({width:o,label:jo(o),figma:!1}))}function _a(e){if(!e?.figmaFileKey||typeof e.figmaFileKey!="string")return;let t=typeof e.figmaNodeId=="string"?e.figmaNodeId.replace(":","-"):void 0,n=`https://www.figma.com/design/${e.figmaFileKey}/preview`;return t?`${n}?node-id=${t}`:n}function Ua(e){return`<div class="${e} block">
|
|
880
886
|
<div><div>
|
|
881
887
|
<h2>${e} heading</h2>
|
|
882
888
|
<p>Sample body copy for the preview. Replace with real authored content.</p>
|
|
883
889
|
<p><a href="#">Primary action</a></p>
|
|
884
890
|
<p><a href="#">Secondary action</a></p>
|
|
885
891
|
</div></div>
|
|
886
|
-
</div>`}async function
|
|
887
|
-
`)),await new Promise(o=>{let
|
|
888
|
-
`)),e.open!==!1&&await ua(a.url),await new Promise(c=>{let u=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u)})}var Gl,zl,gt=w(()=>{"use strict";m();R();ra();aa();z();I();Gl=new Set(["header","footer"]),zl=[375,768,1280]});var mo={};N(mo,{blockFromDesign:()=>Ql});import{existsSync as se}from"fs";import{readFile as Ge,writeFile as ql}from"fs/promises";import W from"path";import C from"chalk";import qt from"ora";async function Kl(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 Xl(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(B(),U)),r=await n({message:"1/7 Design source",choices:[{name:"Figma",value:"figma"},{name:"Google Stitch",value:"stitch"},{name:"Canva",value:"canva"},{name:"Sketch",value:"sketch"},{name:"Framer",value:"framer"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:x=>ye.test(x.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${He[r]} link`,validate:x=>{if(!x.trim())return"Paste the design link";if(r!=="figma")return!0;try{return Jt(x.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}),u=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),p=await zt(),f=await n({message:"7/7 Run with",choices:[...p.map(x=>({name:`${x.type}${r==="figma"&&!x.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${x.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:p[0]?`agent:${p[0].type}`:"dry-run"}),g=He[r].toLowerCase();i.info(j("Summary"));let y=O(["component",g,"content","ue model","screenshot","run"]);i.info($("component",a,y));let h=r==="figma"?(()=>{let x=Jt(s.trim());return x.nodeId?`node ${x.nodeId}`:x.fileKey})():s.trim();if(i.info($(g,h,y)),i.info($("content",d+(l?` (${l})`:""),y)),i.info($("ue model",c?"yes":"no",y)),i.info($("screenshot",u?"yes":"no (token-lean)",y)),i.info($("run",f.replace("agent:",""),y)),i.info(""),!await o({message:"Generate this block?",default:!0}))return null;let S={figmaUrl:s.trim(),name:a,provider:r,source:d,cfHint:l,ueModel:c,screenshot:u};return f==="dry-run"?S.dryRun=!0:f==="none"?S.agent="none":(S.agent=f.replace("agent:",""),S.yes=!0),S}function ga(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function Yl(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=W.isAbsolute(e)?e:W.resolve(process.cwd(),e);return!se(t)||!Vl.has(W.extname(t).toLowerCase())?null:t}async function Ql(e,t){let n=E();if(!n){i.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await i.logoOnceAnimated("Design \u2192 EDS block");let o=e,r=t;if(!o){let K=await Xl(o);if(!K){i.info("Cancelled.");return}o=K.figmaUrl,r={...r,...K}}let a=r.provider??"figma",s=He[a],d=Yl(o),l=d?d.startsWith(n+W.sep)?W.relative(n,d):d:void 0,c=null,u=l??o;if(d)i.info(` ${J.pass} Local design file ${C.dim(l)} ${C.dim("(no Figma MCP)")}`);else if(a==="figma"){let K=qt("Parsing Figma URL...").start();try{c=Jt(o),K.succeed(`Parsed Figma URL ${C.dim(c.nodeId?`node ${c.nodeId}`:`file ${c.fileKey}`)}`)}catch(Re){K.fail(Re.message),process.exitCode=1;return}}else i.info(` ${J.pass} ${s} design ${C.dim(u)}`);let p=r.name||(d?ga(W.basename(d,W.extname(d))):c?ga(c.fileName):"");if(!ye.test(p)){i.error(`Invalid block name "${p}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!r.name&&c?.nodeId&&(i.warn(`Block name "${p}" came from the Figma file name, not the selected frame.`),i.info(C.dim(` Pass ${C.cyan("--name <kebab-case>")} for a cleaner block name.`)));let f=await fe(n),g=f.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,y=qt("Resolving design source...").start(),h=await Yr({figma:c,localFile:l,token:g,projectRoot:n,preferMcp:r.mcp,refresh:r.refresh});y.succeed(`Design source ${C.dim(h.summary)}`),h.restError&&i.warn(`Figma REST fetch failed, using MCP fallback: ${h.restError}`);let b=qt("Reading design tokens & building prompt...").start(),S=await ea({provider:a,figma:c,designRef:u,blockName:p,projectRoot:n,withUeModel:r.ueModel!==!1,contentSource:r.source??"document",cfHint:r.cfHint,screenshot:r.screenshot===!0,design:h.design}),x=await Zn(S,n),T=se(W.join(n,"styles","styles.css"));if(b.succeed(T?`Loaded design tokens ${C.dim("styles/styles.css")}`:`Built prompt ${C.dim("no project tokens found")}`),i.info(C.dim(` prompt \u2192 ${x}`)),r.dryRun){i.info(""),i.info(C.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),i.info(`Prompt file: ${C.cyan(x)}`),i.info(`Block name: ${C.cyan(p)}`),i.info(`Prompt version: ${ut}`),i.info(""),i.info("Preview:"),i.info(C.dim("\u2500".repeat(60))),console.log(S);return}let oe=r.agent||f.agent;if(r.agent==="none"){i.info("Agent skipped (--agent none). Use the prompt file manually:"),i.info(` ${C.cyan(x)}`);return}let H=qt("Detecting AI agent...").start(),q=await Mr(oe);if(!q){H.fail("No AI agent found (claude, cursor, or codex)."),i.info(`Install Claude Code: ${C.cyan("npm install -g @anthropic-ai/claude-code")}`),i.info(`Or use the prompt file manually: ${C.cyan(x)}`),process.exitCode=1;return}if(H.succeed(`Agent ready ${C.cyan(q.type)} ${C.dim(q.path)}`),(h.design?.mode==="mcp"||!h.design&&a==="figma")&&a==="figma"&&!q.hasFigmaMcp&&(i.warn(`Figma MCP may not be configured for ${q.type}.`),i.info(`Run ${C.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!r.yes){let{confirm:K}=await Promise.resolve().then(()=>(B(),U));if(!await K({message:`Run ${q.type} with the generated prompt?`,default:!0})){i.info(`Prompt saved to: ${C.cyan(x)}`);return}}let Te=h.design?.mode==="spec"?"embedded design (no MCP)":h.design?.mode==="file"?`reading ${l}`:h.design?.mode==="mcp"?`via ${s} MCP (1 call, cached)`:`via ${s} MCP`;if(i.info(` ${C.dim("\u2192")} Handing off to ${C.cyan(q.type)} ${C.dim(Te)}`),h.design?.mode==="mcp"&&i.info(C.dim(" get_design_context \xD71 \u2192 cache")),!await eo(q,x,n,f.model)){process.exitCode=1;return}let Ke=W.join(n,"blocks",p);if(!(se(W.join(Ke,`${p}.js`))||se(W.join(Ke,`${p}.css`)))){i.warn(`No block files were written to blocks/${p}/ \u2014 nothing to preview.`),i.info(C.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),i.info(C.dim(` ${s} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),i.info(C.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command.")),process.exitCode=1;return}let Oa=await ed(Ke,p,r.ueModel!==!1);if(se(Ke)){let K=W.join(Ke,".eds-meta.json"),Re;if(se(K))try{Re=JSON.parse(await Ge(K,"utf-8")).breakpoints}catch{}let De=Hr(r.widths,Re),Ma={provider:a,designRef:u,figmaFileKey:c?.fileKey??null,figmaNodeId:c?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:ut,agentUsed:q.type,...De.length?{breakpoints:De}:{}};await ql(K,`${JSON.stringify(Ma,null,2)}
|
|
889
|
-
`),
|
|
890
|
-
`)),await new Promise(a=>{let s=async()=>{
|
|
892
|
+
</div>`}async function ue(e,t,n){let o=Z.join(e,"blocks",t);if(!ie(Z.join(o,`${t}.css`))&&!ie(Z.join(o,`${t}.js`)))return null;let i=null,a=Z.join(o,".eds-meta.json");if(ie(a))try{i=JSON.parse(await an(a,"utf-8"))}catch{}let s=Z.join(o,`_${t}.preview.html`),d,l=!1;return ie(s)?d=await an(s,"utf-8"):(d=Ua(t),l=!0),{name:t,sampleContent:d,breakpoints:Ia(n,i),figmaUrl:_a(i),placeholder:l}}async function Ke(e,t,n){return rn(e,{},n,"127.0.0.1",async i=>{if(!i.startsWith(ke))return;let a=i.slice(ke.length);if(!/^[a-z0-9-]+$/i.test(a))return;let s=await ue(e,a,t);if(s)return{body:on({blockName:a,breakpoints:s.breakpoints,sampleContent:s.sampleContent,frameRoute:ke+a}),type:"text/html; charset=utf-8"}})}async function Le(e){let t=Z.join(e,"blocks");if(!ie(t))return[];let n=await Md(t,{withFileTypes:!0}),o=[];for(let i of n){if(!i.isDirectory()||Id.has(i.name))continue;let a=Z.join(t,i.name);(ie(Z.join(a,`${i.name}.css`))||ie(Z.join(a,`${i.name}.js`)))&&o.push(i.name)}return o.sort()}async function Ba(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{let{execa:n}=await import("execa");await n(t,[e],{stdio:"ignore",shell:process.platform==="win32"})}catch{}}async function Ha(e,t={}){let n=P();if(!n)return r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1,null;let o=Z.join(n,"blocks",e);if(!ie(o))return r.error(`Block "${e}" not found at blocks/${e}/.`),process.exitCode=1,null;if(!ie(Z.join(o,`${e}.css`))&&!ie(Z.join(o,`${e}.js`)))return r.error(`Block "${e}" has no ${e}.css / ${e}.js to preview.`),process.exitCode=1,null;(e==="header"||e==="footer")&&(r.warn(`"${e}" is page chrome, not a content block \u2014 it won't render standalone here.`),r.info(ve.dim(` It fetches the ${e==="header"?"nav":"footer"} fragment and needs the full page runtime.`)),r.info(ve.dim(" Preview a content block instead (e.g. a block generated from a design).")));let i=null,a=Z.join(o,".eds-meta.json");if(ie(a))try{i=JSON.parse(await an(a,"utf-8"))}catch{}let s=Z.join(o,`_${e}.preview.html`),d,l=!1;ie(s)?d=await an(s,"utf-8"):(d=Ua(e),l=!0);let c=Ia(t.widths,i),m=_a(i),p="/__eds_preview_frame",u=on({blockName:e,breakpoints:c,sampleContent:d,frameRoute:p}),g=La({blockName:e,breakpoints:c,sampleContent:d,figmaUrl:m,frameRoute:p,placeholder:l}),h=Number.parseInt(t.port??"8777",10),b=await rn(n,{"/":{body:g,type:"text/html; charset=utf-8"},[p]:{body:u,type:"text/html; charset=utf-8"}},Number.isFinite(h)?h:8777);r.logoOnce(C(`Preview \u2014 ${e}`)),r.info(S("Live preview",b.url)),r.info(A("pass","breakpoints",`${c.map(v=>`${v.width}${v.figma?"\u2713":""}`).join(", ")}, Full`)),l&&r.info(A("warn","content",`placeholder \u2014 add blocks/${e}/_${e}.preview.html for real content`));let w,y=Ma(o,{recursive:!0},()=>{clearTimeout(w),w=setTimeout(()=>b.reload(),150)});return r.info(""),r.info(` ${ve.bold("\u279C")} ${ve.cyan(b.url)}`),r.info(A("pass","live reload","edits to the block refresh the browser")),t.open!==!1&&await Ba(b.url),{url:b.url,close:async()=>{y.close(),await b.close()}}}async function Ud(e,t={}){let n=await Ha(e,t);n&&(r.info(ve.dim(` Press Ctrl+C to stop.
|
|
893
|
+
`)),await new Promise(o=>{let i=async()=>{await n.close(),o(),process.exit(0)};process.on("SIGINT",i),process.on("SIGTERM",i)}))}async function Bd(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n="/__eds_frame/",o=async c=>{if(c==="/"){let m=await Le(t),p=[];for(let u of m){let g=await ue(t,u,e.widths);g&&p.push({blockName:u,breakpoints:g.breakpoints,frameRoute:n+u,figmaUrl:g.figmaUrl,placeholder:g.placeholder})}return{body:Da(p),type:"text/html; charset=utf-8"}}if(c.startsWith(n)){let m=c.slice(n.length);if(!/^[a-z0-9-]+$/i.test(m))return;let p=await ue(t,m,e.widths);return p?{body:on({blockName:m,breakpoints:p.breakpoints,sampleContent:p.sampleContent,frameRoute:n+m}),type:"text/html; charset=utf-8"}:void 0}},i=Number.parseInt(e.port??"8777",10),a=await rn(t,{},Number.isFinite(i)?i:8777,"127.0.0.1",o),s=await Le(t);r.logoOnce(C("Preview \u2014 gallery")),r.info(S("Live gallery",a.url)),r.info(A(s.length?"pass":"warn","blocks",s.length?s.join(", "):"none yet \u2014 generate one with eds block from-design"));let d,l=Ma(Z.join(t,"blocks"),{recursive:!0},()=>{clearTimeout(d),d=setTimeout(()=>a.reload(),150)});r.info(""),r.info(` ${ve.bold("\u279C")} ${ve.cyan(a.url)}`),r.info(A("pass","live reload","new & edited blocks refresh the browser")),r.info(ve.dim(` Press Ctrl+C to stop.
|
|
894
|
+
`)),e.open!==!1&&await Ba(a.url),await new Promise(c=>{let m=async()=>{l.close(),await a.close(),c(),process.exit(0)};process.on("SIGINT",m),process.on("SIGTERM",m)})}var Id,_d,ke,Oe=k(()=>{"use strict";f();R();Oa();Na();z();M();Id=new Set(["header","footer"]),_d=[375,768,1280];ke="/__eds_frame/"});var Eo={};O(Eo,{blockFromDesign:()=>Yd});import{existsSync as ae}from"fs";import{readFile as Xe,writeFile as Hd}from"fs/promises";import q from"path";import{fileURLToPath as Gd}from"url";import E from"chalk";import sn from"ora";function zd(){let e=q.dirname(Gd(import.meta.url));return[q.resolve(e,"../../samples/hero.svg"),q.resolve(e,"../../../samples/hero.svg")].find(n=>ae(n))??null}async function Wd(e=8777){try{let t=new AbortController,n=setTimeout(()=>t.abort(),400),o=await fetch(`http://127.0.0.1:${e}/__eds_ping`,{signal:t.signal});return clearTimeout(n),o.ok?(await o.json())?.eds===!0:!1}catch{return!1}}async function Jd(e){let{input:t,select:n,confirm:o}=await Promise.resolve().then(()=>(G(),H)),i=await n({message:"1/7 Design source",choices:[{name:"Figma (REST / MCP / local)",value:"figma"},{name:"Framer (scraped, headless Chromium)",value:"framer"},{name:"Google Stitch (scraped, headless Chromium)",value:"stitch"}],default:"figma"}),a=await t({message:"2/7 Component name",validate:v=>Pe.test(v.trim())||"Use kebab-case, e.g. hero-banner"}),s=e??await t({message:`3/7 ${qe[i]} link`,validate:v=>{if(!v.trim())return"Paste the design link";if(i!=="figma")return/^https?:\/\//i.test(v.trim())||"Paste a public http(s) URL to the page";try{return nn(v.trim()),!0}catch(T){return T.message}}}),d=await n({message:"4/7 Where does the content come from?",choices:[{name:"Document authoring (default EDS)",value:"document"},{name:"Universal Editor",value:"ue"},{name:"Content Fragment",value:"cf"},{name:"Mixed - Universal Editor + Content Fragment",value:"mixed"}],default:"document"}),l;(d==="cf"||d==="mixed")&&(l=(await t({message:" CF model / GraphQL persisted-query name (optional)"})).trim()||void 0);let c=await o({message:"5/7 Generate the Universal Editor model?",default:!0}),m=await o({message:"6/7 Add a screenshot MCP call for a pixel check? (off = one fewer MCP call)",default:!1}),p=await tn(),u=await n({message:"7/7 Run with",choices:[...p.map(v=>({name:`${v.type}${i==="figma"&&!v.hasFigmaMcp?" (Figma MCP not detected)":""}`,value:`agent:${v.type}`})),{name:"Preview the prompt only (--dry-run)",value:"dry-run"},{name:"Save the prompt, run it later (--agent none)",value:"none"}],default:p[0]?`agent:${p[0].type}`:"dry-run"}),g=qe[i].toLowerCase();r.info(S("Summary"));let h=I(["component",g,"content","ue model","screenshot","run"]);r.info(j("component",a,h));let b=i==="figma"?(()=>{let v=nn(s.trim());return v.nodeId?`node ${v.nodeId}`:v.fileKey})():s.trim();if(r.info(j(g,b,h)),r.info(j("content",d+(l?` (${l})`:""),h)),r.info(j("ue model",c?"yes":"no",h)),r.info(j("screenshot",m?"yes":"no (token-lean)",h)),r.info(j("run",u.replace("agent:",""),h)),r.info(""),!await o({message:"Generate this block?",default:!0}))return null;let y={figmaUrl:s.trim(),name:a,provider:i,source:d,cfHint:l,ueModel:c,screenshot:m};return u==="dry-run"?y.dryRun=!0:u==="none"?y.agent="none":(y.agent=u.replace("agent:",""),y.yes=!0),y}function Po(e){return e&&e.replace(/[-_\s]+/g,"-").replace(/[^a-z0-9-]/gi,"").toLowerCase().replace(/^-+|-+$/g,"")||"design-block"}function qd(e){try{let t=new URL(e);return t.pathname.split("/").filter(Boolean).pop()||t.hostname.split(".")[0]}catch{return""}}function Kd(e){if(e)try{let t=new URL(e).hostname.toLowerCase();if(t.includes("figma.com"))return"figma";if(t.includes("framer"))return"framer";if(t.includes("stitch"))return"stitch"}catch{}}function Vd(e){if(/^[a-z][a-z0-9+.-]*:\/\//i.test(e))return null;let t=q.isAbsolute(e)?e:q.resolve(process.cwd(),e);return!ae(t)||!Xd.has(q.extname(t).toLowerCase())?null:t}async function Yd(e,t){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found). Run this from your project root."),process.exitCode=1;return}await r.logoOnceAnimated("Design \u2192 EDS block");let o=e,i=t;if(!o&&i.sample){let D=zd();if(!D){r.error("Bundled sample design not found (samples/hero.svg)."),process.exitCode=1;return}o=D,i={name:"hero",provider:"figma",...i},r.info(` ${W.pass} Sample design ${E.dim("Kiri Bloom hero")} ${E.dim("(bundled \xB7 no token \xB7 no MCP)")}`)}if(!o){let D=await Jd(o);if(!D){r.info("Cancelled.");return}o=D.figmaUrl,i={...i,...D}}let a=i.provider;if(a&&!(a in qe)){r.error(`Unknown --provider "${a}". Use: figma, framer or stitch.`),process.exitCode=1;return}let s=a??Kd(o)??"figma",d=qe[s],l=Vd(o),c=l?l.startsWith(n+q.sep)?q.relative(n,l):l:void 0,m=null,p=c??o;if(l)r.info(` ${W.pass} Local design file ${E.dim(c)} ${E.dim("(no Figma MCP)")}`);else if(s==="figma"){let D=sn("Parsing Figma URL...").start();try{m=nn(o),D.succeed(`Parsed Figma URL ${E.dim(m.nodeId?`node ${m.nodeId}`:`file ${m.fileKey}`)}`)}catch(re){D.fail(re.message),process.exitCode=1;return}}else r.info(` ${W.pass} ${d} design ${E.dim(p)}`);let u=i.name||(l?Po(q.basename(l,q.extname(l))):m?Po(m.fileName):o?Po(qd(o)):"");if(!Pe.test(u)){r.error(`Invalid block name "${u}". Use --name with a kebab-case name (e.g., --name hero-banner).`),process.exitCode=1;return}!i.name&&m?.nodeId&&(r.warn(`Block name "${u}" came from the Figma file name, not the selected frame.`),r.info(E.dim(` Pass ${E.cyan("--name <kebab-case>")} for a cleaner block name.`)));let g=await le(n),h=g.figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT,b;if(xo(s)&&!l&&!i.dryRun&&(i.auth||i.authRefresh))if(b=$o(s),i.authRefresh||!Aa(s)){let D=(()=>{try{return new URL(o).origin}catch{return o}})();r.info(` ${E.dim("\u2192")} Opening ${E.cyan(d)} \u2014 click ${E.cyan("Sign In")} and log in, then come back here.`);let{input:re}=await Promise.resolve().then(()=>(G(),H));try{await Ta(b),await ua({loginUrl:D,statePath:b,projectRoot:n,waitForUser:async()=>{await re({message:"Press Enter once you're signed in (you don't need to open the design)"})}}),await Ra(b),r.info(` ${W.pass} Session saved ${E.dim(b)}`)}catch(ne){r.error(`Could not capture the ${d} session: ${ne instanceof Error?ne.message:String(ne)}`),process.exitCode=1;return}}else r.info(` ${W.pass} Using saved ${d} session ${E.dim(b)} ${E.dim("(--auth-refresh to re-login)")}`);let w=sn("Resolving design source...").start(),y=await xa({figma:m,localFile:c,token:h,projectRoot:n,preferMcp:i.mcp,refresh:i.refresh,provider:s,designUrl:l?void 0:o,storageStatePath:b,dryRun:i.dryRun});if(y.scrapeError){w.fail(`Scrape failed: ${y.scrapeError}`),r.info(E.dim(` Check the URL is a public ${d} page, and that Chromium is installed (${E.cyan("npx playwright install chromium")}).`)),process.exitCode=1;return}if(w.succeed(`Design source ${E.dim(y.summary)}`),y.restError&&r.warn(`Figma REST fetch failed, using MCP fallback: ${y.restError}`),y.design?.mode==="scrape"&&!i.dryRun)try{let D=JSON.parse(y.design.spec),re=(D.title??"").toLowerCase(),ne=y.design.spec.toLowerCase(),Tt=/isn'?t shared|doesn'?t exist|page not found|\b404\b/;(Tt.test(re)||Tt.test(ne)||/\bsign[ -]?in\b|\blog[ -]?in\b/.test(re)||(D.nodeCount??0)<8)&&(r.warn(`The scraped page looks like a login / error shell${D.title?` ("${D.title}")`:""} \u2014 the design may be gated or the URL wrong.`),r.info(E.dim(` Use ${E.cyan("--auth")} to log in once (or ${E.cyan("--auth-refresh")} to re-login), and confirm the URL opens the design when you're signed in.`)))}catch{}let v=sn("Reading design tokens & building prompt...").start(),T=await ja({provider:s,figma:m,designRef:p,blockName:u,projectRoot:n,withUeModel:i.ueModel!==!1,contentSource:i.source??"document",cfHint:i.cfHint,screenshot:i.screenshot===!0,design:y.design}),K=await po(T,n),J=ae(q.join(n,"styles","styles.css"));if(v.succeed(J?`Loaded design tokens ${E.dim("styles/styles.css")}`:`Built prompt ${E.dim("no project tokens found")}`),r.info(E.dim(` prompt \u2192 ${K}`)),i.dryRun){r.info(""),r.info(E.yellow("Dry run mode \u2014 prompt generated but agent not invoked.")),r.info(`Prompt file: ${E.cyan(K)}`),r.info(`Block name: ${E.cyan(u)}`),r.info(`Prompt version: ${kt}`),r.info(""),r.info("Preview:"),r.info(E.dim("\u2500".repeat(60))),console.log(T);return}let Se=i.agent||g.agent;if(i.agent==="none"){r.info("Agent skipped (--agent none). Use the prompt file manually:"),r.info(` ${E.cyan(K)}`);return}let At=sn("Detecting AI agent...").start(),Y=await na(Se);if(!Y){At.fail("No AI agent found (claude, cursor, or codex)."),r.info(`Install Claude Code: ${E.cyan("npm install -g @anthropic-ai/claude-code")}`),r.info(`Or use the prompt file manually: ${E.cyan(K)}`),process.exitCode=1;return}if(At.succeed(`Agent ready ${E.cyan(Y.type)} ${E.dim(Y.path)}`),(y.design?.mode==="mcp"||!y.design&&s==="figma")&&s==="figma"&&!Y.hasFigmaMcp&&(r.warn(`Figma MCP may not be configured for ${Y.type}.`),r.info(`Run ${E.cyan("eds figma setup")} to configure it, or set a Figma token for REST.`)),!i.yes){let{confirm:D}=await Promise.resolve().then(()=>(G(),H));if(!await D({message:`Run ${Y.type} with the generated prompt?`,default:!0})){r.info(`Prompt saved to: ${E.cyan(K)}`);return}}let Ss=y.design?.mode==="spec"?"embedded design (no MCP)":y.design?.mode==="scrape"?`scraped ${d} page (no MCP)`:y.design?.mode==="file"?`reading ${c}`:y.design?.mode==="mcp"?`via ${d} MCP (1 call, cached)`:`via ${d} MCP`;if(r.info(` ${E.dim("\u2192")} Handing off to ${E.cyan(Y.type)} ${E.dim(Ss)}`),y.design?.mode==="mcp"&&r.info(E.dim(" get_design_context \xD71 \u2192 cache")),!await uo(Y,K,n,g.model)){process.exitCode=1;return}let tt=q.join(n,"blocks",u);if(!(ae(q.join(tt,`${u}.js`))||ae(q.join(tt,`${u}.css`)))){r.warn(`No block files were written to blocks/${u}/ \u2014 nothing to preview.`),y.design?.mode==="mcp"?(r.info(E.dim(" The agent couldn't read the design, so it generated nothing. Common cause: the")),r.info(E.dim(` ${d} MCP tool-call limit (e.g. Figma Starter plan). See the log above.`)),r.info(E.dim(" Wait for the limit to reset or upgrade the plan, then re-run the same command."))):r.info(E.dim(" The agent generated nothing \u2014 see the log above for why.")),process.exitCode=1;return}let js=await Zd(tt,u,i.ueModel!==!1);if(ae(tt)){let D=q.join(tt,".eds-meta.json"),re;if(ae(D))try{re=JSON.parse(await Xe(D,"utf-8")).breakpoints}catch{}let ne=ca(i.widths,re),Tt={provider:s,designRef:p,figmaFileKey:m?.fileKey??null,figmaNodeId:m?.nodeId??null,lastSyncedAt:new Date().toISOString(),promptVersion:kt,agentUsed:Y.type,...ne.length?{breakpoints:ne}:{}};await Hd(D,`${JSON.stringify(Tt,null,2)}
|
|
895
|
+
`),ne.length&&r.info(E.dim(` Preview breakpoints: ${ne.map(ei=>ei.width).join(" \xB7 ")}`))}if(!js){r.warn(`Block "${u}" generated with issues \u2014 review the output above before publishing.`),process.exitCode=1;return}if(r.success(`Block "${u}" generation complete.`),!i.yes){let{confirm:D}=await Promise.resolve().then(()=>(G(),H));if(await D({message:"Instrument this block for analytics (dataLayer)?",default:!1})){let{trackBlock:ne}=await Promise.resolve().then(()=>(ut(),pt));await ne(u,{})}}if(!i.yes)await Qd({blockName:u,projectRoot:n,agent:Y,model:g.model,provider:s,figma:m,designRef:p});else if(i.serve){let{previewBlock:D}=await Promise.resolve().then(()=>(Oe(),xt));await D(u,{})}else r.info(` ${E.dim("\u2192")} Next: ${E.cyan(`eds block preview ${u}`)}`)}async function Qd(e){let{select:t,input:n}=await Promise.resolve().then(()=>(G(),H)),{startPreview:o}=await Promise.resolve().then(()=>(Oe(),xt)),i=null;for(r.info("");;){let a=await t({message:"Block ready \u2014 what next?",choices:[{name:"Refine \u2014 describe a change",value:"refine"},{name:i?`Preview open at ${i.url} (reloads on change)`:"Open live preview",value:"preview",disabled:i?"running":!1},{name:"Finish",value:"done"}],default:"refine"});if(a==="done")break;if(a==="preview"){await Wd()?r.info(E.dim(" A preview server is already running at http://127.0.0.1:8777.")):i=await o(e.blockName,{});continue}let s=(await n({message:"Describe the change:"})).trim();if(!s)continue;let d=Pa({blockName:e.blockName,feedback:s,provider:e.provider,figma:e.figma,designRef:e.designRef}),l=await po(d,e.projectRoot);r.info(` ${E.dim("\u2192")} Applying your change with ${E.cyan(e.agent.type)}\u2026`),await uo(e.agent,l,e.projectRoot,e.model)}i&&(r.info(E.dim(` Preview still live at ${i.url} \u2014 press Ctrl+C to stop.
|
|
896
|
+
`)),await new Promise(a=>{let s=async()=>{i&&await i.close(),a(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}))}async function Zd(e,t,n){let o=[],i=q.join(e,`${t}.js`),a=q.join(e,`${t}.css`),s=ae(i),d=ae(a);if(o.push({status:s?"pass":"fail",name:`${t}.js`,message:s?"created":"missing \u2014 agent did not write the JS file"}),o.push({status:d?"pass":"fail",name:`${t}.css`,message:d?"created":"missing \u2014 agent did not write the CSS file"}),s){let c=await Xe(i,"utf-8");o.push({status:/export\s+default/.test(c)?"pass":"fail",name:"decorate export",message:/export\s+default/.test(c)?"found":"no default export \u2014 block won't load"}),c.includes("console.log")&&o.push({status:"warn",name:"no console.log",message:"found console.log \u2014 remove before production"})}if(d){let c=await Xe(a,"utf-8");o.push({status:c.includes(`.${t}`)?"pass":"warn",name:"scoped CSS",message:c.includes(`.${t}`)?`scoped to .${t}`:`no .${t} selector \u2014 styles may leak`})}if(n){let c=ae(q.join(e,`_${t}.json`)),m=q.join(e,"..","..","component-models.json"),p=!1;if(!c&&ae(m))try{p=(await Xe(m,"utf-8")).includes(`"${t}"`)}catch{}let u=c||p;if(o.push({status:u?"pass":"warn",name:"Universal Editor model",message:u?c?`_${t}.json created`:"added to component-models.json":`missing \u2014 no _${t}.json (run with default UE generation, or --no-ue-model to skip)`}),c&&s)try{let g=await Xe(q.join(e,`_${t}.json`),"utf-8"),h=await Xe(i,"utf-8"),b=/"resourceType"\s*:\s*"[^"]*\/item"/.test(g)||/"filter"\s*:/.test(g)||/"multi"\s*:\s*true/.test(g),w=/\.children/.test(h)||/\bfor\s*\(/.test(h)||/\.forEach\s*\(/.test(h);b&&o.push({status:w?"pass":"warn",name:"multifield wired",message:w?"decorate() iterates items":"repeatable model but decorate() never iterates block.children \u2014 only one item will render"})}catch{}}r.info(S("Verification"));let l=I(o.map(c=>c.name));for(let c of o)r.info(A(c.status,c.name,c.message,l));return r.info(""),!o.some(c=>c.status==="fail")}var Xd,Co=k(()=>{"use strict";f();mo();oa();ye();la();$a();Sa();Ea();R();z();Be();Fa();bo();M();Xd=new Set([".svg",".png",".jpg",".jpeg",".webp"])});var Ga={};O(Ga,{listBlocks:()=>nm});import{existsSync as $t}from"fs";import{readFile as em,readdir as tm}from"fs/promises";import Ve from"path";import Ye from"chalk";async function nm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ve.join(t,"blocks");if(!$t(n)){r.info("No blocks/ directory found.");return}let o=await tm(n,{withFileTypes:!0}),i=[];for(let s of o){if(!s.isDirectory())continue;let d=s.name,l=Ve.join(n,d),c={name:d,hasJs:$t(Ve.join(l,`${d}.js`)),hasCss:$t(Ve.join(l,`${d}.css`)),hasUeModel:$t(Ve.join(l,`_${d}.json`))},m=Ve.join(l,".eds-meta.json");if($t(m))try{let p=JSON.parse(await em(m,"utf-8"));c.figmaSource={fileKey:p.figmaFileKey,nodeId:p.figmaNodeId,lastSyncedAt:p.lastSyncedAt}}catch{}i.push(c)}if(e.json){console.log(JSON.stringify(i,null,2));return}if(i.length===0){r.info("No blocks found.");return}r.info(S("Blocks",`${i.length} in project`));let a=I(i.map(s=>s.name));for(let s of i){let d=[s.hasJs?U.ok("js"):Ye.dim.strikethrough("js"),s.hasCss?U.ok("css"):Ye.dim.strikethrough("css")];s.hasUeModel&&d.push(U.blue("ue-model")),s.figmaSource&&d.push(`${W.figma} ${U.dotPurple("figma")}`);let l=nt(Ye.bold(s.name),a);if(r.info(` ${l} ${Ye.dim("[")}${d.join(" ")}${Ye.dim("]")}`),s.figmaSource){let c=new Date(s.figmaSource.lastSyncedAt).toLocaleDateString();r.info(` ${" ".repeat(a)} ${W.arrow} ${Ye.dim(`figma:${s.figmaSource.fileKey} \xB7 synced ${c}`)}`)}}r.info("")}var za=k(()=>{"use strict";f();R();z();M()});import Wa from"path";function Ao(e,t){return Wa.join(e,"blocks",t,"__snapshots__")}function qa(e,t,n){return Wa.join(Ao(e,t),`${t}-${n}.png`)}function St(e){return`${(e*100).toFixed(2)}%`}async function To(e,t,n=900){let o;try{({chromium:o}=await import("playwright"))}catch{throw new Error(Ja)}let i=await o.launch();try{let a=await i.newPage({viewport:{width:t,height:n}});return await a.goto(e,{waitUntil:"networkidle"}),await a.waitForTimeout(300),await a.screenshot({fullPage:!0})}finally{await i.close()}}async function Ka(){try{let e="pngjs",t="pixelmatch",{PNG:n}=await import(e),o=(await import(t)).default;return{PNG:n,pixelmatch:o}}catch{throw new Error(Ja)}}async function Xa(e,t){let{PNG:n,pixelmatch:o}=await Ka(),i=n.sync.read(e),a=n.sync.read(t);if(i.width!==a.width||i.height!==a.height)return{diffPixels:-1,totalPixels:0,ratio:1,sizeMismatch:!0,width:i.width,height:i.height};let{width:s,height:d}=i,l=new n({width:s,height:d}),c=o(i.data,a.data,l.data,s,d,{threshold:.1}),m=s*d;return{diffPixels:c,totalPixels:m,ratio:m?c/m:0,width:s,height:d,diffPng:n.sync.write(l)}}async function Va(e,t){let{PNG:n,pixelmatch:o}=await Ka(),i=n.sync.read(e),a=n.sync.read(t),s=Math.min(i.width,a.width),d=Math.min(i.height,a.height),l=new n({width:s,height:d}),c=new n({width:s,height:d});i.bitblt(l,0,0,s,d,0,0),a.bitblt(c,0,0,s,d,0,0);let m=new n({width:s,height:d}),p=o(l.data,c.data,m.data,s,d,{threshold:.1}),u=s*d;return{diffPixels:p,totalPixels:u,ratio:u?p/u:0,width:s,height:d,diffPng:n.sync.write(m)}}var Ja,Ya=k(()=>{"use strict";f();Ja=`Visual testing needs extra tools. Install them with:
|
|
897
|
+
npm i -D playwright pixelmatch pngjs && npx playwright install chromium`});var ts={};O(ts,{visualTest:()=>om});import{existsSync as Qa}from"fs";import{mkdir as Ro,readFile as Za,writeFile as jt}from"fs/promises";import fe from"path";import Fo from"chalk";async function om(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}if(t.design){await im(n,e,t);return}let o=e?[e]:await Le(n);if(!o.length){r.warn("No previewable blocks to test.");return}let i=Number.parseInt(t.port??"8788",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8788),s=Number.parseFloat(t.threshold??"0.01"),d=fe.join(n,"tmp","eds-cli","visual-diff");r.logoOnce(C("Visual test"));let l=0,c=0,m=0,p=0;try{for(let u of o){let g=await ue(n,u,t.widths);if(g){r.info(S(u));for(let h of g.breakpoints){let b=await To(es(a.url,u),h.width),w=qa(n,u,h.width),y=Qa(w);if(t.update||!y){await Ro(Ao(n,u),{recursive:!0}),await jt(w,b),y?(p++,r.info(A("pass",`${h.width}px`,"baseline updated"))):(m++,r.info(A("pass",`${h.width}px`,"baseline created")));continue}let v=await Xa(await Za(w),b);if(v.sizeMismatch){c++,r.info(A("fail",`${h.width}px`,`size changed \u2192 ${v.width}\xD7${v.height}`));continue}if(v.ratio>s){c++,await Ro(d,{recursive:!0});let T=fe.join(d,`${u}-${h.width}.diff.png`);v.diffPng&&await jt(T,v.diffPng),r.info(A("fail",`${h.width}px`,`${St(v.ratio)} changed \u2192 ${fe.relative(n,T)}`))}else l++,r.info(A("pass",`${h.width}px`,v.ratio>0?`${St(v.ratio)} (within ${St(s)})`:"identical"))}}}}catch(u){r.error(u instanceof Error?u.message:String(u)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Fo.green(`${l} passed`)} \xB7 ${Fo.yellow(`${c} changed`)} \xB7 ${m} new \xB7 ${p} updated`),c>0&&(r.warn(`${c} visual change(s). Review the diff PNGs in tmp/eds-cli/visual-diff/, then re-run with --update to accept.`),process.exitCode=1)}async function im(e,t,n){if(!t){r.error("Design diff needs a block name: eds block test <name> --design"),process.exitCode=1;return}let o=await ue(e,t,n.widths);if(!o){r.error(`Block "${t}" has no css/js to render.`),process.exitCode=1;return}let i,a,s=fe.join(e,"blocks",t,".eds-meta.json");if(Qa(s))try{let g=JSON.parse(await Za(s,"utf-8"));i=g.figmaFileKey??void 0,a=g.figmaNodeId??void 0}catch{}if(!i||!a){r.error(`"${t}" has no Figma source in .eds-meta.json \u2014 can't fetch the design image.`),process.exitCode=1;return}let l=(await le(e)).figma?.token??process.env.FIGMA_TOKEN??process.env.FIGMA_PAT;if(!l){r.error("Design diff needs a Figma token (FIGMA_TOKEN or figma.token) to render the node."),process.exitCode=1;return}let c=o.breakpoints.filter(g=>g.figma),m=(c.length?c:o.breakpoints).reduce((g,h)=>h.width>g.width?h:g,o.breakpoints[0]).width,p=Number.parseInt(n.port??"8788",10),u=await Ke(e,n.widths,Number.isFinite(p)?p:8788);r.logoOnce(C("Design \u2194 render")),r.info(S(t,`${m}px`));try{let g=await To(es(u.url,t),m);r.info(A("pass","render","block screenshot captured"));let h=await wa({fileKey:i,nodeId:a,token:l,scale:1});r.info(A("pass","design","Figma image fetched (REST)"));let b=await Va(h,g),w=fe.join(e,"tmp","eds-cli","visual-diff");await Ro(w,{recursive:!0}),await jt(fe.join(w,`${t}-design.png`),h),await jt(fe.join(w,`${t}-render.png`),g),b.diffPng&&await jt(fe.join(w,`${t}-design-diff.png`),b.diffPng),r.info(A("warn","diff",`~${St(b.ratio)} different over ${b.width}\xD7${b.height} (approximate)`)),r.info(""),r.info(Fo.dim(` Saved design / render / diff to ${fe.relative(e,w)}/${t}-*.png \u2014 compare side by side.`))}catch(g){r.error(g instanceof Error?g.message:String(g)),process.exitCode=1}finally{await u.close()}}var es,ns=k(()=>{"use strict";f();ye();ko();R();Ya();z();M();Oe();es=(e,t)=>`${e}${ke.slice(1)}${t}`});async function os(e,t){let n;try{({chromium:n}=await import("playwright"))}catch{throw new Error(rm)}let o=await n.launch();try{let i=await o.newPage({viewport:{width:t,height:900}});return await i.goto(e,{waitUntil:"networkidle"}),await i.waitForTimeout(200),await i.evaluate(am)}finally{await o.close()}}var rm,am,is=k(()=>{"use strict";f();rm=`Content checks need Playwright. Install it with:
|
|
898
|
+
npm i -D playwright && npx playwright install chromium`,am=`(() => {
|
|
899
|
+
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 rs={};O(rs,{blockCheck:()=>sm});import Do from"chalk";async function sm(e,t={}){let n=P();if(!n){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let o=e?[e]:await Le(n);if(!o.length){r.warn("No previewable blocks to check.");return}let i=Number.parseInt(t.port??"8789",10),a=await Ke(n,t.widths,Number.isFinite(i)?i:8789);r.logoOnce(C("Content check"));let s=0,d=0,l=0;try{for(let c of o){let m=await ue(n,c,t.widths);if(!m)continue;let p=m.breakpoints.reduce((g,h)=>h.width>g.width?h:g,m.breakpoints[0]).width,u=await os(`${a.url}${ke.slice(1)}${c}`,p);if(r.info(S(c,`${p}px`)),!u.length){l++,r.info(A("pass","clean","no issues"));continue}for(let g of u)g.level==="error"?s++:d++,r.info(A(g.level==="error"?"fail":"warn",g.rule,g.detail))}}catch(c){r.error(c instanceof Error?c.message:String(c)),process.exitCode=1;return}finally{await a.close()}r.info(""),r.info(`${Do.green(`${l} clean`)} \xB7 ${Do.red(`${s} error(s)`)} \xB7 ${Do.yellow(`${d} warning(s)`)}`),(s>0||t.strict&&d>0)&&(process.exitCode=1)}var as=k(()=>{"use strict";f();R();is();z();M();Oe()});function ss(e){return cn.find(t=>t.id===e)}function cs(e,t){return`
|
|
891
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
|
|
892
934
|
{
|
|
893
935
|
${t.split(`
|
|
894
936
|
`).map(n=>n&&` ${n}`).join(`
|
|
895
937
|
`)}
|
|
896
938
|
}
|
|
897
|
-
`}var
|
|
939
|
+
`}var cn,ls=k(()=>{"use strict";f();cn=[{id:"gtm",name:"Google Tag Manager",fields:[{name:"id",message:"GTM container ID",placeholder:"GTM-XXXXXXX"}],code:()=>`// Google Tag Manager - loaded from ./analytics.js (delayed phase, after LCP).
|
|
898
940
|
import { loadGTM } from './analytics.js';
|
|
899
941
|
import pageMetaPush from './page-meta.js';
|
|
900
942
|
|
|
@@ -985,19 +1027,19 @@ document.head.appendChild(cb);`},{id:"custom",name:"Custom third-party script",f
|
|
|
985
1027
|
const s = document.createElement('script');
|
|
986
1028
|
s.async = true;
|
|
987
1029
|
s.src = ${JSON.stringify(e.url||"")};
|
|
988
|
-
document.head.appendChild(s);`}]});var
|
|
1030
|
+
document.head.appendChild(s);`}]});var Oo={};O(Oo,{integrate:()=>mm});import{existsSync as cm}from"fs";import{mkdir as ds,readFile as lm,writeFile as ms}from"fs/promises";import ln from"path";import Lo from"chalk";async function mm(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Integrate - third-party service"));let{select:n,input:o}=await Promise.resolve().then(()=>(G(),H)),i=e||await n({message:"Which service do you want to add?",choices:cn.map(p=>({name:p.name,value:p.id}))}),a=ss(i);if(!a){r.error(`Unknown integration "${i}". Options: ${cn.map(p=>p.id).join(", ")}`),process.exitCode=1;return}let s={};for(let p of a.fields){let u=await o({message:` ${p.message}`,default:p.placeholder});s[p.name]=u.trim()}let d=[];if(a.module)for(let p of a.module(s)){let u=ln.join(t,p.file);await ds(ln.dirname(u),{recursive:!0}),await ms(u,p.content),d.push(p.file)}let l=a.module?`
|
|
989
1031
|
// ${a.name} (eds integrate)
|
|
990
1032
|
${a.code(s)}
|
|
991
|
-
`:
|
|
992
|
-
${l}`),
|
|
1033
|
+
`:cs(a.name,a.code(s)),c=ln.join(t,"scripts","delayed.js");await ds(ln.dirname(c),{recursive:!0});let m=cm(c)?await lm(c,"utf-8"):dm;await ms(c,`${m.replace(/\s*$/,"")}
|
|
1034
|
+
${l}`),r.info(S("Added"));for(let p of d)r.info(j(a.name,`wrote ${p}`));r.info(j(a.name,"wired into scripts/delayed.js")),r.info(""),r.info(Lo.dim(" Loads after LCP (delayed phase) - zero impact on your Core Web Vitals.")),(a.id==="gtm"||a.id==="ga4")&&r.info(Lo.dim(" Tip: gate analytics behind user consent (add the Cookiebot integration).")),a.id==="chat"&&r.info(Lo.dim(" The widget loads only when the visitor clicks the button (facade pattern).")),r.info(""),r.info(N(["Integration added"]))}var dm,No=k(()=>{"use strict";f();ls();R();z();M();dm=`// delayed.js - third-party / non-critical scripts.
|
|
993
1035
|
// Loaded in the EDS delayed phase (after LCP), so nothing here blocks the page.
|
|
994
|
-
`});var
|
|
995
|
-
`),
|
|
996
|
-
`),o){case"claude":
|
|
997
|
-
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=
|
|
998
|
-
`,{mode:384}),
|
|
999
|
-
Setup complete!`)),o!=="none"&&
|
|
1000
|
-
`);for(let l=0;l<
|
|
1001
|
-
`),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<
|
|
1002
|
-
`),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let
|
|
1003
|
-
`);for(let a=0;a<r.length;a++){let s=r[a],d=!1;for(let l of Ed)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 Rd(e){if(!Vt(Ae.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(Vt(Ae.join(e,"package-lock.json"))||Vt(Ae.join(e,"npm-shrinkwrap.json")))&&!Vt(Ae.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 Dd(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 l of Ea(t)){let c=Ae.extname(l).slice(1).toLowerCase();if(!Ad.has(c))continue;let u=Ae.relative(t,l);if(u.endsWith("aem.js")||u.endsWith("lib-franklin.js"))continue;let p=await Sd(l,"utf-8");n.push(...Td(p,u,c))}let o=await Rd(t),r=l=>n.filter(c=>c.severity===l),a={critical:r("critical").length,high:r("high").length,moderate:r("moderate").length,low:r("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(i.logoOnce(P("Security Audit")),i.info(j("Dependencies","npm audit")),o.status==="skipped")i.info(D("info","npm audit",o.note??"skipped"));else if(o.status==="ok")i.info(D("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};i.info(D(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(i.info(j("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)i.info(D("pass","code","no risky patterns found"));else{let l=[...n].sort((c,u)=>ja.indexOf(c.severity)-ja.indexOf(u.severity));for(let c of l){let u=Pd[c.severity],p=So.dim(`${c.file}:${c.line}`);i.info(` ${vt(u.status)} ${So.bold(u.label)} ${c.message} ${p}`),i.info(So.dim(` ${c.snippet}`))}}let d=de({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)});i.info(""),i.info(L([d||`${J.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var Ed,ja,Pd,Cd,Ad,Eo=w(()=>{"use strict";m();R();z();I();Ed=[{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"]}],ja=["critical","high","moderate","low"],Pd={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Cd=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Ad=new Set(["js","mjs","html","json","pem","txt"])});async function Pa(e,t,n){let o=t.ref||"main",r=n.startsWith("/")?n:`/${n}`,a=`${Fd}/${e}/${t.org}/${t.site}/${o}${r}`;i.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:r,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:r,message:d.message||`HTTP ${s.status}`}}async function Po(e,t){return Pa("preview",e,t)}async function Co(e,t){return Pa("live",e,t)}async function Ca(e,t){return Promise.all(t.map(n=>Po(e,n)))}async function Aa(e,t){return Promise.all(t.map(n=>Co(e,n)))}var Fd,Ao=w(()=>{"use strict";m();R();Fd="https://admin.hlx.page"});var To={};N(To,{preview:()=>Od,resolveAdminConfig:()=>Yt});import Ta from"chalk";import Ld from"ora";async function Od(e,t){let n=E(),o=await fe(n),r=Yt(o,t);if(!r)return;let a=Ld(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await Po(r,e[0])]:await Ca(r,e);a.stop();let d=!1;for(let l of s)l.ok?i.success(`${l.path} \u2192 ${Ta.cyan(l.previewUrl||"preview updated")}`):(i.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function Yt(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(Ta.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:r}}var Qt=w(()=>{"use strict";m();Ao();Pe();R();z()});var Ro={};N(Ro,{publish:()=>_d});import Md from"chalk";import Nd from"ora";async function _d(e,t){let n=E(),o=await fe(n),r=Yt(o,t);if(!r)return;let a=Nd(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await Co(r,e[0])]:await Aa(r,e);a.stop();let d=!1;for(let l of s)l.ok?i.success(`${l.path} \u2192 ${Md.cyan(l.liveUrl||"published")}`):(i.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Do=w(()=>{"use strict";m();Ao();Pe();R();z();Qt()});var Zt={};N(Zt,{adminWizard:()=>Id});async function Id(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 Promise.resolve().then(()=>(B(),U)),s=(await fe(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(),u=(await o({message:"Git ref",default:s.ref||"main"})).trim(),f=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||f.length===0){i.error("org, site and at least one path are required."),process.exitCode=1;return}i.info(j("Summary"));let g=O(["operation","org","site","ref","paths"]);if(i.info($("operation",d,g)),i.info($("org",l,g)),i.info($("site",c,g)),i.info($("ref",u,g)),i.info($("paths",f.join(", "),g)),i.info(""),d==="publish"&&!await r({message:`Publish ${f.length} path(s) to LIVE?`,default:!1})){i.info("Cancelled.");return}let y={org:l,site:c,ref:u};if(d==="preview"){let{preview:h}=await Promise.resolve().then(()=>(Qt(),To));await h(f,y)}else{let{publish:h}=await Promise.resolve().then(()=>(Do(),Ro));await h(f,y)}}var en=w(()=>{"use strict";m();Pe();R();z();I()});var Ra={};N(Ra,{mainMenu:()=>Gd});import{existsSync as Ud}from"fs";import{readdir as Bd}from"fs/promises";import Hd from"path";async function Fo(e){let t=Hd.join(e,"blocks");return Ud(t)?(await Bd(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function Gd(){let{select:e,input:t}=await Promise.resolve().then(()=>(B(),U));switch(await i.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 / Stitch / Canva / Sketch / Framer"},{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(()=>(Mt(),Ot));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:r}=await Promise.resolve().then(()=>(Pn(),En));await r(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:r}=await Promise.resolve().then(()=>(Se(),$e));await r(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(uo(),mo));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(Fn(),Dn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(re(),ce));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>ye.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:r}=await Promise.resolve().then(()=>(Kn(),qn));await r(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(ho(),go));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 Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(gt(),ft));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(Hn(),Bn));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 Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:r.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(at(),rt));await s(a,{});return}case"schema":{let o=E();if(!o){i.error("Not inside an EDS project (no EDS project markers found).");return}let r=await Fo(o);if(r.length===0){i.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:r.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(zn(),Gn));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:r}=await Promise.resolve().then(()=>(dt(),lt));await r()}else{let r=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(dt(),lt));await a(r.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(en(),Zt));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(()=>(vo(),yo));await r({})}else if(o==="loading"){let{auditLoading:r}=await Promise.resolve().then(()=>($o(),xo));await r({})}else{let{auditSecurity:r}=await Promise.resolve().then(()=>(Eo(),jo));await r({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(wo(),bo));await o();return}}}var Da=w(()=>{"use strict";m();R();z();Me()});m();import zd from"chalk";import{Command as Jd}from"commander";var Oo={name:"aem-eds-kit",version:"0.4.26",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"}};R();I();var M=new Jd;M.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(Oo.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&&(zd.level=0)});M.addHelpText("beforeAll",()=>P());var yt=M.command("sandbox").description("Disposable EDS sandbox repos on GitHub");yt.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(()=>(Se(),$e));await n(e,t)});yt.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Se(),$e));await e()});yt.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(()=>(Se(),$e));await n(e,t)});var Wd=M.command("template").description("Generate page templates / initial content");Wd.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(()=>(Pn(),En));await n(e,t)});M.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(()=>(Mt(),Ot));await t(e)});var qd=M.command("migrate").description("Migrate from classic AEM to EDS");qd.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(()=>(Fn(),Dn));await n(e,t)});var Kd=M.command("model").description("Compose Universal Editor models");Kd.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(()=>(Hn(),Bn));await o(e,t,n)});var Xd=M.command("schema").description("Structured data (JSON-LD) for blocks");Xd.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(()=>(zn(),Gn));await n(e,t)});var Vd=M.command("track").description("Instrument blocks for analytics");Vd.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(()=>(at(),rt));await n(e,t)});var Fa=M.command("ue").description("Universal Editor - readiness check + editor deep link");Fa.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(dt(),lt));await e()});Fa.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(()=>(dt(),lt));await n(e,t)});var tn=M.command("block").description("Manage EDS blocks");tn.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(()=>(Kn(),qn));await n(e,t)});tn.command("from-design [design]").description("Generate an EDS block from a design: a Figma/Stitch/Canva URL, 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("--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("--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(()=>(uo(),mo));await n(e,t)});tn.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(ba(),ha));await t({...e,json:M.opts().json})});tn.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(()=>(gt(),ft));e?await n.previewBlock(e,t):await n.galleryPreview(t)});var qe=M.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.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(()=>(re(),ce));await t(e)});qe.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(re(),ce));await e()});qe.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(re(),ce));await t(e)});qe.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(()=>(re(),ce));await t(e)});qe.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(re(),ce));await e()});M.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(()=>(ho(),go));await t(e)});var Yd=M.command("figma").description("Figma MCP integration");Yd.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(wo(),bo));await e()});M.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(vo(),yo));await e({json:M.opts().json})});var La=M.command("audit").description("Run project audits");La.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>($o(),xo));await e({json:M.opts().json})});La.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Eo(),jo));await e({json:M.opts().json})});M.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(()=>(en(),Zt));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(Qt(),To));await n(e,t)});M.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(()=>(en(),Zt));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Do(),Ro));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(Da(),Ra));await e()}else M.outputHelp();else await M.parseAsync()}catch(e){i.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();
|
|
1036
|
+
`});var Mo={};O(Mo,{figmaSetup:()=>gm});import{existsSync as pm}from"fs";import{mkdir as um,writeFile as fm}from"fs/promises";import se from"chalk";async function gm(){let{select:e,confirm:t}=await Promise.resolve().then(()=>(G(),H));r.logoOnce(C()),r.info(S("Figma MCP Setup Wizard")),r.info("Detecting installed AI agents...");let n=await tn(),o;if(n.length===0?(r.warn("No AI agents found (claude, cursor, codex)."),r.info(`Install Claude Code: ${se.cyan("npm install -g @anthropic-ai/claude-code")}`),o="none"):(r.success(`Found: ${n.map(a=>se.cyan(a.type)).join(", ")}`),o=await e({message:"Which agent do you want to use with eds-cli?",choices:[...n.map(a=>({name:`${a.type}${a.hasFigmaMcp?se.green(" (Figma MCP detected)"):""}`,value:a.type})),{name:"None (manual mode)",value:"none"}]})),o!=="none"){let a=n.find(s=>s.type===o);if(a&&!a.hasFigmaMcp){switch(r.warn(`Figma MCP is not configured for ${o}.
|
|
1037
|
+
`),r.info(`Install it with one of these methods:
|
|
1038
|
+
`),o){case"claude":r.info(` ${se.cyan("claude mcp add --transport sse figma-sse https://mcp.figma.com/sse")}`),r.info(" or for Figma Desktop app:"),r.info(` ${se.cyan("claude mcp add --transport http figma-desktop http://127.0.0.1:3845/mcp")}`);break;case"cursor":r.info(` Add to ${se.cyan("~/.cursor/mcp.json")}:`),r.info(se.dim(JSON.stringify({mcpServers:{figma:{url:"https://mcp.figma.com/sse"}}},null,2)));break;case"codex":r.info(" See Figma MCP docs: https://help.figma.com/hc/en-us/articles/32132100833559");break}r.info("")}else a?.hasFigmaMcp&&r.success(`Figma MCP is already configured for ${o}!`)}if(r.info(se.dim(`
|
|
1039
|
+
Note: Figma MCP requires a Figma seat (Dev or Full on paid plans for desktop server).`)),await t({message:"Save preferences to ~/.eds/config.json?",default:!0})){let a=aa();pm(a)||await um(a,{recursive:!0});let s={};o!=="none"&&(s.agent=o),await fm(ho(),`${JSON.stringify(s,null,2)}
|
|
1040
|
+
`,{mode:384}),r.success(`Config saved to ${se.cyan(ho())}`)}r.info(se.bold(`
|
|
1041
|
+
Setup complete!`)),o!=="none"&&r.info(`Try: ${se.cyan('eds block from-design "<figma-url>" --dry-run')}`)}var Io=k(()=>{"use strict";f();mo();ye();R();M()});var _o={};O(_o,{doctor:()=>wm});import{existsSync as Pt}from"fs";import{readFile as Et,readdir as hm}from"fs/promises";import Ne from"path";import{parse as ps}from"yaml";async function wm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=Ei(t);e.json||(r.logoOnce(C("Doctor")),r.info(S("Doctor",t)));let o=[];if(o.push({name:"fstab.yaml exists",status:n.hasFstab?"pass":"warn",message:n.hasFstab?"Found":"Missing - fine for Universal Editor / DA; required for document-mounted setups"}),n.hasFstab)try{let p=await Et(Ne.join(t,"fstab.yaml"),"utf-8");ps(p),o.push({name:"fstab.yaml valid YAML",status:"pass",message:"Valid"})}catch{o.push({name:"fstab.yaml valid YAML",status:"fail",message:"Invalid YAML syntax"})}if(o.push({name:"head.html exists",status:n.hasHeadHtml?"pass":"warn",message:n.hasHeadHtml?"Found":"Missing - recommended for metadata/scripts"}),o.push({name:"blocks/ directory",status:n.hasBlocks?"pass":"warn",message:n.hasBlocks?"Found":"Missing - no blocks yet"}),n.hasBlocks){let p=Ne.join(t,"blocks"),u=await hm(p,{withFileTypes:!0}),g="",h=Ne.join(t,"component-models.json");if(Pt(h))try{g=await Et(h,"utf-8")}catch{}for(let b of u){if(!b.isDirectory())continue;let w=b.name,y=Ne.join(p,w,`${w}.js`),v=Pt(y);o.push({name:`blocks/${w} has JS`,status:v?"pass":"warn",message:v?"Found":`Missing ${w}.js`}),v&&(await Et(y,"utf-8")).includes("console.log")&&o.push({name:`blocks/${w} no console.log`,status:"warn",message:"Found console.log - remove before production"});let T=Pt(Ne.join(p,w,`_${w}.json`)),K=g.includes(`"${w}"`);o.push({name:`blocks/${w} UE model`,status:T||K?"pass":"warn",message:T||K?T?`_${w}.json`:"in component-models.json":"no Universal Editor model - authors can't edit this block in UE"});let J=Ne.join(p,w,".eds-meta.json");if(Pt(J))try{let Se=JSON.parse(await Et(J,"utf-8")),At=new Date(Se.lastSyncedAt),Y=Math.floor((Date.now()-At.getTime())/(1e3*60*60*24));o.push({name:`blocks/${w} Figma sync`,status:Y>30?"warn":"pass",message:Y>30?`Last synced ${Y} days ago - design may have changed`:`Synced ${Y} days ago`})}catch{o.push({name:`blocks/${w} .eds-meta.json`,status:"warn",message:"Invalid metadata file"})}}}let i=Ne.join(t,"helix-query.yaml");if(Pt(i))try{let p=await Et(i,"utf-8");ps(p),o.push({name:"helix-query.yaml valid",status:"pass",message:"Valid YAML"})}catch{o.push({name:"helix-query.yaml valid",status:"fail",message:"Invalid YAML syntax"})}o.push({name:"~/.eds/config.json",status:wo()?"pass":"warn",message:wo()?"Found":'Missing - run "eds figma setup" to configure'});let a=o.filter(p=>p.status==="fail"),s=o.filter(p=>p.status==="warn");if(e.json){let p={pass:o.filter(u=>u.status==="pass").length,warn:s.length,fail:a.length};console.log(JSON.stringify({projectRoot:t,results:o,summary:p},null,2)),a.length>0&&(process.exitCode=1);return}let d=I(o.map(p=>p.name));for(let p of o)r.info(A(p.status,p.name,p.message,d));let l=o.filter(p=>p.status==="fail"),c=o.filter(p=>p.status==="warn"),m=o.filter(p=>p.status==="pass");r.info(""),r.info(N([ge({pass:m.length,warn:c.length,fail:l.length})])),l.length>0&&(process.exitCode=1)}var Uo=k(()=>{"use strict";f();ye();R();z();M()});var Ho={};O(Ho,{auditLoading:()=>ym});import{existsSync as xe}from"fs";import{readFile as Qe,readdir as bm,stat as us}from"fs/promises";import $e from"path";import Bo from"chalk";async function ym(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}e.json||(r.logoOnce(C("Loading Audit")),r.info(S("Loading Order Audit",t)));let n=[];if(await vm(t,n),await km(t,n),await xm(t,n),await $m(t,n),await Sm(t,n),await jm(t,n),e.json){let o={pass:n.filter(i=>i.status==="pass").length,warn:n.filter(i=>i.status==="warn").length,fail:n.filter(i=>i.status==="fail").length,info:n.filter(i=>i.status==="info").length};console.log(JSON.stringify({projectRoot:t,results:n,summary:o},null,2)),o.fail>0&&(process.exitCode=1);return}Em(n)}async function vm(e,t){let n=$e.join(e,"head.html");if(!xe(n)){t.push({rule:"head.html exists",status:"warn",message:"Missing head.html"});return}let o=await Qe(n,"utf-8"),i=o.split(`
|
|
1042
|
+
`);for(let l=0;l<i.length;l++){let c=i[l];/<script\b/i.test(c)&&!/type\s*=\s*["']module["']/i.test(c)&&!/<\/script>/.test(c)&&t.push({rule:"No render-blocking scripts in head.html",status:"fail",message:'Script without type="module" blocks rendering',file:"head.html",line:l+1})}let s=(o.match(/<link[^>]+rel=["']stylesheet["'][^>]*>/gi)||[]).filter(l=>!l.includes("styles/styles.css")&&!l.includes("styles.css"));s.length>0&&t.push({rule:"No extra stylesheets in head.html",status:"warn",message:`${s.length} extra stylesheet(s) \u2014 each competes with LCP budget`,file:"head.html"}),/<link[^>]+rel=["'](preload|preconnect)["']/i.test(o)&&t.push({rule:"No preload/preconnect in head.html",status:"warn",message:"preload/preconnect can hurt EDS LCP \u2014 resources compete with the 100KB budget",file:"head.html"}),/<script\b[^>]*>[\s\S]*?[^\s<][\s\S]*?<\/script>/i.test(o)&&t.push({rule:"No inline scripts in head.html",status:"warn",message:"Inline scripts block rendering \u2014 move to delayed.js",file:"head.html"});let d=/(?:src|href)=["'](https?:\/\/(?!(?:localhost|127\.0\.0\.1))[^"']+)["']/gi;for(let l of o.matchAll(d)){let c=l[1];c.includes("fonts.googleapis.com")||t.push({rule:"No third-party resources in head.html",status:"warn",message:`Third-party resource: ${c} \u2014 move to delayed.js`,file:"head.html"})}/<link[^>]+as=["']font["']/i.test(o)&&t.push({rule:"No font preloads in head.html",status:"warn",message:"Font preloads consume LCP bandwidth budget \u2014 let loadFonts() handle them",file:"head.html"}),t.some(l=>l.file==="head.html")||t.push({rule:"head.html is clean",status:"pass",message:"No render-blocking issues found",file:"head.html"})}async function km(e,t){let n=$e.join(e,"scripts","scripts.js");if(!xe(n)){t.push({rule:"scripts/scripts.js exists",status:"warn",message:"Missing scripts.js \u2014 cannot audit loading phases"});return}let o=await Qe(n,"utf-8"),i=o.split(`
|
|
1043
|
+
`),a=/function\s+loadEager|loadEager\s*=/i.test(o),s=/function\s+loadLazy|loadLazy\s*=/i.test(o),d=/function\s+loadDelayed|loadDelayed\s*=/i.test(o);t.push({rule:"loadEager phase exists",status:a?"pass":"fail",message:a?"Found":"Missing loadEager \u2014 LCP optimization depends on it",file:"scripts/scripts.js"}),t.push({rule:"loadLazy phase exists",status:s?"pass":"fail",message:s?"Found":"Missing loadLazy \u2014 below-fold content won't load properly",file:"scripts/scripts.js"}),t.push({rule:"loadDelayed phase exists",status:d?"pass":"warn",message:d?"Found":"Missing loadDelayed \u2014 third-party scripts may block LCP",file:"scripts/scripts.js"});let l=o.match(/setTimeout\s*\([^,]+,\s*(\d+)\s*\)/);if(d&&l){let c=Number.parseInt(l[1],10);c<3e3?t.push({rule:"Delayed phase waits >= 3s",status:"warn",message:`delayed.js loads after ${c}ms \u2014 should be >= 3000ms for LCP safety`,file:"scripts/scripts.js"}):t.push({rule:"Delayed phase waits >= 3s",status:"pass",message:`${c}ms delay before loading delayed.js`,file:"scripts/scripts.js"})}if(a){let c=o.match(/loadEager[\s\S]*?(?=function\s|const\s+load|$)/)?.[0]||"";/loadSections\s*\(/.test(c)&&t.push({rule:"loadEager loads only first section",status:"fail",message:"loadEager calls loadSections() \u2014 should only load first section for fast LCP",file:"scripts/scripts.js"})}for(let c=0;c<i.length;c++){let m=i[c];/import\s.*from\s+['"]https?:\/\//i.test(m)&&t.push({rule:"No third-party imports at top level",status:"warn",message:`Third-party import at line ${c+1} \u2014 move to delayed.js if not critical`,file:"scripts/scripts.js",line:c+1})}if(a){let c=Pm(o,"loadEager");c&&/loadHeader|loadFooter/.test(c)&&t.push({rule:"Header/footer not in loadEager",status:"warn",message:"Header/footer in loadEager delays LCP \u2014 move to loadLazy",file:"scripts/scripts.js"})}}async function xm(e,t){let n=$e.join(e,"styles","styles.css");if(!xe(n))return;let i=(await us(n)).size/1024;t.push({rule:"styles.css size within LCP budget",status:i>40?"warn":"pass",message:`${i.toFixed(1)} KB${i>40?" \u2014 large CSS competes with 100KB LCP budget":""}`,file:"styles/styles.css"});let a=await Qe(n,"utf-8");/@import\s/.test(a)&&t.push({rule:"No @import in styles.css",status:"warn",message:"@import creates a request chain \u2014 inline the CSS or use lazy-styles.css",file:"styles/styles.css"})}async function $m(e,t){let n=$e.join(e,"scripts","delayed.js");if(!xe(n)){t.push({rule:"scripts/delayed.js exists",status:"info",message:"No delayed.js \u2014 third-party scripts should go here"});return}(await Qe(n,"utf-8")).replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").trim()||t.push({rule:"delayed.js has content",status:"info",message:"delayed.js is empty \u2014 add analytics/martech here",file:"scripts/delayed.js"})}async function Sm(e,t){let n=$e.join(e,"blocks");if(!xe(n))return;let o=await bm(n,{withFileTypes:!0});for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=$e.join(n,a,`${a}.js`);if(!xe(s))continue;let d=await Qe(s,"utf-8"),l=d.split(`
|
|
1044
|
+
`),c=["jquery","lodash","moment","rxjs","d3","three","gsap","anime","chart.js","swiper"];for(let u=0;u<l.length;u++){let g=l[u].toLowerCase();for(let h of c)g.includes("from")&&g.includes(h)&&/import\s/.test(g)&&t.push({rule:"No heavy imports in blocks",status:"warn",message:`Imports "${h}" \u2014 heavy library delays section loading`,file:`blocks/${a}/${a}.js`,line:u+1})}/document\.write/i.test(d)&&t.push({rule:"No document.write in blocks",status:"fail",message:"document.write blocks parsing and can break the page",file:`blocks/${a}/${a}.js`});let p=(await us(s)).size/1024;p>20&&t.push({rule:"Block JS size reasonable",status:"warn",message:`${p.toFixed(1)} KB \u2014 consider splitting or lazy-loading parts`,file:`blocks/${a}/${a}.js`})}for(let i of o){if(!i.isDirectory())continue;let a=i.name,s=$e.join(n,a,`${a}.css`);if(!xe(s))continue;let d=await Qe(s,"utf-8"),l=/^([a-z][a-z0-9-]*)\s*\{/gm;for(let c of d.matchAll(l)){let m=c[1];["body","html","main"].includes(m)||t.push({rule:"Block CSS is scoped",status:"warn",message:`Bare element selector "${m}" \u2014 may leak styles and cause CLS. Use .${a} prefix`,file:`blocks/${a}/${a}.css`})}}}async function jm(e,t){let n=$e.join(e,"scripts","aem.js");if(!xe(n)){t.push({rule:"scripts/aem.js exists",status:"warn",message:"Missing aem.js (or lib-franklin.js) \u2014 the EDS framework library"});return}t.push({rule:"aem.js present",status:"pass",message:"Found \u2014 remember: never modify this file",file:"scripts/aem.js"})}function Pm(e,t){let o=new RegExp(`(?:async\\s+)?function\\s+${t}\\s*\\([^)]*\\)\\s*\\{`).exec(e);if(!o)return null;let i=1,a=o.index+o[0].length,s=a;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,a++;return e.slice(s,a-1)}function Em(e){let t=new Map;for(let o of e){let i=o.file||"general",a=t.get(i)??[];a.push(o),t.set(i,a)}for(let[o,i]of t){r.info(` ${W.bullet} ${Bo.underline(o)}`);for(let a of i){let s=a.line?Bo.dim(`:${a.line}`):"";r.info(` ${Rt(a.status)} ${a.rule}${s}`),a.status!=="pass"&&r.info(Bo.dim(` ${a.message}`))}r.info("")}let n={pass:e.filter(o=>o.status==="pass").length,warn:e.filter(o=>o.status==="warn").length,fail:e.filter(o=>o.status==="fail").length,info:e.filter(o=>o.status==="info").length};r.info(N([ge(n)])),n.fail>0&&(process.exitCode=1)}var Go=k(()=>{"use strict";f();R();z();M()});var Wo={};O(Wo,{auditSecurity:()=>Nm});import{existsSync as dn}from"fs";import{readFile as Cm,readdir as Am}from"fs/promises";import Me from"path";import zo from"chalk";async function*gs(e){let t=await Am(e,{withFileTypes:!0});for(let n of t){let o=Me.join(e,n.name);if(n.isDirectory()){if(Fm.has(n.name))continue;yield*gs(o)}else n.isFile()&&(yield o)}}function Lm(e,t,n){let o=[],i=e.split(`
|
|
1045
|
+
`);for(let a=0;a<i.length;a++){let s=i[a],d=!1;for(let l of Tm)l.ext.includes(n)&&(l.id==="innerhtml-static"&&d||l.re.test(s)&&(l.extra&&!l.extra(s)||(l.id==="innerhtml-dynamic"&&(d=!0),o.push({severity:l.severity,rule:l.id,message:l.message,file:t,line:a+1,snippet:s.trim().slice(0,100)}))))}return o}async function Om(e){if(!dn(Me.join(e,"package.json")))return{status:"skipped",note:"no package.json"};if(!(dn(Me.join(e,"package-lock.json"))||dn(Me.join(e,"npm-shrinkwrap.json")))&&!dn(Me.join(e,"node_modules")))return{status:"skipped",note:"no package-lock.json / node_modules \u2014 run npm install"};try{let{execa:n}=await import("execa"),{stdout:o}=await n("npm",["audit","--json"],{cwd:e,reject:!1}),a=JSON.parse(o)?.metadata?.vulnerabilities??{},s={critical:a.critical??0,high:a.high??0,moderate:a.moderate??0,low:a.low??0};return{status:s.critical+s.high+s.moderate+s.low>0?"vulnerable":"ok",counts:s}}catch(n){return{status:"skipped",note:`npm audit failed: ${n.message}`}}}async function Nm(e={}){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}let n=[];for await(let l of gs(t)){let c=Me.extname(l).slice(1).toLowerCase();if(!Dm.has(c))continue;let m=Me.relative(t,l);if(m.endsWith("aem.js")||m.endsWith("lib-franklin.js"))continue;let p=await Cm(l,"utf-8");n.push(...Lm(p,m,c))}let o=await Om(t),i=l=>n.filter(c=>c.severity===l),a={critical:i("critical").length,high:i("high").length,moderate:i("moderate").length,low:i("low").length},s=a.critical>0||a.high>0||(o.counts?.critical??0)>0||(o.counts?.high??0)>0;if(e.json){console.log(JSON.stringify({projectRoot:t,dependencies:o,findings:n,summary:{code:a}},null,2)),s&&(process.exitCode=1);return}if(r.logoOnce(C("Security Audit")),r.info(S("Dependencies","npm audit")),o.status==="skipped")r.info(A("info","npm audit",o.note??"skipped"));else if(o.status==="ok")r.info(A("pass","npm audit","no known vulnerabilities"));else{let l=o.counts??{critical:0,high:0,moderate:0,low:0};r.info(A(l.critical+l.high>0?"fail":"warn","npm audit",`${l.critical} critical, ${l.high} high, ${l.moderate} moderate, ${l.low} low \u2014 run \`npm audit fix\``))}if(r.info(S("Exploit scan","XSS \xB7 secrets \xB7 injection \xB7 tabnabbing")),n.length===0)r.info(A("pass","code","no risky patterns found"));else{let l=[...n].sort((c,m)=>fs.indexOf(c.severity)-fs.indexOf(m.severity));for(let c of l){let m=Rm[c.severity],p=zo.dim(`${c.file}:${c.line}`);r.info(` ${Rt(m.status)} ${zo.bold(m.label)} ${c.message} ${p}`),r.info(zo.dim(` ${c.snippet}`))}}let d=ge({fail:a.critical+a.high+(o.counts?.critical??0)+(o.counts?.high??0),warn:a.moderate+(o.counts?.moderate??0),info:a.low+(o.counts?.low??0)});r.info(""),r.info(N([d||`${W.pass} no vulnerabilities or risky patterns found`])),s&&(process.exitCode=1)}var Tm,fs,Rm,Fm,Dm,Jo=k(()=>{"use strict";f();R();z();M();Tm=[{id:"eval",severity:"critical",re:/\beval\s*\(/,message:"eval() executes arbitrary code \u2014 prime XSS / RCE vector",ext:["js","mjs","html"]},{id:"aws-key",severity:"critical",re:/\bAKIA[0-9A-Z]{16}\b/,message:"Hardcoded AWS access key id",ext:["js","mjs","html","json"]},{id:"private-key",severity:"critical",re:/-----BEGIN (?:RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/,message:"Embedded private key material",ext:["js","mjs","html","json","pem","txt"]},{id:"new-function",severity:"high",re:/\bnew\s+Function\s*\(/,message:"new Function() runs strings as code",ext:["js","mjs","html"]},{id:"document-write",severity:"high",re:/document\.write(?:ln)?\s*\(/,message:"document.write() enables XSS and blocks parsing",ext:["js","mjs","html"]},{id:"innerhtml-dynamic",severity:"high",re:/\.(?:inner|outer)HTML\s*=\s*[^;\n]*(?:\$\{|\+|concat)/,message:"Dynamic innerHTML assignment \u2014 sanitize or use textContent / DOM APIs",ext:["js","mjs"]},{id:"insert-adjacent-html",severity:"high",re:/insertAdjacentHTML\s*\(/,message:"insertAdjacentHTML with untrusted data is an XSS vector",ext:["js","mjs"]},{id:"js-url",severity:"high",re:/(?:href|src)\s*=\s*["']?\s*javascript:/i,message:"javascript: URL \u2014 XSS vector",ext:["js","mjs","html"]},{id:"secret",severity:"high",re:/(?:api[_-]?key|secret|access[_-]?token|auth[_-]?token|client[_-]?secret|passwd|password)\s*[:=]\s*["'][^"']{8,}["']/i,message:"Possible hardcoded secret / credential",ext:["js","mjs","html","json"],extra:e=>!/(example|placeholder|your[-_]|changeme|xxxx|<[^>]+>|\$\{)/i.test(e)},{id:"bearer-token",severity:"high",re:/Bearer\s+[A-Za-z0-9\-._~+/]{20,}/,message:"Hardcoded bearer token",ext:["js","mjs","html","json"]},{id:"innerhtml-static",severity:"moderate",re:/\.(?:inner|outer)HTML\s*=/,message:"innerHTML assignment \u2014 confirm the content is trusted / sanitized",ext:["js","mjs"]},{id:"insecure-url",severity:"moderate",re:/(?:href|src)\s*=\s*["']http:\/\/(?!localhost|127\.0\.0\.1)/i,message:"Insecure http:// resource \u2014 mixed content, use https://",ext:["html","js","mjs"]},{id:"target-blank",severity:"moderate",re:/target\s*=\s*["']_blank["']/,message:'target="_blank" without rel="noopener" \u2014 reverse tabnabbing',ext:["html","js","mjs"],extra:e=>!/rel\s*=\s*["'][^"']*noopener/i.test(e)},{id:"postmessage-wildcard",severity:"moderate",re:/postMessage\s*\([^,]+,\s*["']\*["']\s*\)/,message:"postMessage to '*' origin \u2014 restrict the target origin",ext:["js","mjs"]},{id:"inline-handler",severity:"low",re:/\son[a-z]+\s*=\s*["']/i,message:"Inline event handler \u2014 move to addEventListener (CSP-unfriendly)",ext:["html"]},{id:"console-log",severity:"low",re:/console\.(?:log|debug)\s*\(/,message:"console.log / debug left in code \u2014 potential info leak",ext:["js","mjs"]}],fs=["critical","high","moderate","low"],Rm={critical:{status:"fail",label:"CRIT"},high:{status:"fail",label:"HIGH"},moderate:{status:"warn",label:"MOD "},low:{status:"info",label:"LOW "}},Fm=new Set(["node_modules",".git","dist","build",".vscode","coverage"]),Dm=new Set(["js","mjs","html","json","pem","txt"])});async function hs(e,t,n){let o=t.ref||"main",i=n.startsWith("/")?n:`/${n}`,a=`${Mm}/${e}/${t.org}/${t.site}/${o}${i}`;r.debug(`POST ${a}`);let s=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"}}),d=await s.json().catch(()=>({})),l=d;return s.ok?{ok:!0,status:s.status,path:i,previewUrl:l.preview?.url,liveUrl:l.live?.url}:{ok:!1,status:s.status,path:i,message:d.message||`HTTP ${s.status}`}}async function qo(e,t){return hs("preview",e,t)}async function Ko(e,t){return hs("live",e,t)}async function ws(e,t){return Promise.all(t.map(n=>qo(e,n)))}async function bs(e,t){return Promise.all(t.map(n=>Ko(e,n)))}var Mm,Xo=k(()=>{"use strict";f();R();Mm="https://admin.hlx.page"});var Vo={};O(Vo,{preview:()=>_m,resolveAdminConfig:()=>mn});import ys from"chalk";import Im from"ora";async function _m(e,t){let n=P(),o=await le(n),i=mn(o,t);if(!i)return;let a=Im(`Previewing ${e.length} path(s)...`).start(),s=e.length===1?[await qo(i,e[0])]:await ws(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${ys.cyan(l.previewUrl||"preview updated")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}function mn(e,t){let n=t.org||e.admin?.org,o=t.site||e.admin?.site,i=t.ref||e.admin?.ref||"main";if(!n||!o){r.error("Missing --org and --site. Set them via flags or in .edsrc.json:"),r.info(ys.dim(' { "admin": { "org": "my-org", "site": "my-site" } }')),process.exitCode=1;return}return{org:n,site:o,ref:i}}var pn=k(()=>{"use strict";f();Xo();ye();R();z()});var Yo={};O(Yo,{publish:()=>Hm});import Um from"chalk";import Bm from"ora";async function Hm(e,t){let n=P(),o=await le(n),i=mn(o,t);if(!i)return;let a=Bm(`Publishing ${e.length} path(s)...`).start(),s=e.length===1?[await Ko(i,e[0])]:await bs(i,e);a.stop();let d=!1;for(let l of s)l.ok?r.success(`${l.path} \u2192 ${Um.cyan(l.liveUrl||"published")}`):(r.error(`${l.path} \u2014 ${l.message}`),d=!0);d&&(process.exitCode=1)}var Qo=k(()=>{"use strict";f();Xo();ye();R();z();pn()});var un={};O(un,{adminWizard:()=>Gm});async function Gm(e){let t=P();if(!t){r.error("Not inside an EDS project (no EDS project markers found)."),process.exitCode=1;return}r.logoOnce(C("Admin API \u2014 preview / publish"));let{select:n,input:o,confirm:i}=await Promise.resolve().then(()=>(G(),H)),s=(await le(t)).admin??{},d=e??await n({message:"What do you want to do?",choices:[{name:"Preview pages (staging)",value:"preview"},{name:"Publish pages (go live)",value:"publish"}]}),l=(await o({message:"GitHub org / owner",default:s.org})).trim(),c=(await o({message:"Repository / site",default:s.site})).trim(),m=(await o({message:"Git ref",default:s.ref||"main"})).trim(),u=(await o({message:"Paths (space- or comma-separated)",default:"/"})).split(/[\s,]+/).filter(Boolean);if(!l||!c||u.length===0){r.error("org, site and at least one path are required."),process.exitCode=1;return}r.info(S("Summary"));let g=I(["operation","org","site","ref","paths"]);if(r.info(j("operation",d,g)),r.info(j("org",l,g)),r.info(j("site",c,g)),r.info(j("ref",m,g)),r.info(j("paths",u.join(", "),g)),r.info(""),d==="publish"&&!await i({message:`Publish ${u.length} path(s) to LIVE?`,default:!1})){r.info("Cancelled.");return}let h={org:l,site:c,ref:m};if(d==="preview"){let{preview:b}=await Promise.resolve().then(()=>(pn(),Vo));await b(u,h)}else{let{publish:b}=await Promise.resolve().then(()=>(Qo(),Yo));await b(u,h)}}var fn=k(()=>{"use strict";f();ye();R();z();M()});var vs={};O(vs,{mainMenu:()=>qm});import{existsSync as zm}from"fs";import{readdir as Wm}from"fs/promises";import Jm from"path";async function Zo(e){let t=Jm.join(e,"blocks");return zm(t)?(await Wm(t,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name):[]}async function qm(){let{select:e,input:t}=await Promise.resolve().then(()=>(G(),H));switch(await r.logoOnceAnimated(""),await e({message:"Choose an action",choices:[{name:"Set up project",value:"init",description:"Authoring model, CI, naming"},{name:"Page template",value:"template",description:"Generate initial content"},{name:"Sandbox repo",value:"sandbox",description:"Disposable GitHub repo"},{name:"Block from design",value:"from-design",description:"Figma, Framer or Google Stitch"},{name:"Migrate component",value:"migrate",description:"Classic AEM component \u2192 EDS"},{name:"Scaffold UE",value:"scaffold",description:"Universal Editor components"},{name:"Empty block",value:"create",description:"Create a bare block"},{name:"Integration",value:"integrate",description:"GTM, chat, consent\u2026"},{name:"Model fields",value:"model",description:"Add fields to a block model (partials)"},{name:"Analytics",value:"track",description:"Instrument a block (dataLayer)"},{name:"Structured data",value:"schema",description:"Add JSON-LD to a block"},{name:"Universal Editor",value:"ue",description:"Check readiness / open the editor"},{name:"Preview block",value:"preview-block",description:"Live preview in the browser"},{name:"Pages",value:"admin",description:"Preview / publish (Admin API)"},{name:"Audit",value:"audit",description:"Doctor / loading / security"},{name:"Figma MCP",value:"figma-setup",description:"Configure the connection"}]})){case"init":{let{initProject:o}=await Promise.resolve().then(()=>(qt(),Jt));await o({});return}case"template":{let o=await t({message:"Template name",validate:a=>!!a.trim()||"Required"}),{templateNew:i}=await Promise.resolve().then(()=>(_n(),In));await i(o.trim(),{});return}case"sandbox":{let o=await t({message:"Sandbox repo name",validate:a=>/^[a-z0-9][a-z0-9._-]*$/i.test(a.trim())||"Use a valid repo name"}),{sandboxNew:i}=await Promise.resolve().then(()=>(Re(),Te));await i(o.trim(),{});return}case"from-design":{let{blockFromDesign:o}=await Promise.resolve().then(()=>(Co(),Eo));await o(void 0,{});return}case"migrate":{let{migrateComponent:o}=await Promise.resolve().then(()=>(Wn(),zn));await o(void 0,{});return}case"scaffold":{let{scaffoldInteractive:o}=await Promise.resolve().then(()=>(ce(),me));await o();return}case"create":{let o=await t({message:"Block name",validate:a=>Pe.test(a.trim())||"Use kebab-case, e.g. hero-banner"}),{createBlock:i}=await Promise.resolve().then(()=>(ao(),ro));await i(o.trim(),{});return}case"integrate":{let{integrate:o}=await Promise.resolve().then(()=>(No(),Oo));await o(void 0);return}case"preview-block":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{previewBlock:s}=await Promise.resolve().then(()=>(Oe(),xt));await s(a,{});return}case"model":{let{modelAdd:o}=await Promise.resolve().then(()=>(eo(),Zn));await o(void 0,[],{});return}case"track":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block to instrument?",choices:i.map(d=>({name:d,value:d}))}),{trackBlock:s}=await Promise.resolve().then(()=>(ut(),pt));await s(a,{});return}case"schema":{let o=P();if(!o){r.error("Not inside an EDS project (no EDS project markers found).");return}let i=await Zo(o);if(i.length===0){r.warn("No blocks found in blocks/.");return}let a=await e({message:"Which block?",choices:i.map(d=>({name:d,value:d}))}),{schemaBlock:s}=await Promise.resolve().then(()=>(no(),to));await s(a,{});return}case"ue":{if(await e({message:"Universal Editor:",choices:[{name:"Check readiness (which blocks are editable)",value:"check"},{name:"Open a page in the editor",value:"open"}]})==="check"){let{ueCheck:i}=await Promise.resolve().then(()=>(wt(),ht));await i()}else{let i=await t({message:"Page path",default:"/"}),{ueOpen:a}=await Promise.resolve().then(()=>(wt(),ht));await a(i.trim()||"/",{})}return}case"admin":{let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o();return}case"audit":{let o=await e({message:"Which audit?",choices:[{name:"Doctor \u2014 overall project health",value:"doctor"},{name:"Loading \u2014 three-phase / LCP budget",value:"loading"},{name:"Security \u2014 vulnerabilities & exploit patterns",value:"security"}]});if(o==="doctor"){let{doctor:i}=await Promise.resolve().then(()=>(Uo(),_o));await i({})}else if(o==="loading"){let{auditLoading:i}=await Promise.resolve().then(()=>(Go(),Ho));await i({})}else{let{auditSecurity:i}=await Promise.resolve().then(()=>(Jo(),Wo));await i({})}return}case"figma-setup":{let{figmaSetup:o}=await Promise.resolve().then(()=>(Io(),Mo));await o();return}}}var ks=k(()=>{"use strict";f();R();z();Be()});f();import Km from"chalk";import{Command as Xm}from"commander";var ti={name:"aem-eds-kit",version:"0.4.33",description:"CLI for AEM Edge Delivery Services with Figma MCP integration",type:"module",engines:{node:">=20"},bin:{eds:"dist/bin/eds.js"},files:["dist","samples","CHANGELOG.md"],scripts:{dev:"tsx src/bin/eds.ts",build:"tsup",test:"vitest run","test:watch":"vitest",lint:"biome check src/ tests/","lint:fix":"biome check --write src/ tests/",typecheck:"tsc --noEmit",prepare:"git config core.hooksPath .githooks || true",prepublishOnly:"npm run build"},keywords:["aem","edge-delivery-services","helix","figma","mcp","cli","adobe"],author:"Piotr Godycki <piotrgodycki@yahoo.com>",license:"MIT",repository:{type:"git",url:"git+https://github.com/piotrgodycki/aem-eds-kit.git"},homepage:"https://piotrgodycki.github.io/aem-eds-kit/",bugs:{url:"https://github.com/piotrgodycki/aem-eds-kit/issues"},dependencies:{"@inquirer/prompts":"^7.0.0",chalk:"^5.4.0",commander:"^13.0.0",execa:"^9.5.0","fast-xml-parser":"^5.11.2",ora:"^8.1.0",yaml:"^2.6.0",zod:"^3.24.0"},devDependencies:{"@biomejs/biome":"^1.9.0","@types/node":"^22.0.0",tsup:"^8.3.0",tsx:"^4.19.0",typescript:"^5.7.0",vitest:"^2.1.0"},optionalDependencies:{"@modelcontextprotocol/sdk":"^1.29.0",pixelmatch:"^6.0.0",playwright:"^1.64.0",pngjs:"^7.0.0"}};R();M();var _=new Xm;_.name("eds").description("CLI for AEM Edge Delivery Services with Figma integration").version(ti.version).option("--verbose","Enable verbose output").option("--quiet","Suppress non-error output").option("--json","Output in JSON format").option("--no-color","Disable color output").showHelpAfterError("(add --help for usage)").hook("preAction",e=>{let t=e.opts();t.verbose&&r.setLevel("debug"),t.quiet&&r.setQuiet(!0),t.color===!1&&(Km.level=0)});_.addHelpText("beforeAll",()=>C());var Ct=_.command("sandbox").description("Disposable EDS sandbox repos on GitHub");Ct.command("new <name>").description("Create a disposable EDS repo from a boilerplate (GitHub auth, no gh required)").option("--org <org>","Create under a GitHub org (else your account)").option("--boilerplate <repo>","Template repo (default adobe/aem-boilerplate)").option("--ue","Use the crosswalk / Universal Editor boilerplate").option("--private","Create a private repo").option("--yes","Skip the guided prompts (use flags/defaults)").action(async(e,t)=>{let{sandboxNew:n}=await Promise.resolve().then(()=>(Re(),Te));await n(e,t)});Ct.command("login").description("Authorize GitHub (OAuth device flow or a token) - no gh needed").action(async()=>{let{sandboxLogin:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("logout").description("Remove the stored GitHub token").action(async()=>{let{sandboxLogout:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("list").description("List your EDS sandboxes (repos tagged eds-sandbox)").action(async()=>{let{sandboxList:e}=await Promise.resolve().then(()=>(Re(),Te));await e()});Ct.command("rm <name>").description("Delete a sandbox repo (destructive)").option("--org <org>","Owner org (else your account)").option("--yes","Skip the confirmation").action(async(e,t)=>{let{sandboxRm:n}=await Promise.resolve().then(()=>(Re(),Te));await n(e,t)});var Vm=_.command("template").description("Generate page templates / initial content");Vm.command("new <name>").description("Generate EDS page initial content (sections + blocks + metadata), DA push optional").option("--path <path>","Content path (default: /templates/<name>)").option("--title <title>","Page title").option("--description <text>","Page description").option("--blocks <list>","Comma-separated block ids to seed",e=>e.split(",").map(t=>t.trim())).option("--area <area>","Site area / template label (stored in metadata)").option("--authoring <model>","Force authoring model: da | gdrive | sharepoint | ue").option("--push","Push the page to DA (da.live)").option("--org <org>","DA org (else from .edsrc.json)").option("--site <site>","DA site (else from .edsrc.json)").option("--yes","Skip prompts").action(async(e,t)=>{let{templateNew:n}=await Promise.resolve().then(()=>(_n(),In));await n(e,t)});_.command("init").description("Set up a freshly cloned EDS boilerplate for your authoring model (interactive)").option("--name <name>","Project name (kebab-case)").option("--authoring <model>","Authoring model: ue | da | gdrive | sharepoint").option("--mountpoint <url>","Content source URL (document models)").option("--org <org>","DA org (authoring=da)").option("--site <site>","DA site (authoring=da)").option("--no-ci","Skip the GitHub Actions CI workflow").option("--no-env","Skip the local-dev .env (aem up config)").option("--no-xwalk","Skip xwalk.json (UE multi-field)").option("--yes","Skip prompts; apply with flags/defaults").action(async e=>{let{initProject:t}=await Promise.resolve().then(()=>(qt(),Jt));await t(e)});var Ym=_.command("migrate").description("Migrate from classic AEM to EDS");Ym.command("component [dir]").description("Migrate a classic AEM component's dialog into an EDS block + UE model").option("--name <name>","Block name (otherwise inferred from the component)").option("--clientlib <dir>","Path to the component's clientlib (otherwise auto-detected)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{migrateComponent:n}=await Promise.resolve().then(()=>(Wn(),zn));await n(e,t)});var Qm=_.command("model").description("Compose Universal Editor models");Qm.command("add <block> [partials...]").description("Add reusable field groups (partials) to a block's UE model").option("--yes","Skip prompts").action(async(e,t,n)=>{let{modelAdd:o}=await Promise.resolve().then(()=>(eo(),Zn));await o(e,t,n)});var Zm=_.command("schema").description("Structured data (JSON-LD) for blocks");Zm.command("block <name>").description("Inject a JSON-LD (schema.org) builder into a block's decorate()").option("--type <type>","schema.org type (Article, FAQPage, Product, ...)").option("--yes","Skip prompts").action(async(e,t)=>{let{schemaBlock:n}=await Promise.resolve().then(()=>(no(),to));await n(e,t)});var ep=_.command("track").description("Instrument blocks for analytics");ep.command("block <name>").description("Add dataLayer tracking (click + form submit) to a block's decorate()").option("--no-click","Skip click tracking").option("--no-submit","Skip form-submit tracking").action(async(e,t)=>{let{trackBlock:n}=await Promise.resolve().then(()=>(ut(),pt));await n(e,t)});var xs=_.command("ue").description("Universal Editor - readiness check + editor deep link");xs.command("check").description("Check whether blocks are Universal-Editor-ready (offline)").action(async()=>{let{ueCheck:e}=await Promise.resolve().then(()=>(wt(),ht));await e()});xs.command("open [path]").description("Open a page in the hosted Universal Editor (preview host from git)").option("--org <slug>","IMS org slug (skips the org picker)").option("--ref <branch>","Branch/ref for the preview host (default: main)").option("--url <host>","Override the delivery host (e.g. main--repo--owner.aem.page)").option("--no-open","Print the link without opening the browser").action(async(e,t)=>{let{ueOpen:n}=await Promise.resolve().then(()=>(wt(),ht));await n(e,t)});var Ze=_.command("block").description("Manage EDS blocks");Ze.command("create <name>").description("Scaffold a new EDS block (with Universal Editor model by default)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").action(async(e,t)=>{let{createBlock:n}=await Promise.resolve().then(()=>(ao(),ro));await n(e,t)});Ze.command("from-design [design]").description("Generate an EDS block from a design: a Figma URL, a Framer/Stitch page (scraped with headless Chromium), or a local SVG/PNG export (quota-free, no MCP). Interactive wizard when run with no argument.").option("--name <name>","Override the inferred block name").option("--provider <type>","Design source: figma | framer | stitch (else detected from the URL)").option("--agent <type>","Force agent type (claude|cursor|codex|none)").option("--dry-run","Generate prompt only, do not invoke agent").option("--source <type>","Content source: document|ue|cf|mixed (default: document)").option("--widths <list>","Design frame widths for preview breakpoints (e.g. 390,768,1440)").option("--no-ue-model","Skip the Universal Editor model (generated by default)").option("--screenshot","Add a screenshot MCP call for pixel verification (opt-in; costs a call)").option("--mcp","Force the Figma MCP adapter even when a REST token is set").option("--refresh","Ignore the cached design snapshot and re-fetch").option("--auth","Scrape with a logged-in session (Framer/Stitch) \u2014 login captured once, then reused").option("--auth-refresh","Force a fresh scrape login even if a session is saved").option("--sample","Use the bundled sample design (Kiri Bloom hero) \u2014 no URL, no token, no MCP").option("--serve","Auto-start the live preview after generating (non-interactive runs only)").option("--yes","Skip confirmation prompts").action(async(e,t)=>{let{blockFromDesign:n}=await Promise.resolve().then(()=>(Co(),Eo));await n(e,t)});Ze.command("list").description("List all blocks in the project").action(async e=>{let{listBlocks:t}=await Promise.resolve().then(()=>(za(),Ga));await t({...e,json:_.opts().json})});Ze.command("preview [name]").description("Serve a live, breakpoint-switchable preview of a block \u2014 or a gallery of all blocks when no name is given").option("--port <port>","Port to serve on (default: 8777, falls back if taken)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--no-open","Do not open the browser automatically").action(async(e,t)=>{let n=await Promise.resolve().then(()=>(Oe(),xt));e?await n.previewBlock(e,t):await n.galleryPreview(t)});Ze.command("test [name]").description("Visual-regression test a block (or all blocks) against committed baselines").option("--update","(Re)write the baseline screenshots instead of comparing").option("--threshold <ratio>","Max changed-pixel ratio before failing (default 0.01 = 1%)").option("--design","Compare the rendered block against its Figma design image (needs a token)").option("--widths <list>","Comma-separated breakpoint widths (e.g. 375,768,1280)").option("--port <port>","Port for the internal preview server (default: 8788)").action(async(e,t)=>{let{visualTest:n}=await Promise.resolve().then(()=>(ns(),ts));await n(e,t)});Ze.command("check [name]").description("Content, link and a11y check on a block's rendered DOM (or all blocks)").option("--strict","Fail on warnings too, not just errors").option("--widths <list>","Comma-separated breakpoint widths (uses the widest)").option("--port <port>","Port for the internal preview server (default: 8789)").action(async(e,t)=>{let{blockCheck:n}=await Promise.resolve().then(()=>(as(),rs));await n(e,t)});var et=_.command("scaffold").description("Scaffold standard UE components and blocks").action(async()=>{let{scaffoldInteractive:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("ue").description("Scaffold default-content UE components + a field-reference block (all 17 fields)").action(async()=>{let{scaffoldUe:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("blocks [names...]").description("Scaffold standard blocks (hero, cards, columns, accordion, embed) with UE models").action(async e=>{let{scaffoldBlocks:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("ci").description("Scaffold a GitHub Actions workflow (doctor + audits + project lint/build)").action(async()=>{let{scaffoldCi:e}=await Promise.resolve().then(()=>(ce(),me));await e()});et.command("helpers [names...]").description("Scaffold scripts/utils.js with chosen EDS helpers (interactive picker)").action(async e=>{let{scaffoldHelpers:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("env").description("Write a local-dev .env for `aem up` (AEM_OPEN / AEM_PORT / AEM_PAGES_URL)").option("--open <path>","AEM_OPEN - path opened on start (default: /)").option("--port <port>","AEM_PORT - proxy port (default: 3007)").option("--pages-url <url>","AEM_PAGES_URL - content origin (default: from git remote)").option("--yes","Skip prompts; use flags/defaults").action(async e=>{let{scaffoldEnv:t}=await Promise.resolve().then(()=>(ce(),me));await t(e)});et.command("xwalk").description("Write xwalk.json enabling Universal Editor multi-field support").action(async()=>{let{scaffoldXwalk:e}=await Promise.resolve().then(()=>(ce(),me));await e()});_.command("integrate [type]").description("Add a third-party service (GTM, GA4, chat, consent) to scripts/delayed.js").action(async e=>{let{integrate:t}=await Promise.resolve().then(()=>(No(),Oo));await t(e)});var tp=_.command("figma").description("Figma MCP integration");tp.command("setup").description("Configure Figma MCP for your AI agent").action(async()=>{let{figmaSetup:e}=await Promise.resolve().then(()=>(Io(),Mo));await e()});_.command("doctor").description("Audit your EDS project for common issues").action(async()=>{let{doctor:e}=await Promise.resolve().then(()=>(Uo(),_o));await e({json:_.opts().json})});var $s=_.command("audit").description("Run project audits");$s.command("loading").description("Check loading order (eager/lazy/delayed phases, LCP budget)").action(async()=>{let{auditLoading:e}=await Promise.resolve().then(()=>(Go(),Ho));await e({json:_.opts().json})});$s.command("security").description("Scan for vulnerabilities (npm audit) and exploit patterns (XSS, secrets, tabnabbing)").action(async()=>{let{auditSecurity:e}=await Promise.resolve().then(()=>(Jo(),Wo));await e({json:_.opts().json})});_.command("preview [paths...]").description("Preview pages via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o("preview");return}let{preview:n}=await Promise.resolve().then(()=>(pn(),Vo));await n(e,t)});_.command("publish [paths...]").description("Publish pages to live via Admin API (interactive wizard when run with no paths)").option("--org <org>","GitHub org/owner").option("--site <site>","Repository name").option("--ref <ref>","Git ref (default: main)").action(async(e,t)=>{if(!e||e.length===0){let{adminWizard:o}=await Promise.resolve().then(()=>(fn(),un));await o("publish");return}let{publish:n}=await Promise.resolve().then(()=>(Qo(),Yo));await n(e,t)});(async()=>{try{if(process.argv.slice(2).length===0)if(process.stdout.isTTY){let{mainMenu:e}=await Promise.resolve().then(()=>(ks(),vs));await e()}else _.outputHelp();else await _.parseAsync()}catch(e){r.error(e instanceof Error?e.message:String(e)),process.exitCode=1}})();
|