@melonbuild/create 0.0.0-stage → 0.2.1

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/scripts/mb.mjs ADDED
@@ -0,0 +1,732 @@
1
+ #!/usr/bin/env node
2
+ // MelonBuild AST query tool: read the AST in small, targeted slices instead of loading it whole.
3
+ // Zero dependencies. Node >= 18.
4
+ import {readFileSync,readdirSync,statSync,renameSync,existsSync,writeFileSync,unlinkSync} from 'node:fs';
5
+ import {createHash} from 'node:crypto';
6
+ import {join,basename,extname} from 'node:path';
7
+
8
+ const USAGE=`mb.mjs <command> <ast.json> [args]
9
+
10
+ outline <ast> [--section <id>] [--all] screens, state groups, components, connectors
11
+ tokens <ast> colors / type / radius / spacing / shadow usage
12
+ show <ast> <target...> [--depth N] [--expand]
13
+ compact subtree(s) + resolved styles; several targets
14
+ share one styles block; --expand inlines component refs
15
+ diff <ast> <idA> <idB> what changes from A to B (state merging)
16
+ texts <ast> [id] all text content (deduped)
17
+ check <ast> <dir...> [--unit id] texts / images missing from generated code
18
+ assets <ast> [--apply] flag plain-shape SVGs (→ CSS); for files from older CLIs
19
+ also rename hashed names, merge duplicates, repair SVGs
20
+ subset <ast> <id...> -o <out> keep only these units (+ the templates and styles they use);
21
+ then: melonbuild download-images <out> --image-dir … --output …
22
+ prune <ast> <code-dir...> [--apply] delete downloaded images the code never references
23
+
24
+ path = <id or template>/<childIndex>/... e.g. 12:34/0/2`;
25
+
26
+ const [cmd,file,...rest]=process.argv.slice(2);
27
+ const wantsHelp=[cmd,file,...rest].some(a=>a==='-h'||a==='--help');
28
+ if(!cmd||!file||wantsHelp){console.log(USAGE);process.exit(cmd?0:1);}
29
+ const ast=JSON.parse(readFileSync(file,'utf8'));
30
+ const T=ast.templates||{},G=ast.globalStyles||{};
31
+ const opt=(name,def)=>{const i=rest.indexOf(name);if(i<0)return def;const v=rest[i+1];rest.splice(i,2);return v;};
32
+
33
+ // ---------- basics ----------
34
+ const isRef=n=>n&&typeof n.t==='string';
35
+ const kids=n=>Array.isArray(n?.children)?n.children:[];
36
+ const STYLE_ATTRS=['layout','fills','fontStyle','strokes','effects'];
37
+ const short=(s,n)=>{s=String(s).replace(/\s+/g,' ');return s.length>n?s.slice(0,n-1)+'…':s;};
38
+ // 图片链接只显示短标识:远程签名 URL 取图片 id 前 8 位,本地路径取文件名
39
+ const shortImage=v=>v.replace(/https:\/\/[^\s"')]*?\/images\/([0-9a-f-]{8})[^\s"')]*/g,'img:$1').replace(/(?:\.{0,2}\/)?(?:[^\s"'(),]*\/)+([^\/\s"'(),]+\.(?:svg|png|jpe?g|webp|gif))/g,'$1');
40
+ const shortJSON=v=>shortImage(JSON.stringify(v));
41
+ const val=v=>{
42
+ if(v&&typeof v==='object'){
43
+ if(typeof v.$param==='string')return '{'+v.$param+'}';
44
+ if('x' in v&&'y' in v&&Object.keys(v).length===2)return v.x+','+v.y;
45
+ return JSON.stringify(v);
46
+ }
47
+ if(typeof v==='string'){
48
+ v=shortImage(v);
49
+ return /^[^\s"=]+$/.test(v)?v:JSON.stringify(v);
50
+ }
51
+ return String(v);
52
+ };
53
+ const resolved=new Map();
54
+ function style(key){
55
+ if(resolved.has(key))return resolved.get(key);
56
+ let v=G[key];
57
+ if(v&&typeof v==='object'&&!Array.isArray(v)&&typeof v.extends==='string'){
58
+ const {extends:ext,...own}=v;let base={};
59
+ for(const b of ext.split(',').map(s=>s.trim()).filter(Boolean)){const bv=style(b);if(bv&&typeof bv==='object')base={...base,...bv};}
60
+ v={...base,...own};
61
+ }
62
+ resolved.set(key,v);return v;
63
+ }
64
+ // template parameter environment of a ref: params → variant → args (args may point to an outer env)
65
+ function envOf(ref,outer={}){
66
+ const t=T[ref.t]||{};const e={...(t.params||{}),...(t.variants?.[ref.args?.variant]||{}),...(ref.args||{})};
67
+ for(const k in e){const v=e[k];if(v&&typeof v==='object'&&typeof v.$param==='string'&&v.$param in outer)e[k]=outer[v.$param];}
68
+ return e;
69
+ }
70
+ const bind=(v,env)=>v&&typeof v==='object'&&typeof v.$param==='string'&&env&&v.$param in env?env[v.$param]:v;
71
+ const imgName=s=>{const m=String(s).match(/url\(([^)]+)\)/);return basename((m?m[1]:String(s)).replace(/["']/g,''));};
72
+
73
+ // walk every concrete node; refs are visited as refs, template bodies are walked separately
74
+ function walk(list,fn,depth=0,parent=null){for(const n of list){if(fn(n,depth,parent)===false)continue;walk(kids(n),fn,depth+1,n);}}
75
+ const bodies=()=>Object.entries(T).map(([name,t])=>[name,t.body]);
76
+ function count(n){if(!n)return 0;if(isRef(n))return expandedSize(n.t)+kids(n).reduce((s,c)=>s+count(c),0);return 1+kids(n).reduce((s,c)=>s+count(c),0);}
77
+ const sizeMemo=new Map();
78
+ function expandedSize(name){if(sizeMemo.has(name))return sizeMemo.get(name);sizeMemo.set(name,0);const s=count(T[name]?.body);sizeMemo.set(name,s);return s;}
79
+
80
+ // index page-tree ids
81
+ const byId=new Map();
82
+ walk(ast.nodes,n=>{if(n.id!==undefined&&!byId.has(String(n.id)))byId.set(String(n.id),n);});
83
+ for(const [,b] of bodies())walk([b],n=>{if(n.id!==undefined&&!byId.has(String(n.id)))byId.set(String(n.id),n);});
84
+ function locate(spec){
85
+ const [head,...steps]=spec.split('/');
86
+ let n=byId.get(head)??byId.get(head.replace('-',':'))??(T[head]?{...T[head].body,__template:head}:null);
87
+ if(!n)throw new Error('not found: '+head);
88
+ for(const s of steps){
89
+ const list=isRef(n)&&!kids(n).length?[T[n.t]?.body]:kids(n);
90
+ n=list[Number(s)];if(!n)throw new Error('bad path step '+s+' in '+spec);
91
+ }
92
+ return n;
93
+ }
94
+
95
+ // ---------- show ----------
96
+ function attrLine(n,env){
97
+ const parts=[];const v=k=>bind(n[k],env);
98
+ for(const k of Object.keys(n)){
99
+ if(['tag','t','id','name','children','text','args','__template','__path'].includes(k))continue;
100
+ if(k==='width'&&'height' in n){parts.push(val(v('width'))+'x'+val(v('height')));continue;}
101
+ if(k==='height'&&'width' in n)continue;
102
+ const x=v(k);if(x===null||x===undefined)continue; // param resolved to "absent"
103
+ parts.push(k+'='+val(x));
104
+ }
105
+ return parts.join(' ');
106
+ }
107
+ function show(targets,maxDepth,expand){
108
+ const usedStyles=new Set(),usedTemplates=new Set(),shown=new Set(targets.filter(t=>t.root.__template).map(t=>t.root.__template));
109
+ const note=v=>{if(typeof v==='string'&&v in G)usedStyles.add(v);};
110
+ for(const {spec,root} of targets){
111
+ const lines=[];
112
+ // extra:展开模板多出来的缩进层数,不占 --depth 的预算
113
+ (function rec(n,d,path,env,extra=0){
114
+ const pad=' '.repeat(d);
115
+ if(isRef(n)&&/^T\d/.test(n.t)&&!kids(n).length&&T[n.t]?.body&&!T[n.t].params){
116
+ // tiny compression templates: inline them instead of making the reader look them up
117
+ return rec({...T[n.t].body,...(n.id!==undefined?{id:n.id}:{})},d,path,env,extra);
118
+ }
119
+ if(isRef(n)){
120
+ const args=Object.entries(n.args||{}).map(([k,v])=>{v=bind(v,env);note(v);return k+'='+(v===null||v===undefined?'∅':val(v));}).join(' ');
121
+ if(expand&&T[n.t]?.body&&!/^S/.test(n.t)&&d-extra<maxDepth){
122
+ lines.push(pad+'<'+n.t+(n.id!==undefined?' #'+n.id:'')+(args?' '+args:'')+'> expanded ['+path+']');
123
+ const inner=envOf(n,env);
124
+ for(const v of Object.values(inner))note(v);
125
+ // slot contents are placed where <slotN/> sits in the body
126
+ const slots=Object.fromEntries(kids(n).map(s=>[s.tag,kids(s)]));
127
+ return rec({...T[n.t].body,__slots:slots},d+1,path,inner,extra+1);
128
+ }
129
+ usedTemplates.add(n.t);
130
+ lines.push(pad+'<'+n.t+(n.id!==undefined?' #'+n.id:'')+(args?' '+args:'')+(kids(n).length?'>':' />')+' ['+path+']');
131
+ if(kids(n).length&&d-extra<maxDepth)kids(n).forEach((c,i)=>rec(c,d+1,path+'/'+i,env,extra));
132
+ return;
133
+ }
134
+ if(/^slot\d+$/.test(n.tag||'')&&!kids(n).length&&env&&env.__slots?.[n.tag]){
135
+ lines.push(pad+'<'+n.tag+'> (filled)');env.__slots[n.tag].forEach((c,i)=>rec(c,d+1,path+'/'+i,env,extra));return;
136
+ }
137
+ if(n.__slots)env={...env,__slots:n.__slots};
138
+ for(const k of Object.keys(n))note(bind(n[k],env));
139
+ // TEXT 的图层名多半是内容的旧副本(实例改过文字、图层名还是主组件里的),只会误导;有内容就只给内容
140
+ const named=n.name&&!AUTO.test(n.name)&&!(n.tag==='TEXT'&&n.text!==undefined);
141
+ const head=(n.tag||'?')+(n.id!==undefined?' #'+n.id:'')+(named?' "'+short(n.name,40)+'"':'');
142
+ const tv=bind(n.text,env);
143
+ // 文案原样完整给出(换行写成 \n):要逐字写进代码,截断只会写错或逼着再查一次
144
+ const fullText=t=>String(t).replace(/\r?\n|\u2028/g,'\\n');
145
+ const text=n.text!==undefined?' ⟨'+(tv&&typeof tv==='object'?val(tv):fullText(tv??'∅'))+'⟩':'';
146
+ const a=attrLine(Object.fromEntries(Object.entries(n).filter(([k])=>k!=='__slots')),env);
147
+ lines.push(pad+head+(a?' '+a:'')+text);
148
+ const c=kids(n);
149
+ if(!c.length)return;
150
+ if(d-extra>=maxDepth){lines.push(pad+' … '+c.length+' children / '+c.reduce((s,x)=>s+count(x),0)+' nodes → show '+path+' ');return;}
151
+ c.forEach((x,i)=>rec(x,d+1,path+'/'+i,env,extra));
152
+ })(root,0,spec,{});
153
+ // template header when showing a template
154
+ if(root.__template){
155
+ const t=T[root.__template];
156
+ const meta=['uses='+(t.uses??'?'),'nodes='+expandedSize(root.__template)];
157
+ if(t.params)meta.push('params '+shortJSON(t.params));
158
+ if(t.variants)meta.push('variants '+shortJSON(t.variants));
159
+ for(const v of [...Object.values(t.params||{}),...Object.values(t.variants||{}).flatMap(Object.values)])note(v);
160
+ lines.unshift('template '+root.__template+' '+meta.join(' '));
161
+ }
162
+ if(isRef(root))lines.push(' (instance of '+root.t+': show '+root.t+' for its body; only args/slots differ per instance)');
163
+ if(targets.length>1)console.log('=== '+spec);
164
+ console.log(lines.join('\n'));
165
+ }
166
+ const pending=[...usedTemplates].filter(t=>!shown.has(t));
167
+ if(pending.length){
168
+ console.log('\nrefs: '+pending.map(t=>t+'(uses='+(T[t]?.uses??'?')+',nodes='+expandedSize(t)+(T[t]?.params?',params='+Object.keys(T[t].params).join('|'):'')+(T[t]?.variants?',variants='+Object.keys(T[t].variants).join('|'):'')+')').join(' '));
169
+ console.log(' (read several at once: show <ast> '+pending.slice(0,6).join(' ')+' — or --expand to inline them here)');
170
+ }
171
+ if(usedStyles.size){
172
+ console.log('\nstyles:');
173
+ for(const k of [...usedStyles].sort())console.log(k+' '+shortJSON(style(k)));
174
+ }
175
+ }
176
+
177
+ // ---------- units & similarity ----------
178
+ // address of a node: its id when it has one, else nearest ancestor id + child indexes
179
+ const addr=new Map();
180
+ (function rec(list,base){list.forEach((n,i)=>{const a=n.id!==undefined?String(n.id):base+'/'+i;addr.set(n,a);if(!isRef(n))rec(kids(n),a);});})(ast.nodes,'');
181
+ const A=n=>addr.get(n)||String(n.id??'?');
182
+ function units(){
183
+ const out=[];
184
+ (function rec(list,group){
185
+ for(const n of list){
186
+ // a SECTION about the size of a screen is one screen made of parts, not a board of screens
187
+ if(!isRef(n)&&n.tag==='SECTION'&&group&&dim(n).width&&dim(n).width<=2000&&dim(n).height<=6000){out.push({unit:n,group});continue;}
188
+ if(!isRef(n)&&(n.tag==='SECTION'||n.tag==='CANVAS')){out.push({section:n,group});rec(kids(n),n);continue;}
189
+ out.push({unit:n,group});
190
+ }
191
+ })(ast.nodes,null);
192
+ return out;
193
+ }
194
+ const normName=s=>String(s||'').replace(/[\d\s_\-]+/g,'').toLowerCase().slice(0,24);
195
+ function bag(n,depth=0,b=new Map()){
196
+ if(!n||depth>5)return b;
197
+ const key=depth+':'+(isRef(n)?n.t:n.tag+':'+normName(n.name));
198
+ b.set(key,(b.get(key)||0)+1);
199
+ const c=isRef(n)?kids(n):kids(n);
200
+ for(const x of c)bag(x,depth+1,b);
201
+ return b;
202
+ }
203
+ function jaccard(a,b){let i=0,u=0;const keys=new Set([...a.keys(),...b.keys()]);for(const k of keys){const x=a.get(k)||0,y=b.get(k)||0;i+=Math.min(x,y);u+=Math.max(x,y);}return u?i/u:0;}
204
+ // 自身没有宽高(内容撑开)的屏幕级节点,设计稿尺寸记在 canvasXY 里
205
+ const dim=n=>{
206
+ const c=n?.canvasXY||{};
207
+ if(!isRef(n))return {...n,width:n.width??c.width,height:n.height??c.height};
208
+ const b=T[n.t]?.body||{},e=envOf(n);return {...b,width:bind(b.width,e)??c.width,height:bind(b.height,e)??c.height};
209
+ };
210
+ const wh=d=>(typeof d.width==='number'?d.width:'?')+'x'+(typeof d.height==='number'?d.height:'?');
211
+ function texts(n,acc=[],env={}){
212
+ if(!n)return acc;
213
+ if(isRef(n)){
214
+ const t=T[n.t];const e={...(t?.params||{}),...(t?.variants?.[n.args?.variant]||{}),...(n.args||{})};
215
+ for(const k in e){const v=e[k];if(v&&typeof v==='object'&&v.$param)e[k]=env[v.$param];}
216
+ texts(t?.body,acc,e);for(const s of kids(n))kids(s).forEach(c=>texts(c,acc,env));return acc;
217
+ }
218
+ if(n.text!==undefined){const v=typeof n.text==='object'&&n.text?.$param?env[n.text.$param]:n.text;if(typeof v==='string'&&v.trim())acc.push(v.trim());}
219
+ for(const c of kids(n))texts(c,acc,env);
220
+ return acc;
221
+ }
222
+ // expand a ref one level for similarity purposes (shell template + slot contents)
223
+ const flatRef=n=>isRef(n)?{tag:'REF',name:n.t,children:[T[n.t]?.body,...kids(n).flatMap(kids)].filter(Boolean)}:n;
224
+ const statePrefix=n=>{const nm=String((isRef(n)?T[n.t]?.body?.name:n.name)||'');const m=nm.match(/^(.{2,20}?)\s*[-_—–·||/]\s*\S/);return m&&!AUTO.test(m[1])?m[1].replace(/页$/,'').trim():null;};
225
+ function clusters(list){
226
+ const bags=list.map(u=>bag(flatRef(u))),parent=list.map((_,i)=>i),near=list.map(()=>null);
227
+ const find=i=>parent[i]===i?i:(parent[i]=find(parent[i]));
228
+ for(let i=0;i<list.length;i++)for(let j=i+1;j<list.length;j++){
229
+ if(isRef(list[i])&&isRef(list[j])&&list[i].t===list[j].t&&/^S/.test(list[i].t)){parent[find(j)]=find(i);continue;}
230
+ // designers name state frames "<screen>-<state>": same prefix + same width = same screen
231
+ const pi=statePrefix(list[i]),pj=statePrefix(list[j]);
232
+ if(pi&&pi===pj&&dim(list[i]).width===dim(list[j]).width){parent[find(j)]=find(i);continue;}
233
+ const a=dim(list[i]),b=dim(list[j]);
234
+ if(!a.width||!b.width||Math.abs(a.width-b.width)/Math.max(a.width,b.width)>0.08)continue;
235
+ const s=jaccard(bags[i],bags[j]);
236
+ if(s>=0.5)parent[find(j)]=find(i);
237
+ else if(s>=0.25){if(!near[i]||near[i][1]<s)near[i]=[j,s];if(!near[j]||near[j][1]<s)near[j]=[i,s];}
238
+ }
239
+ const groups=new Map();list.forEach((_,i)=>{const r=find(i);if(!groups.has(r))groups.set(r,[]);groups.get(r).push(i);});
240
+ return {groups:[...groups.values()],near};
241
+ }
242
+ const AUTO=/^(Frame|Group|Rectangle|Vector|Ellipse|Line|Union|Subtract|image|Mask group)\b[\s\d]*$/i;
243
+ function label(n){
244
+ const nm=isRef(n)?T[n.t]?.body?.name:n.name;
245
+ if(nm&&!AUTO.test(nm))return nm;
246
+ const tx=texts(n)[0];if(tx)return '⟨'+tx+'⟩';
247
+ const src=JSON.stringify(isRef(n)?T[n.t]?.body:n).match(/([^"/\\]+)\.svg/);return src?src[1]+'.svg':nm||'';
248
+ }
249
+ function skeleton(n){if(!n)return '';if(isRef(n))return n.t;return (n.tag||'')+'('+kids(n).map(skeleton).join(',')+')';}
250
+
251
+
252
+ // ---------- canvas regions ----------
253
+ // 画板上常见的组织方式:大块背景圈出一个分区,分区里的大标题是分区名,小标题领着一排屏幕。
254
+ // 背景外面的屏幕通常是旧稿、备选方案或附件。
255
+ const xy=n=>{const p=n?.canvasXY;return p&&typeof p.x==='number'?p:null;};
256
+ function canvasRegions(board,screens){
257
+ const kids=kids0(board);
258
+ const area=n=>{const d=dim(n);return (d.width||0)*(d.height||0);};
259
+ const screenArea=Math.max(...screens.map(area).filter(Boolean),1);
260
+ const box=n=>{const p=xy(n),d=dim(n);return p&&d.width&&d.height?{x:p.x,y:p.y,w:d.width,h:d.height}:null;};
261
+ const inside=(p,b)=>p&&p.x>=b.x&&p.x<b.x+b.w&&p.y>=b.y&&p.y<b.y+b.h;
262
+ const backs=kids.filter(n=>!isRef(n)&&!kids0(n).length&&n.tag!=='TEXT'&&area(n)>=screenArea*4).map(box).filter(Boolean)
263
+ .filter(b=>screens.filter(u=>inside(xy(u),b)).length>=2);
264
+ const titles=kids.filter(n=>!isRef(n)&&n.tag==='TEXT'&&xy(n)).map(n=>({text:String(n.text??n.name??''),...xy(n),size:dim(n).height||0}));
265
+ if(!backs.length&&!titles.length)return null;
266
+ return u=>{
267
+ const p=xy(u);if(!p)return {region:null,row:null};
268
+ const back=backs.filter(b=>inside(p,b)).sort((a,b)=>a.w*a.h-b.w*b.h)[0];
269
+ if(backs.length&&!back)return {region:'⚠ 不在任何分区里(可能是旧稿、备选方案或附件,列给用户确认是否需要)',row:null};
270
+ const own=titles.filter(t=>!back||inside(t,back));
271
+ const head=[...own].sort((a,b)=>b.size-a.size||a.y-b.y)[0];
272
+ const above=own.filter(t=>t!==head&&t.y<=p.y).sort((a,b)=>b.y-a.y||Math.abs(a.x-p.x)-Math.abs(b.x-p.x))[0];
273
+ return {region:head?.text??(back?'(未命名分区)':null),row:above?.text??null};
274
+ };
275
+ }
276
+ const kids0=n=>Array.isArray(n?.children)?n.children:[];
277
+
278
+ // 宿主外观:手机状态栏、小程序胶囊、浏览器栏、Home Indicator……属于运行环境,不属于页面
279
+ const HOST=/状态栏|status ?bar|home ?indicator|胶囊|小程序|capsule|safari|toolbar|刘海|notch|navigation bar\/system|system\/|^9:41/i;
280
+ function hostChrome(){
281
+ const out=new Map();
282
+ for(const [k,t] of Object.entries(T)){
283
+ const nm=String(t.body?.name??''),tx=texts(t.body);
284
+ // 名字点明是系统外观,或者全部文案都是时间、电量、运营商这类状态栏内容(含页面标题的导航栏不算)
285
+ const statusOnly=tx.length>0&&tx.every(x=>/^\d{1,2}:\d{2}( ?[AP]M)?$|^\d{1,3}%$|^(sketch|carrier|中国移动|中国联通|中国电信|5G|4G|LTE|wi-?fi)$/i.test(x.trim()));
286
+ if(HOST.test(nm)||statusOnly)out.set(k,nm||label(t.body));
287
+ }
288
+ return out;
289
+ }
290
+
291
+ // 同一状态组里选基准帧:与组内其它帧平均最相似的那个;结构差太多的单独看
292
+ function baseOf(members){
293
+ const bags=members.map(u=>bag(flatRef(u)));
294
+ const sim=(i,j)=>jaccard(bags[i],bags[j]);
295
+ let best=0,bestScore=-1;
296
+ members.forEach((_,i)=>{const sc=members.reduce((t,_,j)=>t+(i===j?0:sim(i,j)),0)/Math.max(1,members.length-1);if(sc>bestScore){best=i;bestScore=sc;}});
297
+ return {base:members[best],scores:members.map((_,i)=>i===best?1:sim(best,i))};
298
+ }
299
+
300
+ function outline(){
301
+ const section=opt('--section');
302
+ const bytes=statSync(file).size;
303
+ console.log(`${ast.name||''} fileKey=${ast.fileKey||''} ast=${(bytes/1024).toFixed(0)}KB templates=${Object.keys(T).length} styles=${Object.keys(G).length}`);
304
+ if(ast.connectors?.length){
305
+ console.log('\nconnectors (from --label--> to):');
306
+ for(const c of ast.connectors){
307
+ const nm=(id,alt)=>alt||byId.get(String(id).split('/')[0])?.name||'';
308
+ console.log(` ${c.from}${c.fromName||nm(c.from)?' "'+short(c.fromName||nm(c.from),30)+'"':''} --${c.label||''}--> ${c.to}${c.toName||nm(c.to)?' "'+short(c.toName||nm(c.to),30)+'"':''}`);
309
+ }
310
+ }
311
+ let entries=units();
312
+ if(section)entries=entries.filter(e=>e.group&&(A(e.group)===section||A(e.group).startsWith(section+'/')));
313
+ const byGroup=new Map();
314
+ for(const e of entries){if(e.unit){const g=e.group?A(e.group):'(root)';if(!byGroup.has(g))byGroup.set(g,{group:e.group,list:[]});byGroup.get(g).list.push(e.unit);}}
315
+ const all=rest.includes('--all');
316
+ const isNote=u=>!isRef(u)&&u.tag==='TEXT';
317
+ const allScreens=[...byGroup.values()].flatMap(g=>g.list).filter(u=>!isNote(u)&&count(u)>12);
318
+ // global clustering so states split across sections still group together
319
+ const {groups,near}=clusters(allScreens);
320
+ const gOf=new Map();let gi=0;const summary=[];
321
+ for(const idxs of groups)if(idxs.length>1){gi++;for(const i of idxs)gOf.set(allScreens[i],gi);summary.push('g'+gi+': '+idxs.map(i=>A(allScreens[i])).join(' '));}
322
+ const nearOf=new Map(allScreens.map((u,i)=>[u,near[i]&&!gOf.has(u)?allScreens[near[i][0]]:null]));
323
+ // distinctive texts: drop those present in many screens (nav, headers)
324
+ const big=allScreens.filter(u=>count(u)>100);
325
+ const df=new Map();for(const u of big)for(const t of new Set(texts(u)))df.set(t,(df.get(t)||0)+1);
326
+ const common=big.length<4?Infinity:Math.max(3,big.length*0.25);
327
+ const line=u=>{const d=dim(u);
328
+ const tx=[...new Set(texts(u))].filter(t=>(df.get(t)||0)<common).slice(0,5).map(s=>short(s,20)).join(' | ');
329
+ return `${gOf.has(u)?'≈g'+gOf.get(u)+' ':''}${A(u)} ${isRef(u)?'<'+u.t+'> ':''}"${short(label(u),30)}" ${wh(d)} n=${count(u)}${tx?' '+tx:''}${nearOf.get(u)?' ~'+A(nearOf.get(u)):''}`;};
330
+ const board=ast.nodes.length===1&&!isRef(ast.nodes[0])&&['SECTION','CANVAS'].includes(ast.nodes[0].tag)?ast.nodes[0]:null;
331
+ const where=board?canvasRegions(board,allScreens):null;
332
+ const host=hostChrome();
333
+ console.log('\nunits (n=nodes; ≈gN = same screen in different states, build once; ~id = partly similar):');
334
+ const printList=(list,pad)=>{
335
+ const notes=list.filter(isNote);
336
+ const screens=list.filter(u=>allScreens.includes(u)),small=list.filter(u=>!isNote(u)&&!allScreens.includes(u));
337
+ for(const u of screens)console.log(pad+line(u));
338
+ if(all)for(const u of small)console.log(pad+'· '+line(u));
339
+ if(small.length&&!all){const by=new Map();for(const u of small){const k=short(label(u),24);by.set(k,(by.get(k)||0)+1);}
340
+ console.log(pad+'small parts ('+small.length+'): '+[...by].map(([k,c])=>k+(c>1?'×'+c:'')).join(', ')+' (--all to list)');}
341
+ const txt=n=>String(n.text??n.name??'');
342
+ const ann=notes.filter(n=>!(txt(n).length<=10&&!/[,。,.::;;!?!?]/.test(txt(n))));
343
+ if(ann.length)console.log(pad+'notes (requirements): '+ann.map(n=>'"'+short(txt(n),all?400:90)+'"').join(' ; '));
344
+ };
345
+ if(where){
346
+ // 按画布分区与行标题组织:设计师就是这样告诉你「哪些是同一页、哪套是正式稿」的
347
+ const groups=new Map();
348
+ for(const u of kids0(board)){const {region,row}=where(u);const k=region??'(未归入分区)';if(!groups.has(k))groups.set(k,new Map());
349
+ const rows=groups.get(k);const r=row??'';if(!rows.has(r))rows.set(r,[]);rows.get(r).push(u);}
350
+ const order=[...groups.keys()].sort((a,b)=>(a.startsWith('⚠')?1:0)-(b.startsWith('⚠')?1:0));
351
+ for(const k of order){console.log('REGION '+k);for(const [row,list] of groups.get(k)){if(row)console.log(' ['+row+']');printList(list.filter(u=>!(isNote(u)&&String(u.text??'').length<=10)),row?' ':' ');}}
352
+ for(const [gid,{group,list}] of byGroup)if(group&&group!==board){console.log(`SECTION ${A(group)} "${short(group.name||'',50)}" ${list.length} units`);printList(list,' ');}
353
+ }else for(const [gid,{group,list}] of byGroup){
354
+ console.log(group?`SECTION ${A(group)} "${short(group.name||'',50)}" ${list.length} units`:'(root)');
355
+ printList(list,' ');
356
+ const txt=n=>String(n.text??n.name??'');
357
+ const titles=list.filter(isNote).filter(n=>txt(n).length<=10&&!/[,。,.::;;!?!?]/.test(txt(n)));
358
+ if(titles.length)console.log(' titles: '+titles.map(n=>'"'+txt(n)+'"').join(' ; '));
359
+ }
360
+ if(gi){
361
+ console.log('\nstate groups (base = 写组件时作为基准的帧;其它帧用 diff 对比基准,similarity<0.3 的结构差异大,单独 show):');
362
+ let g=0;
363
+ for(const idxs of groups)if(idxs.length>1){g++;
364
+ const members=idxs.map(i=>allScreens[i]);const {base,scores}=baseOf(members);
365
+ const stray=u=>where&&where(u).region?.startsWith('⚠')?' ⚠分区外':'';
366
+ console.log(` g${g} base=${A(base)} "${short(label(base),24)}"${stray(base)}`);
367
+ const others=members.filter(u=>u!==base).sort((a,b)=>scores[members.indexOf(b)]-scores[members.indexOf(a)]);
368
+ const fmt=u=>`${A(u)} "${short(label(u),16)}" ${scores[members.indexOf(u)].toFixed(2)}${stray(u)}`;
369
+ const near=others.filter(u=>scores[members.indexOf(u)]>=0.3),far=others.filter(u=>scores[members.indexOf(u)]<0.3);
370
+ if(near.length)console.log(' diff 对比: '+near.map(fmt).join(' ; '));
371
+ if(far.length)console.log(' 单独 show: '+far.map(fmt).join(' ; '));
372
+ }
373
+ }
374
+ // 不是模板的宿主外观图层(小程序胶囊、Home Indicator……),按名字列出
375
+ const hostNodes=new Map();
376
+ const scan=n=>{if(!n||typeof n!=='object')return;if(isRef(n)){kids0(n).forEach(scan);return;}
377
+ if(n.name&&HOST.test(n.name))hostNodes.set(n.name,(hostNodes.get(n.name)||0)+1);else kids0(n).forEach(scan);};
378
+ ast.nodes.forEach(scan);for(const [k,t] of Object.entries(T))if(!host.has(k))scan(t.body);
379
+ if(host.size||hostNodes.size)console.log('\nhost chrome (运行环境的外观:照设计稿实现,单独封装成宿主外观组件、和页面内容分开;check 会忽略模板里的文案): '+
380
+ [...[...host].map(([k,n])=>`${k} "${short(n,24)}"`),...[...hostNodes].map(([n,c])=>`"${short(n,24)}"${c>1?'×'+c:''}`)].join(', '));
381
+
382
+ // components: rank by uses × size, the reuse value
383
+ const comps=Object.entries(T).filter(([k])=>!/^T\d/.test(k)).map(([k,t])=>({k,t,n:expandedSize(k)}));
384
+ comps.sort((a,b)=>(b.t.uses||1)*b.n-(a.t.uses||1)*a.n);
385
+ if(comps.length){
386
+ const shown=all?comps:comps.slice(0,40);
387
+ console.log('\ncomponents by reuse value (C=component, S=screen shell; ×uses n=nodes):');
388
+ for(const {k,t,n} of shown){
389
+ const api=[t.params&&'props:'+Object.keys(t.params).join(','),t.variants&&'variants:'+Object.keys(t.variants).join(','),
390
+ [...new Set(JSON.stringify(t.body).match(/"tag":"slot\d+"/g)?.map(s=>s.match(/slot\d+/)[0]))].join(',')].filter(Boolean).join(' ');
391
+ console.log(` ${k} ×${t.uses??'?'} n=${n} "${short(label(t.body),28)}"${api?' '+api:''}`);
392
+ }
393
+ if(comps.length>shown.length)console.log(` … +${comps.length-shown.length} smaller (--all)`);
394
+ const sk=new Map();
395
+ for(const {k,t} of comps){const s=skeleton(t.body);if(s.length<12)continue;if(!sk.has(s))sk.set(s,[]);sk.get(s).push(k);}
396
+ const merges=[...sk.values()].filter(v=>v.length>1);
397
+ if(merges.length)console.log('\nsame skeleton, different values (likely one component with props/variants):\n '+merges.map(v=>v.join('≈')).join(' '));
398
+ // 同名但结构不同的模板:同一个组件被画了好几版。以使用最多的为准,其余用 diff 看差异再决定做成变体还是忽略
399
+ const byName=new Map();
400
+ for(const {k,t,n} of comps){const nm=String(t.body?.name??'');if(!nm||AUTO.test(nm)||n<8||host.has(k))continue;if(!byName.has(nm))byName.set(nm,[]);byName.get(nm).push({k,uses:t.uses??1});}
401
+ const variants=[...byName].filter(([,v])=>v.length>1);
402
+ if(variants.length){
403
+ console.log('\nsame name, drawn differently (one component drawn several ways; implement every version as a variant; diff <base> <other> to see what differs):');
404
+ for(const [nm,v] of variants){v.sort((a,b)=>b.uses-a.uses);console.log(` "${short(nm,20)}": base=${v[0].k}×${v[0].uses} others: ${v.slice(1).map(x=>x.k+'×'+x.uses).join(' ')}`);}
405
+ }
406
+ }
407
+ }
408
+
409
+ // ---------- tokens ----------
410
+ function tokens(){
411
+ // 数值都是设计稿像素:按屏宽提示倍率,免得把 2x 的值直接写进 CSS
412
+ const SCREEN_TAGS=new Set(['FRAME','GROUP','SECTION','COMPONENT','INSTANCE','COMPONENT_SET']);
413
+ const widths=units().filter(e=>e.unit&&(isRef(e.unit)?SCREEN_TAGS.has(T[e.unit.t]?.body?.tag):SCREEN_TAGS.has(e.unit.tag))).map(e=>dim(e.unit).width).filter(w=>typeof w==='number'&&w>=320&&w<=1300);
414
+ const mode=[...widths.reduce((m,w)=>m.set(w,(m.get(w)||0)+1),new Map())].sort((a,b)=>b[1]-a[1])[0]?.[0];
415
+ if(mode){const scale=mode>=1100?3:mode>=700?2:1;
416
+ console.log(scale>1?`note: 屏宽多为 ${mode},是 ${scale}x 稿:下面的数值都要 ÷${scale} 再写成 CSS(同一文件里 375/390/414 宽的帧是 1x,单独判断)`:`note: 屏宽多为 ${mode},1x 稿,数值直接用`);}
417
+ const refs=new Map();
418
+ const src=JSON.stringify({n:ast.nodes,t:T});
419
+ for(const m of src.matchAll(/"([A-Za-z]+_?[A-Za-z0-9]+)"/g))if(m[1] in G)refs.set(m[1],(refs.get(m[1])||0)+1);
420
+ const tally=new Map();const add=(cat,k,w)=>{if(!tally.has(cat))tally.set(cat,new Map());const t=tally.get(cat);t.set(k,(t.get(k)||0)+w);};
421
+ const colorsIn=v=>JSON.stringify(v).match(/#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)/g)||[];
422
+ for(const [k,w] of refs){
423
+ const v=style(k);if(!v)continue;
424
+ const s=JSON.stringify(v);
425
+ if(Array.isArray(v)||v.backgroundImage||v.gradient||v.fontColor){for(const c of colorsIn(v))add('fill',c.replace(/\s+/g,''),w);if(s.includes('gradient'))add('gradient',s.match(/(linear|radial|conic)-gradient\([^"]*\)/)?.[0]||k,w);continue;}
426
+ if(v.family||v.size){add('type',`${v.family||''} ${v.size||''}${v.lineHeight?'/'+v.lineHeight:''} w${v.weight||''}`,w);if(v.color)add('text-color',String(v.color).replace(/\s+/g,''),w);continue;}
427
+ if(v.colors||v.strokeWeight){for(const c of colorsIn(v.colors))add('stroke',c.replace(/\s+/g,'')+' '+(v.strokeWeight||''),w);continue;}
428
+ if(v.boxShadow||v.backdropFilter||v.filter||v.textShadow){add('effect',v.boxShadow||v.textShadow||v.backdropFilter||v.filter,w);continue;}
429
+ if(v.gap)add('gap',v.gap,w);if(v.padding)add('padding',v.padding,w);
430
+ }
431
+ const zero=r=>/^(0(px)?\s*)+$/.test(String(r).trim());
432
+ walk(ast.nodes,n=>{if(n.borderRadius&&typeof n.borderRadius==='string'&&!zero(n.borderRadius))add('radius',n.borderRadius,1);});
433
+ for(const [,b] of bodies())walk([b],n=>{if(n.borderRadius&&typeof n.borderRadius==='string'&&!zero(n.borderRadius))add('radius',n.borderRadius,1);});
434
+ for(const [cat,t] of tally){
435
+ const top=[...t].sort((a,b)=>b[1]-a[1]).slice(0,cat==='effect'||cat==='gradient'?8:20);
436
+ console.log(cat+': '+top.map(([k,c])=>short(k,cat==='effect'||cat==='gradient'?90:48)+' ×'+c).join(' ; '));
437
+ }
438
+ }
439
+
440
+ // ---------- diff ----------
441
+ // 模板参数作用在哪个图层上:参数名 → 「图层名 字段」,diff 里标出来,下游不用再去翻模板
442
+ const whereMemo=new Map();
443
+ function paramWhere(name){
444
+ if(whereMemo.has(name))return whereMemo.get(name);
445
+ const out={};
446
+ whereMemo.set(name,out); // 先占位,防止模板互相引用时死循环
447
+ walk([T[name]?.body].filter(Boolean),n=>{
448
+ for(const [k,v] of Object.entries(n))if(v&&typeof v==='object'&&typeof v.$param==='string'&&!out[v.$param])
449
+ out[v.$param]=(n.name&&!AUTO.test(n.name)?n.name:n.tag)+' '+(k==='text'?'文字':k);
450
+ // 参数继续传给内层模板:跟到内层,标出最终作用的图层
451
+ if(isRef(n))for(const [ak,av] of Object.entries(n.args||{}))if(av&&typeof av==='object'&&typeof av.$param==='string'&&!out[av.$param]){
452
+ const inner=paramWhere(n.t)[ak];out[av.$param]=inner||(T[n.t]?.body?.name||n.t)+' '+ak;
453
+ }
454
+ });
455
+ whereMemo.set(name,out);return out;
456
+ }
457
+ function diff(aSpec,bSpec){
458
+ const A=locate(aSpec),B=locate(bSpec);let out=[],limit=250;
459
+ const key=n=>isRef(n)?(/^T/.test(n.t)&&!kids(n).length?T[n.t]?.body?.tag??'@'+n.t:'@'+n.t):n.tag;
460
+ const emit=s=>{if(out.length<limit)out.push(s);else if(out.length===limit)out.push('… truncated; diff a deeper path');};
461
+ const same=(x,y)=>JSON.stringify(x)===JSON.stringify(y);
462
+ (function rec(a,b,path,root){
463
+ if(isRef(a)!==isRef(b)||(isRef(a)&&a.t!==b.t)){ // compare a template instance with inline content via its body
464
+ if(isRef(a)&&!kids(a).length)a=T[a.t]?.body||a;
465
+ if(isRef(b)&&!kids(b).length)b=T[b.t]?.body||b;
466
+ }
467
+ if(!root&&key(a)!==key(b)){emit(`± ${path} ${key(a)} → ${key(b)} n=${count(b)}${texts(b).length?' ⟨'+short(texts(b).slice(0,4).join(' | '),80)+'⟩':''}`);return;}
468
+ const ka=new Set(Object.keys(a)),kb=new Set(Object.keys(b));
469
+ for(const k of new Set([...ka,...kb])){
470
+ if(['children','id','canvasXY'].includes(k))continue;
471
+ if(k==='args'&&isRef(a)&&isRef(b)&&a.t===b.t){
472
+ // 同一模板的两个实例:比最终生效的值(参数默认值 → 变体 → 实例参数),不比实例上写了什么,
473
+ // 否则「→ ∅」(回到默认值)、「variant → v2」都看不出实际变成了什么
474
+ const ea=envOf(a),eb=envOf(b),where=paramWhere(a.t);
475
+ if((a.args?.variant)!==(b.args?.variant))emit(`~ ${path} variant: ${a.args?.variant??'默认'} → ${b.args?.variant??'默认'}`);
476
+ for(const q of new Set([...Object.keys(ea),...Object.keys(eb)])){
477
+ if(q==='variant'||same(ea[q],eb[q]))continue;
478
+ const v=x=>x===undefined||x===null?'∅':short(val(x),60);
479
+ emit(`~ ${path} ${q}${where[q]?' ('+where[q]+')':''}: ${v(ea[q])} → ${v(eb[q])}`);
480
+ }
481
+ continue;
482
+ }
483
+ if(k==='args'||k==='params'){const x=a[k]||{},y=b[k]||{};for(const q of new Set([...Object.keys(x),...Object.keys(y)]))if(!same(x[q],y[q]))emit(`~ ${path} ${k}.${q}: ${x[q]===undefined?'∅':short(val(x[q]),60)} → ${y[q]===undefined?'∅':short(val(y[q]),60)}`);continue;}
484
+ if(!same(a[k],b[k]))emit(`~ ${path} ${k}: ${a[k]===undefined?'∅':short(val(a[k]),70)} → ${b[k]===undefined?'∅':short(val(b[k]),70)}`);
485
+ }
486
+ const ca=kids(a),cb=kids(b);
487
+ // LCS alignment on keys
488
+ const m=ca.length,n=cb.length,L=Array.from({length:m+1},()=>new Array(n+1).fill(0));
489
+ for(let i=m-1;i>=0;i--)for(let j=n-1;j>=0;j--)L[i][j]=key(ca[i])===key(cb[j])?L[i+1][j+1]+1:Math.max(L[i+1][j],L[i][j+1]);
490
+ let i=0,j=0;
491
+ while(i<m||j<n){
492
+ if(i<m&&j<n&&key(ca[i])===key(cb[j])){rec(ca[i],cb[j],path+'/'+j,false);i++;j++;}
493
+ else if(j<n&&(i>=m||L[i][j+1]>=L[i+1][j])){emit(`+ ${path}/${j} ${key(cb[j])}${cb[j].id!==undefined?' #'+cb[j].id:''} n=${count(cb[j])}${texts(cb[j]).length?' ⟨'+short(texts(cb[j]).slice(0,4).join(' | '),80)+'⟩':''}`);j++;}
494
+ else {emit(`- ${path}/${i}(A) ${key(ca[i])} n=${count(ca[i])}${texts(ca[i]).length?' ⟨'+short(texts(ca[i]).slice(0,4).join(' | '),80)+'⟩':''}`);i++;}
495
+ }
496
+ })(A,B,bSpec,true);
497
+ const total=count(B);
498
+ console.log(`diff ${aSpec} → ${bSpec}: ${out.length} changes (B has ${total} nodes; paths are B-side)`);
499
+ console.log(out.join('\n'));
500
+ const st=new Set();for(const l of out)for(const m of l.matchAll(/(?:→|:)\s*([A-Za-z]+_?[A-Za-z0-9]+)\b/g))if(m[1] in G)st.add(m[1]);
501
+ if(st.size){console.log('\nstyles:');for(const k of [...st].sort())console.log(k+' '+shortJSON(style(k)));}
502
+ }
503
+
504
+ // ---------- check ----------
505
+ function check(dirs){
506
+ const units=[];let i;while((i=dirs.indexOf('--unit'))>=0){units.push(dirs[i+1]);dirs.splice(i,2);}
507
+ const roots=units.length?units.map(locate):ast.nodes;
508
+ // templates reachable from the chosen roots
509
+ const used=new Set();const visit=n=>{if(!n)return;if(isRef(n)&&!used.has(n.t)){used.add(n.t);visit(T[n.t]?.body);}kids(n).forEach(visit);};roots.forEach(visit);
510
+ const host=hostChrome();
511
+ const hostTexts=new Set([...host.keys()].flatMap(k=>texts(T[k].body)));
512
+ const allTexts=new Set(texts({children:roots,tag:'ROOT'}).filter(t=>!hostTexts.has(t)));
513
+ const images=new Set();
514
+ const keys=new Set();const src0=JSON.stringify({n:roots,t:[...used].map(k=>T[k])});
515
+ for(const m of src0.matchAll(/"([A-Za-z]+_?[A-Za-z0-9]+)"/g))if(m[1] in G)keys.add(m[1]);
516
+ const src=src0+JSON.stringify([...keys].map(k=>G[k]));
517
+ for(const m of src.matchAll(/[^"(/\\]+\.(?:svg|png|jpe?g|webp|gif)\b/gi))images.add(m[0]);
518
+ let code='';const exts=new Set(['.js','.jsx','.ts','.tsx','.vue','.svelte','.html','.css','.scss','.less','.json','.md','.mjs']);
519
+ const rd=p=>{let s;try{s=statSync(p);}catch{return;}
520
+ if(s.isDirectory()){if(/^(node_modules|\.git|dist|build|\.next|\.melonbuild)$/.test(basename(p)))return;for(const f of readdirSync(p))rd(join(p,f));}
521
+ else if(exts.has(extname(p))&&s.size<2e6)code+=readFileSync(p,'utf8')+'\n';};
522
+ for(const d of dirs.length?dirs:['.'])rd(d);
523
+ const flat=code.replace(/\s+/g,' ');
524
+ const missT=[...allTexts].filter(t=>t.length>1&&!flat.includes(t.replace(/\s+/g,' ')));
525
+ const missI=[...images].filter(i=>!code.includes(i)&&!code.includes(i.replace(/;/g,'_')));
526
+ console.log(`texts: ${allTexts.size-missT.length}/${allTexts.size} found in code; images: ${images.size-missI.length}/${images.size} referenced`);
527
+ if(missT.length)console.log('missing texts:\n '+missT.slice(0,60).map(t=>short(t,80)).join('\n ')+(missT.length>60?'\n … +'+(missT.length-60):''));
528
+ if(missI.length)console.log('unreferenced images:\n '+missI.slice(0,40).join('\n ')+(missI.length>40?'\n … +'+(missI.length-40):''));
529
+ }
530
+
531
+
532
+ // ---------- local image references ----------
533
+ const LOCAL_IMAGE=/(^|[\/("'])([^\/("'\s]+\.(?:svg|png|jpe?g|webp|gif))(?=$|["')])/i;
534
+ function localImageRefs(){
535
+ const out=[],seen=new Set();
536
+ const visit=v=>{
537
+ if(typeof v==='string'){if(/https?:\/\//.test(v))return;for(const m of v.matchAll(new RegExp(LOCAL_IMAGE.source,'gi'))){const full=v.slice(0,m.index+m[0].length).replace(/^.*url\(\s*["']?/,'').replace(/^["']/,'');const file=m[2];if(!seen.has(file)){seen.add(file);out.push({file,path:full});}}return;}
538
+ if(Array.isArray(v))return v.forEach(visit);if(v&&typeof v==='object')Object.values(v).forEach(visit);};
539
+ visit({n:ast.nodes,t:T,g:G});return out;
540
+ }
541
+ /** 图片目录:AST 里的本地路径相对 AST 文件 */
542
+ function imageDir(){
543
+ const ref=localImageRefs()[0];if(!ref)return null;
544
+ const rel=ref.path.slice(0,ref.path.length-ref.file.length);
545
+ return join(file,'..',rel);
546
+ }
547
+
548
+ // ---------- assets ----------
549
+ // CLI saves images as <sha256>.<ext>; give them names from their Figma layers so code stays readable.
550
+ function assets(apply){
551
+ const names=new Map(); // filename -> layer name
552
+ // 本地图片引用(CLI --image-dir 改写后的相对路径);远程链接不算
553
+ const fileOf=v=>{if(typeof v!=='string'||/https?:\/\//.test(v))return null;const m=v.match(LOCAL_IMAGE);return m?m[2]:null;};
554
+ const fillOwner=new Map();
555
+ const note=(v,name)=>{const f=fileOf(v);if(f&&name&&!names.has(f))names.set(f,name);};
556
+ const paramNames=new Map(); // template -> param -> layer name
557
+ const up=new Map();walk(ast.nodes,(n,d,p)=>{up.set(n,p);});for(const [,b] of bodies())walk([b],(n,d,p)=>{up.set(n,p);});
558
+ const GENERIC=/^(Frame|Group|Rectangle|Vector|Ellipse|Line|Union|Subtract|image|Mask group|形状|形状结合|蒙版|编组|路径|矩形|椭圆)[\s\d]*$/i;
559
+ const nm=(n,p)=>{for(let x=n,i=0;x&&i<6;x=i===0?p:up.get(x),i++)if(x.name&&!GENERIC.test(x.name))return x.name;return n.name;};
560
+ for(const [tn,t] of Object.entries(T))walk([t.body],(n,d,p)=>{
561
+ for(const [k,v] of Object.entries(n)){
562
+ if(v&&typeof v==='object'&&v.$param&&(k==='src'||k==='fills')){if(!paramNames.has(tn))paramNames.set(tn,{});paramNames.get(tn)[v.$param]=nm(n,p);}
563
+ }
564
+ });
565
+ const visit=(n,p)=>{
566
+ if(isRef(n)){const pn=paramNames.get(n.t)||{},t=T[n.t]||{};
567
+ for(const src of [n.args||{},t.params||{},...Object.values(t.variants||{})])for(const [k,v] of Object.entries(src)){if(pn[k])note(v,pn[k]);if(typeof v==='string'&&v in G)fillOwner.set(v,fillOwner.get(v)||pn[k]||t.body?.name);}
568
+ return;}
569
+ if(n.src)note(n.src,nm(n,p));
570
+ for(const k of ['fills','maskFills'])if(typeof n[k]==='string'&&!fillOwner.has(n[k]))fillOwner.set(n[k],nm(n,p)+(k==='maskFills'?' mask':''));
571
+ };
572
+ walk(ast.nodes,(n,d,p)=>{visit(n,p);});for(const [,b] of bodies())walk([b],(n,d,p)=>{visit(n,p);});
573
+ for(const [k,v] of Object.entries(G)){const s=JSON.stringify(v);const f=fileOf(s.replace(/\\"/g,'"'));if(f)note(f,fillOwner.get(k)||'image');}
574
+ // also any file referenced but unnamed
575
+ for(const ref of localImageRefs())if(!names.has(ref.file))names.set(ref.file,'image');
576
+ const slug=s=>{const seg=String(s).split('/').map(x=>x.trim()).filter(Boolean);
577
+ for(const part of [seg.at(-1),...seg.slice(0,-1).reverse()]){const clean=(part||'').toLowerCase().replace(/\b(frame|group|vector|rectangle|union|subtract|mask|layer)\b/g,' ').replace(/\b\d+\b/g,' ');
578
+ const ascii=clean.replace(/[^a-z0-9]+/g,'-').replace(/^[-\d]+|-+$/g,'');if(ascii.length>=2)return ascii.slice(0,40);
579
+ const cjk=clean.replace(/[^a-z0-9\u4e00-\u9fff]+/g,'-').replace(/^[-\d]+|-+$/g,'');if(/[\u4e00-\u9fff]/.test(cjk))return cjk.slice(0,24);}
580
+ return 'img';};
581
+ // locate the image directory from the first local reference
582
+ const dirOf=imageDir();
583
+ if(!dirOf){console.log('no local images (fetch with --image-dir first)');return;}
584
+ const read=f=>{try{return readFileSync(join(dirOf,f));}catch{return null;}};
585
+ // byte-identical downloads collapse into one file
586
+ const byHash=new Map(),dupOf=new Map();
587
+ for(const f of names.keys()){const b=read(f);if(!b)continue;const h=createHash('sha1').update(b).digest('hex');if(byHash.has(h))dupOf.set(f,byHash.get(h));else byHash.set(h,f);}
588
+ const info=f=>{
589
+ const b=read(f);if(!b||!f.endsWith('.svg'))return {};
590
+ const x=b.toString('utf8');
591
+ const photo=/<image\b/.test(x)||b.length>150000;
592
+ return {photo,...(photo?{}:plainShape(x)),broken:!balanced(x)};
593
+ };
594
+ const taken=new Map(),plan=[];
595
+ for(const [f,name] of names){
596
+ if(dupOf.has(f))continue;
597
+ const ext=f.split('.').pop(),meta=info(f),sl=slug(name);
598
+ // 旧版 CLI 用 URL 哈希命名;新版已按图层命名,保持原名
599
+ if(!/^[a-f0-9]{64}\./.test(f)){taken.set(f,f);plan.push([f,f,name,meta]);continue;}
600
+ let base=ext!=='svg'||meta.photo?(sl==='img'?'image':sl):(meta.shape?'shape-':/icon|logo/.test(sl)?'':'icon-')+sl;
601
+ let out=base+'.'+ext;if(taken.has(out))out=base+'-'+f.slice(0,4)+'.'+ext;taken.set(out,f);plan.push([f,out,name,meta]);
602
+ }
603
+ const target=new Map(plan.map(([f,o])=>[f,o]));for(const [d,k] of dupOf)target.set(d,target.get(k));
604
+ const shapes=plan.filter(p=>p[3].shape),broken=plan.filter(p=>p[3].broken);
605
+ const pending=plan.filter(([f,o,,m])=>f!==o||m.broken).length+dupOf.size;
606
+ if(!apply||!pending){
607
+ for(const [f,o,n,m] of plan){if(f===o&&!m.shape&&!m.broken)continue;
608
+ console.log((f===o?o:f.slice(0,10)+'… → '+o)+' ("'+short(n,32)+'")'+(m.shape?' [plain shape: '+m.shape+' → CSS]':'')+(m.broken?' [malformed SVG]':''));}
609
+ console.log(`${names.size} images, ${shapes.length} plain shapes (prefer CSS so states work)`+
610
+ (pending?`; ${pending} files need renaming / dedupe / repair (older CLI) — run with --apply`:''));
611
+ return;
612
+ }
613
+ let text=readFileSync(file,'utf8'),moved=0,fixed=0,removed=0;
614
+ for(const [f,o,,m] of plan){
615
+ const from=join(dirOf,f),to=join(dirOf,o);
616
+ if(existsSync(from)&&!existsSync(to)){renameSync(from,to);moved++;}
617
+ if(m.broken&&existsSync(to)){writeFileSync(to,repairSvg(readFileSync(to,'utf8')));fixed++;}
618
+ }
619
+ for(const d of dupOf.keys()){const p=join(dirOf,d);if(existsSync(p)){unlinkSync(p);removed++;}}
620
+ for(const [f,o] of target)text=text.split(f).join(o);
621
+ writeFileSync(file,text);
622
+ console.log(`renamed ${moved}, merged ${removed} duplicates, repaired ${fixed} malformed SVGs in ${dirOf}; AST rewritten`);
623
+ if(shapes.length)console.log(`plain shapes (likely button/card/tag backgrounds; prefer CSS so states work): ${shapes.map(p=>p[1]).join(', ')}`);
624
+ }
625
+
626
+ // 能直接用 CSS 画的图:只有一个图形、铺满整个画布(矩形 / 圆角矩形 / 椭圆),填充是纯色或渐变
627
+ function plainShape(svg){
628
+ if(/<(filter|pattern|mask|clipPath|text|use)\b/.test(svg))return {};
629
+ const size=svg.match(/<svg[^>]*?\bwidth="([\d.]+)"[^>]*?\bheight="([\d.]+)"/);if(!size)return {};
630
+ const [W,H]=[+size[1],+size[2]];
631
+ const shapes=[...svg.matchAll(/<(rect|path|circle|ellipse|polygon|line|polyline)\b([^>]*)>/g)];
632
+ if(shapes.length!==1)return {};
633
+ const [,tag,attrs]=shapes[0];const a=k=>attrs.match(new RegExp('\\s'+k+'="([^"]*)"'))?.[1];
634
+ let box;
635
+ if(tag==='rect')box=[+(a('x')||0),+(a('y')||0),+(a('width')||0),+(a('height')||0)];
636
+ else if(tag==='circle'||tag==='ellipse'){const rx=+(a('r')||a('rx')||0),ry=+(a('r')||a('ry')||0);box=[+(a('cx')||0)-rx,+(a('cy')||0)-ry,2*rx,2*ry];}
637
+ else if(tag==='path')box=pathBox(a('d')||'');
638
+ if(!box||Math.abs(box[0])>1||Math.abs(box[1])>1||Math.abs(box[2]-W)>1||Math.abs(box[3]-H)>1)return {};
639
+ const fill=a('fill')||'';const opacity=a('fill-opacity')||a('opacity');
640
+ let paint;
641
+ if(/^#[0-9a-f]{3,8}$/i.test(fill)||/^(white|black)$/i.test(fill))paint=fill.toUpperCase()+(opacity?' @'+opacity:'');
642
+ else if(/^url\(#/.test(fill)&&/<(linear|radial)Gradient\b/.test(svg))paint='gradient';
643
+ else return {};
644
+ const outline=tag==='rect'?(a('rx')?`rounded r=${a('rx')}`:'rect'):tag==='path'?(/[CcQqAa]/.test(a('d')||'')?'rounded':'rect'):'ellipse';
645
+ return {shape:`${outline} ${paint}`};
646
+ }
647
+ function pathBox(d){
648
+ const tokens=d.match(/[a-zA-Z]|-?\d*\.?\d+(?:e-?\d+)?/g)||[];let i=0,cmd='',x=0,y=0,sx=0,sy=0;
649
+ let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;const mark=()=>{minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y);};
650
+ const num=()=>+tokens[i++];
651
+ const arity={M:2,L:2,T:2,H:1,V:1,C:6,S:4,Q:4,A:7,Z:0};
652
+ while(i<tokens.length){
653
+ if(/[a-zA-Z]/.test(tokens[i]))cmd=tokens[i++];
654
+ const C=cmd.toUpperCase(),rel=cmd!==C,n=arity[C];if(n===undefined)return null;
655
+ if(C==='Z'){x=sx;y=sy;mark();continue;}
656
+ const args=[];for(let k=0;k<n;k++){if(i>=tokens.length||/[a-zA-Z]/.test(tokens[i]))return null;args.push(num());}
657
+ if(C==='H')x=(rel?x:0)+args[0];else if(C==='V')y=(rel?y:0)+args[0];
658
+ else{const ex=args[n-2],ey=args[n-1];x=(rel?x:0)+ex;y=(rel?y:0)+ey;}
659
+ if(C==='M'){sx=x;sy=y;cmd=rel?'l':'L';}
660
+ mark();
661
+ }
662
+ return minX===Infinity?null:[minX,minY,maxX-minX,maxY-minY];
663
+ }
664
+ // Figma sometimes exports SVGs with unclosed <g> elements; browsers then refuse to render them.
665
+ function balanced(x){const st=[];for(const m of x.matchAll(/<(\/?)([a-zA-Z][\w:-]*)[^>]*?(\/?)>/g)){if(m[0].startsWith('<?')||m[0].startsWith('<!'))continue;if(m[3])continue;if(m[1]){if(st.pop()!==m[2])return false;}else st.push(m[2]);}return st.length===0;}
666
+ function repairSvg(x){
667
+ const st=[];let out='',last=0;
668
+ for(const m of x.matchAll(/<(\/?)([a-zA-Z][\w:-]*)[^>]*?(\/?)>/g)){
669
+ if(m[3])continue;
670
+ if(!m[1]){st.push(m[2]);continue;}
671
+ if(st.includes(m[2])){let close='';while(st.length&&st.at(-1)!==m[2])close+='</'+st.pop()+'>';st.pop();
672
+ out+=x.slice(last,m.index)+close;last=m.index;}
673
+ }
674
+ return out+x.slice(last);
675
+ }
676
+
677
+ // ---------- subset ----------
678
+ // 只保留选中的单元,以及它们用到的模板、样式、连线:先拉不带图片的 AST 决定范围,再只下这部分图片
679
+ function subset(specs,out){
680
+ if(!specs.length||!out)throw new Error('subset needs unit ids and -o <file>');
681
+ const units=specs.map(spec=>structuredClone(locate(spec)));
682
+ const used=new Set();
683
+ const visit=n=>{if(!n||typeof n!=='object')return;if(Array.isArray(n))return n.forEach(visit);
684
+ if(typeof n.t==='string'&&!used.has(n.t)&&T[n.t]){used.add(n.t);visit(T[n.t].body);}
685
+ Object.values(n).forEach(v=>{if(v&&typeof v==='object')visit(v);});};
686
+ units.forEach(visit);
687
+ const templates=Object.fromEntries([...used].map(k=>[k,T[k]]));
688
+ const keys=new Set();const collect=v=>{if(typeof v==='string'){if(v in G&&!keys.has(v)){keys.add(v);const e=G[v];if(e&&typeof e.extends==='string')e.extends.split(',').map(x=>x.trim()).forEach(collect);}return;}
689
+ if(Array.isArray(v))return v.forEach(collect);if(v&&typeof v==='object')Object.values(v).forEach(collect);};
690
+ collect({units,templates});
691
+ const globalStyles=Object.fromEntries(Object.keys(G).filter(k=>keys.has(k)).map(k=>[k,G[k]]));
692
+ const ids=new Set();walk(units,n=>{if(n.id!==undefined)ids.add(String(n.id));});
693
+ const connectors=(ast.connectors??[]).filter(c=>ids.has(String(c.from).split('/')[0])||ids.has(String(c.to).split('/')[0]));
694
+ const result={name:ast.name,fileKey:ast.fileKey,...(connectors.length?{connectors}:{}),nodes:units,templates,globalStyles};
695
+ writeFileSync(out,JSON.stringify(result));
696
+ const remote=new Set(JSON.stringify(result).match(/https:\/\/[^"\\)]+/g)??[]);
697
+ console.log(`subset: ${units.length} units, ${used.size}/${Object.keys(T).length} templates, ${keys.size}/${Object.keys(G).length} styles, ${remote.size} image links → ${out}`);
698
+ }
699
+
700
+ // ---------- prune ----------
701
+ // 生码完成后删掉代码里没有引用的图片(只动 AST 图片目录里的图片文件)
702
+ function prune(dirs,apply){
703
+ const dir=imageDir();if(!dir)throw new Error('no local images in this AST');
704
+ let code='';const exts=new Set(['.js','.jsx','.ts','.tsx','.vue','.svelte','.html','.css','.scss','.less','.json','.md','.mjs']);
705
+ const rd=p=>{let s;try{s=statSync(p);}catch{return;}
706
+ if(s.isDirectory()){if(/^(node_modules|\.git|dist|build|\.next|\.melonbuild)$/.test(basename(p)))return;for(const f of readdirSync(p))rd(join(p,f));}
707
+ else if(exts.has(extname(p))&&s.size<2e6)code+=readFileSync(p,'utf8')+'\n';};
708
+ for(const d of dirs.length?dirs:['.'])rd(d);
709
+ // 只动这份 AST 下载的图片:资源目录里用户原有的文件(别的模块、手放的图)一律不碰
710
+ const ours=new Set(localImageRefs().map(r=>r.file));
711
+ const files=readdirSync(dir).filter(f=>/\.(svg|png|jpe?g|webp|gif)$/i.test(f)&&ours.has(f));
712
+ const unused=files.filter(f=>!code.includes(f)&&!code.includes(encodeURI(f)));
713
+ const bytes=unused.reduce((s,f)=>s+statSync(join(dir,f)).size,0);
714
+ console.log(`${files.length-unused.length}/${files.length} images referenced by code; ${unused.length} unused (${(bytes/1e6).toFixed(1)}MB) in ${dir}`);
715
+ if(!apply){if(unused.length)console.log(' '+unused.slice(0,30).join('\n ')+(unused.length>30?'\n … +'+(unused.length-30):'')+'\nRun with --apply to delete them.');return;}
716
+ for(const f of unused)unlinkSync(join(dir,f));
717
+ console.log(`deleted ${unused.length} files`);
718
+ }
719
+
720
+ try{
721
+ if(cmd==='outline')outline();
722
+ else if(cmd==='assets')assets(rest.includes('--apply'));
723
+ else if(cmd==='subset'){const out=opt('-o');subset(rest,out);}
724
+ else if(cmd==='prune'){const apply=rest.includes('--apply');prune(rest.filter(x=>x!=='--apply'),apply);}
725
+ else if(cmd==='tokens')tokens();
726
+ else if(cmd==='show'){const d=Number(opt('--depth','99'));const ex=rest.includes('--expand');const specs=rest.filter(x=>x!=='--expand');
727
+ if(!specs.length)throw new Error('show needs an id, template or path');show(specs.map(spec=>({spec,root:locate(spec)})),d,ex);}
728
+ else if(cmd==='diff'){if(rest.length<2)throw new Error('diff needs two ids');diff(rest[0],rest[1]);}
729
+ else if(cmd==='texts'){const n=rest[0]?locate(rest[0]):{tag:'ROOT',children:ast.nodes};console.log([...new Set(texts(n))].join('\n'));}
730
+ else if(cmd==='check')check(rest);
731
+ else {console.log(USAGE);process.exit(1);}
732
+ }catch(e){console.error('mb: '+e.message);process.exit(1);}