rcompiler 0.0.0-stage → 2.1.0

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.
@@ -0,0 +1,563 @@
1
+ // rCompiler V2 — 阶段A:项目预扫描分析器
2
+ // 输入 project.json (+可选 opts),输出 Profile,驱动"选择性架构":按需加载运行时模块。
3
+ //
4
+ // 帧模型 / 舞台开关 / 舞台尺寸:
5
+ // - TurboWarp 舞台注释(" // _twconfig_" 行)提供 framerate / interpolation / turbo / width / height
6
+ // - extensionStorage.rcompiler.project 三态设置('default' | 'on' | 'off'):
7
+ // Stage 舞台启用(default=编译器检测:无舞台块默认关,否则开)
8
+ // FrameRate 帧率设置(default=跟随 TW/检测;off=不锁帧;on=强制锁帧)
9
+ // Interpolation 视觉插值(default=跟随 TW;on/off=强制)
10
+ // - 三态 on/off 覆盖 TW;'default' 跟随 TW 或编译器检测
11
+ // - CLI(opts.frame,由 cli.js 传入)位于项目配置之后、默认值之前
12
+ // - 禁用舞台:跳过舞台块编译(standard.js 按 isStageMode 降级)、不启用帧门控
13
+
14
+ 'use strict';
15
+
16
+ const { resolveTarget } = require('./targets');
17
+
18
+ const STAGE_PREFIXES = ['motion_', 'pen_'];
19
+ // 这些外观积木有控制台回退(println),不触发舞台模块
20
+ const CONSOLE_FALLBACK_LOOKS = new Set([
21
+ 'looks_say', 'looks_think', 'looks_sayforsecs', 'looks_thinkforsecs'
22
+ ]);
23
+
24
+ // 这些 opcode 属于"写变量/列表"
25
+ const WRITE_OPS = new Set([
26
+ 'data_setvariableto', 'data_changevariableby',
27
+ 'data_addtolist', 'data_deletealloflist', 'data_deleteoflist',
28
+ 'data_insertatlist', 'data_replaceitemoflist',
29
+ 'rcompiler_varcreate', 'rcompiler_varset'
30
+ ]);
31
+
32
+ // 标准 Scratch 类别前缀:"调试→自动忽略扩展"名单只作用于自制/第三方扩展 id,
33
+ // 误填标准类别时按无效设置处理(避免把变量/运动等标准积木整体跳过)
34
+ const STD_OPCODE_PREFIXES = new Set([
35
+ 'motion', 'looks', 'sound', 'events', 'control', 'sensing',
36
+ 'operators', 'data', 'procedures', 'argument'
37
+ ]);
38
+
39
+ // 解析"调试→自动忽略扩展"名单(逗号/顿号/分号/空白分隔扩展 id)
40
+ function parseIgnoreExt(s) {
41
+ const out = new Set();
42
+ for (const id of splitNames(s)) {
43
+ if (STD_OPCODE_PREFIXES.has(id)) {
44
+ console.warn(`\x1b[33m忽略扩展设置\x1b[m: 「${id}」是标准积木类别而非扩展 id,已跳过该项`);
45
+ continue;
46
+ }
47
+ out.add(id);
48
+ }
49
+ return out;
50
+ }
51
+
52
+ // opcode 是否属于被忽略扩展(扩展积木 opcode 形如 <扩展id>_<块名>,id 不含下划线)
53
+ function isIgnoredExtOp(op, ignoreSet) {
54
+ if (!ignoreSet || !ignoreSet.size || typeof op !== 'string') return false;
55
+ const i = op.indexOf('_');
56
+ if (i <= 0) return false;
57
+ return ignoreSet.has(op.slice(0, i));
58
+ }
59
+
60
+ // 手动类型描述("优化"页):数字/整数/字符串变量 + 数字/字符串列表。
61
+ // 逗号/顿号/分号/空白分隔变量名;与 rcompiler_type/rcompiler_typelist 声明块互补
62
+ // (块声明优先,手动描述补充未声明的同名变量/列表)。
63
+ function splitNames(s) {
64
+ return String(s || '').split(/[,,;;\s]+/).map(x => x.trim()).filter(Boolean);
65
+ }
66
+
67
+ // 健壮解析:Scratch 变量/列表名常含空格(如 "RISC Ram Read return")。
68
+ // 优先整段精确匹配;否则在段内做“最长匹配”——把连续单词粘成已知的变量/列表名。
69
+ // 这样 单词名 与 含空格名 都能正确表达(含空格名需保证与项目中的名字一致)。
70
+ function parseTypeDesc(s, knownNames) {
71
+ const out = new Set();
72
+ const known = knownNames instanceof Set ? knownNames : new Set(knownNames || []);
73
+ if (!known.size) {
74
+ for (const n of splitNames(s)) out.add(n);
75
+ return [...out];
76
+ }
77
+ for (const seg0 of String(s || '').split(/[,,;;]+/)) {
78
+ const seg = seg0.trim();
79
+ if (!seg) continue;
80
+ if (known.has(seg)) { out.add(seg); continue; }
81
+ const words = seg.split(/\s+/).filter(Boolean);
82
+ let i = 0, matchedAny = false;
83
+ while (i < words.length) {
84
+ let matched = null;
85
+ for (let j = words.length; j > i; j--) {
86
+ const cand = words.slice(i, j).join(' ');
87
+ if (known.has(cand)) { matched = cand; i = j; break; }
88
+ }
89
+ if (matched) { out.add(matched); matchedAny = true; }
90
+ else i++;
91
+ }
92
+ if (!matchedAny) {
93
+ // 完全未知:退回按词拆分(保持旧行为,避免用户输入的普通名单失效)
94
+ for (const w of words) if (known.has(w)) out.add(w);
95
+ }
96
+ }
97
+ return [...out];
98
+ }
99
+
100
+ // 收集项目中全部变量/列表名(供类型描述匹配)
101
+ function collectNames(projectJson) {
102
+ const names = new Set();
103
+ for (const t of (projectJson.targets || [])) {
104
+ for (const v of Object.values(t.variables || {})) names.add(String(v[0]));
105
+ for (const l of Object.values(t.lists || {})) names.add(String(l[0]));
106
+ }
107
+ return names;
108
+ }
109
+
110
+ const VAR_TYPE_MAP = {
111
+ 'f64': 'f64', '数字': 'f64', 'num': 'f64', 'number': 'f64',
112
+ 'i32': 'i32', 'usize': 'usize',
113
+ 'String': 'String', '字符串': 'String', 'str': 'String', 'text': 'String',
114
+ 'bool': 'bool', '布尔': 'bool', 'boolean': 'bool'
115
+ };
116
+
117
+ function normType(t) {
118
+ return VAR_TYPE_MAP[t] || null;
119
+ }
120
+
121
+ // ============ TurboWarp 舞台注释配置 ============
122
+ const TW_CONFIG_MAGIC = ' // _twconfig_';
123
+
124
+ function parseTwConfig(projectJson) {
125
+ const out = {};
126
+ const stage = (projectJson.targets || []).find(t => t.isStage);
127
+ if (!stage || !stage.comments) return out;
128
+ for (const c of Object.values(stage.comments)) {
129
+ const text = String((c && c.text) || '');
130
+ for (const line of text.split('\n')) {
131
+ if (!line.endsWith(TW_CONFIG_MAGIC)) continue;
132
+ try {
133
+ const parsed = JSON.parse(line.slice(0, line.length - TW_CONFIG_MAGIC.length));
134
+ if (parsed && typeof parsed === 'object') Object.assign(out, parsed);
135
+ } catch (e) { /* 非法注释忽略 */ }
136
+ }
137
+ }
138
+ return out;
139
+ }
140
+
141
+ // 三态归一:'on'/true → 'on';'off'/false → 'off';其他 → 'default'
142
+ function tri(v) {
143
+ if (v === 'on' || v === true) return 'on';
144
+ if (v === 'off' || v === false) return 'off';
145
+ return 'default';
146
+ }
147
+
148
+ // 抗逆向:'normal'(默认,现状)| 'obf'(混淆)| 'debug'(调试)
149
+ function normAntiReverse(v) {
150
+ if (v === 'obf' || v === '混淆') return 'obf';
151
+ if (v === 'debug' || v === '调试') return 'debug';
152
+ return 'normal';
153
+ }
154
+
155
+ // 打包配置默认值(均为"现状行为",保证不配置时行为不变)
156
+ const APP_DEFAULTS = {
157
+ Title: null, // null = 使用项目名
158
+ Icon: null, // data:image/png;base64,...
159
+ Resizable: false,
160
+ Fullscreen: false,
161
+ Decorations: true,
162
+ HideCursor: false,
163
+ Controls: false, // 旧版顶栏总开关(向后兼容):true = 三个按钮全开
164
+ BtnFlag: false, // 顶栏绿旗按钮
165
+ BtnPause: false, // 顶栏暂停按钮
166
+ BtnStop: false, // 顶栏停止按钮
167
+ Autoplay: true, // 启动即运行绿旗
168
+ ExitKey: 'none', // none | escape | ctrlq
169
+ QuitOnStop: false,
170
+ CloneLimit: 300,
171
+ Bg: '#000000',
172
+ StageWidth: null, // 舞台宽(null = 跟随 TurboWarp width,再默认 480)
173
+ StageHeight: null // 舞台高(null = 跟随 TurboWarp height,再默认 360)
174
+ };
175
+
176
+ function parseHexColor(s, dflt) {
177
+ const m = String(s || '').trim().match(/^#?([0-9a-fA-F]{6})$/);
178
+ return m ? '#' + m[1].toLowerCase() : dflt;
179
+ }
180
+
181
+ // 取第一个有限数字
182
+ function pickNum(...vals) {
183
+ for (const v of vals) {
184
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
185
+ }
186
+ return null;
187
+ }
188
+
189
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
190
+
191
+ // 模组角色(mods//<模组名>//<角色名>,或展开时标记 isRcModTarget)
192
+ const isModTarget = (t) => t && (t.isRcModTarget === true || String(t.name || '').startsWith('mods//'));
193
+
194
+ function analyze(projectJson, opts = {}) {
195
+ const target = (opts.targetInfo && typeof opts.targetInfo === 'object')
196
+ ? opts.targetInfo : resolveTarget(opts.target);
197
+ const profile = {
198
+ opcodes: new Set(),
199
+ target,
200
+ backend: target.backend, // native | web
201
+ headless: !target.canStage, // 无桌面能力(wasi/裸机/通用交叉目标)
202
+ hasStage: false,
203
+ hasSound: false,
204
+ concurrency: 'single',
205
+ forcedMultiReasons: [],
206
+ typeDeclared: new Map(), // varKey -> rust type varKey = `${targetIndex}:${name}`
207
+ listTypeDeclared: new Map(), // listKey -> 'String'|'f64'
208
+ targets: [], // {index,name,isStage,entryCount,writes,hasCloneStart}
209
+ assets: { costumes: [], sounds: [] },
210
+ extensionStorage: (projectJson.extensionStorage && projectJson.extensionStorage.rcompiler) || null,
211
+ flagCount: 0, keyCount: 0, cloneStartCount: 0, cloneMakeCount: 0,
212
+ broadcastCount: 0, allAtOnceCount: 0, thisSpriteClickedCount: 0,
213
+ costumeMeta: [], // per target: [{file,w,h,name}]
214
+ soundMeta: [], // [{file,name,target}]
215
+ tw: {}, // TurboWarp 注释原始配置
216
+ rcHatCount: 0, // 起动帽形状的自制积木调用(宿主角色)
217
+ stageOn: false, // 舞台最终是否启用
218
+ frame: null, // 帧模型解析结果 {gate,tps,renderFps,interpolation,turbo}
219
+ stageSize: { width: 480, height: 360 },
220
+ ignoreExt: new Set(), // "调试→自动忽略扩展"名单(extensionStorage.rcompiler.project.ignoreExt / CLI --ignore-ext)
221
+ ignoredBlocks: 0, // 被忽略扩展的块数(预扫描统计,供日志汇报)
222
+ monitors: [] // 可见监视器(project.monitors;运行时快照绘制)
223
+ };
224
+
225
+ // ============ 监视器(对照 scratch-vm 的 monitors:仅收集可见项) ============
226
+ // 支持的 opcode:变量/列表 + 内置侦测报告器;其余(扩展监视器)编译时告警跳过
227
+ const MON_OPCODES = new Set([
228
+ 'data_variable', 'data_listcontents',
229
+ 'sensing_timer', 'sensing_answer', 'sensing_loudness', 'sensing_dayssince2000',
230
+ 'sensing_username', 'sensing_current', 'sensing_mousedown', 'sensing_mousex', 'sensing_mousey'
231
+ ]);
232
+ for (const m of (projectJson.monitors || [])) {
233
+ if (!m || m.visible === false) continue;
234
+ if (!MON_OPCODES.has(m.opcode)) {
235
+ console.warn(`\x1b[33m监视器暂不支持,已跳过\x1b[m: ${m.opcode || m.id}`);
236
+ continue;
237
+ }
238
+ profile.monitors.push({
239
+ id: String(m.id || ''),
240
+ opcode: m.opcode,
241
+ mode: ['large', 'slider', 'list'].includes(m.mode) ? m.mode : 'default',
242
+ params: (m.params && typeof m.params === 'object') ? m.params : {},
243
+ spriteName: m.spriteName != null ? String(m.spriteName) : null,
244
+ x: Number(m.x) || 0, y: Number(m.y) || 0,
245
+ width: Number(m.width) || 0, height: Number(m.height) || 0,
246
+ sliderMin: Number(m.sliderMin != null ? m.sliderMin : 0),
247
+ sliderMax: Number(m.sliderMax != null ? m.sliderMax : 100),
248
+ isDiscrete: m.isDiscrete !== false
249
+ });
250
+ }
251
+
252
+ const targets = projectJson.targets || [];
253
+ // 忽略名单需在块扫描前确定:被忽略扩展的块不参与舞台/声音/并发判定
254
+ const extProjEarly = (profile.extensionStorage && profile.extensionStorage.project) || {};
255
+ profile.ignoreExt = parseIgnoreExt(
256
+ (extProjEarly.ignoreExt != null && extProjEarly.ignoreExt !== '') ? extProjEarly.ignoreExt : opts.ignoreExt
257
+ );
258
+ const stat = targets.map(() => ({ entryCount: 0, writes: 0, hasCloneStart: false, writeKeys: new Set() }));
259
+
260
+ targets.forEach((t, ti) => {
261
+ profile.targets.push({
262
+ index: ti, name: t.name || ('target' + ti), isStage: !!t.isStage,
263
+ entryCount: 0, writes: false, hasCloneStart: false,
264
+ x: t.x || 0, y: t.y || 0, direction: t.direction == null ? 90 : t.direction,
265
+ size: t.size == null ? 100 : t.size, visible: t.visible !== false,
266
+ costumes: (t.costumes || []).map(c => c.name),
267
+ currentCostume: t.currentCostume || 0,
268
+ sounds: (t.sounds || []).map(s => s.name)
269
+ });
270
+ // 造型资产
271
+ (t.costumes || []).forEach((c, ci) => {
272
+ if (!c.md5ext) return;
273
+ const isBitmap = (c.dataFormat === 'png' || c.dataFormat === 'jpg' || c.dataFormat === 'jpeg');
274
+ profile.assets.costumes.push({
275
+ target: ti, index: ci, name: c.name || ('costume' + ci),
276
+ assetId: c.assetId, file: c.md5ext,
277
+ bitmap: isBitmap,
278
+ bitmapResolution: c.bitmapResolution || 1,
279
+ rotationCenterX: c.rotationCenterX || 0, rotationCenterY: c.rotationCenterY || 0
280
+ });
281
+ });
282
+ // 声音资产
283
+ (t.sounds || []).forEach((s, si) => {
284
+ if (!s.md5ext) return;
285
+ profile.assets.sounds.push({
286
+ target: ti, index: si, name: s.name || ('sound' + si),
287
+ assetId: s.assetId, file: s.md5ext, dataFormat: s.dataFormat || 'wav',
288
+ rate: s.rate || 22050, sampleCount: s.sampleCount || 0
289
+ });
290
+ });
291
+ });
292
+
293
+ // 遍历所有块
294
+ targets.forEach((t, ti) => {
295
+ const blocks = t.blocks || {};
296
+ for (const id in blocks) {
297
+ const b = blocks[id];
298
+ if (!b || typeof b !== 'object' || !b.opcode) continue;
299
+ const op = b.opcode;
300
+ // 被忽略扩展的块:不进入任何统计(舞台/声音/并发/类型声明均不受其影响)
301
+ if (isIgnoredExtOp(op, profile.ignoreExt)) { profile.ignoredBlocks++; continue; }
302
+ profile.opcodes.add(op);
303
+ if (STAGE_PREFIXES.some(p => op.startsWith(p)) ||
304
+ (op.startsWith('looks_') && !CONSOLE_FALLBACK_LOOKS.has(op)) ||
305
+ // 舞台点击帽/背景切换帽同样依赖舞台模块(此前只有运动/外观/画笔会触发)
306
+ op === 'event_whenstageclicked' || op === 'event_whenbackdropswitchesto') {
307
+ profile.hasStage = true;
308
+ }
309
+ if (op.startsWith('sound_') || op === 'sensing_loudness') profile.hasSound = true;
310
+
311
+ switch (op) {
312
+ case 'event_whenflagclicked':
313
+ // 模组角色的绿旗不随工程启动执行(runtime._startupHatsRunOn)
314
+ if (!isModTarget(t)) { profile.flagCount++; stat[ti].entryCount++; }
315
+ break;
316
+ case 'event_whenkeypressed': profile.keyCount++; stat[ti].entryCount++; break;
317
+ case 'event_whenbroadcastreceived': profile.broadcastCount++; stat[ti].entryCount++; break;
318
+ case 'event_whenthisspriteclicked': profile.thisSpriteClickedCount++; stat[ti].entryCount++; break;
319
+ case 'event_whenstageclicked': stat[ti].entryCount++; break;
320
+ case 'event_whenbackdropswitchesto': stat[ti].entryCount++; break;
321
+ case 'control_start_as_clone': profile.cloneStartCount++; stat[ti].entryCount++; stat[ti].hasCloneStart = true; break;
322
+ case 'control_create_clone_of': profile.cloneMakeCount++; break;
323
+ case 'event_broadcast': case 'event_broadcastandwait': profile.broadcastCount++; break;
324
+ case 'control_all_at_once': profile.allAtOnceCount++; break;
325
+ // 高级自制积木:形状为“起动帽”的调用块(顶层、重复执行定义体)
326
+ case 'procedures_call':
327
+ if (b.mutation && b.mutation.rc_shape === 'hat' && !isModTarget(t)) profile.rcHatCount++;
328
+ break;
329
+ case 'rcompiler_typevar': {
330
+ const f = b.fields || {};
331
+ if (f.NAME && f.TYPE) {
332
+ const ty = normType(f.TYPE[0]);
333
+ if (ty) profile.typeDeclared.set(ti + ':' + f.NAME[0], ty);
334
+ }
335
+ break;
336
+ }
337
+ case 'rcompiler_typelist': {
338
+ const f = b.fields || {};
339
+ if (f.NAME && f.TYPE) {
340
+ const ty = normType(f.TYPE[0]);
341
+ if (ty) profile.listTypeDeclared.set(ti + ':' + f.NAME[0], ty === 'String' ? 'String' : 'f64');
342
+ }
343
+ break;
344
+ }
345
+ default: break;
346
+ }
347
+ if (WRITE_OPS.has(op)) stat[ti].writes++;
348
+ }
349
+ });
350
+
351
+ // 合并统计
352
+ targets.forEach((t, ti) => {
353
+ profile.targets[ti].entryCount = stat[ti].entryCount;
354
+ profile.targets[ti].writes = stat[ti].writes > 0;
355
+ profile.targets[ti].hasCloneStart = stat[ti].hasCloneStart;
356
+ profile.targets[ti].isMod = isModTarget(t);
357
+ });
358
+
359
+ // ============ 手动类型描述("优化"页,extensionStorage.rcompiler.project) ============
360
+ // 变量:数字(numvars)/整数(intvars)/字符串(strvars);列表:数字(numlists)/字符串(strlists)
361
+ const extProj0 = (profile.extensionStorage && profile.extensionStorage.project) || {};
362
+ const knownNames = collectNames(projectJson);
363
+ const manualVars = [
364
+ ['f64', parseTypeDesc(extProj0.numvars, knownNames)],
365
+ ['i32', parseTypeDesc(extProj0.intvars, knownNames)],
366
+ ['String', parseTypeDesc(extProj0.strvars, knownNames)]
367
+ ];
368
+ const manualLists = [
369
+ ['f64', parseTypeDesc(extProj0.numlists, knownNames)],
370
+ ['String', parseTypeDesc(extProj0.strlists, knownNames)]
371
+ ];
372
+ for (const [ty, names] of manualVars) {
373
+ for (const name of names) {
374
+ // 已有块声明的跳过(块声明更具体);对每个含同名变量的 target 及舞台补键
375
+ let found = false;
376
+ targets.forEach((t, ti) => {
377
+ for (const id in (t.variables || {})) {
378
+ if (t.variables[id][0] === name) {
379
+ found = true;
380
+ if (!profile.typeDeclared.has(ti + ':' + name)) profile.typeDeclared.set(ti + ':' + name, ty);
381
+ }
382
+ }
383
+ });
384
+ if (found && !profile.typeDeclared.has('0:' + name)) profile.typeDeclared.set('0:' + name, ty);
385
+ }
386
+ }
387
+ for (const [ty, names] of manualLists) {
388
+ for (const name of names) {
389
+ targets.forEach((t, ti) => {
390
+ for (const id in (t.lists || {})) {
391
+ if (t.lists[id][0] === name && !profile.listTypeDeclared.has(ti + ':' + name)) {
392
+ profile.listTypeDeclared.set(ti + ':' + name, ty === 'String' ? 'String' : 'f64');
393
+ }
394
+ }
395
+ });
396
+ }
397
+ }
398
+
399
+ // ============ 舞台启用(三态) ============
400
+ const tw = parseTwConfig(projectJson);
401
+ profile.tw = tw;
402
+ const extProj = (profile.extensionStorage && profile.extensionStorage.project) || {};
403
+ const stageSetting = tri(extProj.Stage != null ? extProj.Stage : opts.stage);
404
+ if (stageSetting === 'off') profile.hasStage = false; // 禁用舞台:视为无舞台项目
405
+ else if (stageSetting === 'on') profile.hasStage = true; // 强制启用舞台模块
406
+ // default:保持块扫描结果(无舞台块 → 关)
407
+ profile.stageOn = profile.hasStage;
408
+
409
+ // 目标能力约束:舞台/声音需要目标有对应后端。
410
+ // WASI/headless 仅支持纯计算;WASM 舞台走 web 后端(scratch-render JS 宿主)。
411
+ if (profile.hasStage && !target.canStage) {
412
+ throw new Error(`目标 ${target.triple} 不支持舞台渲染(${target.kind})。` +
413
+ '请使用无舞台项目,或选择 WASM / 桌面目标。');
414
+ }
415
+ if (profile.hasSound && !target.canSound) {
416
+ console.warn(`\x1b[33m目标 ${target.triple} 不支持声音,已禁用声音模块\x1b[m`);
417
+ profile.hasSound = false;
418
+ }
419
+ if (target.note) console.warn(`\x1b[33m目标 ${target.triple}:${target.note}\x1b[m`);
420
+
421
+ // 并发判定(保守启发式)
422
+ // "不使用异步运行时"与"不循环克隆的角色"已由编译器自动侦测:
423
+ // - 是否需要异步运行时取决于项目是否含并发积木(此处判定)
424
+ // - 克隆脚本是否递归/循环自克隆由编译器调用图分析决定(见 rcompiler.js)
425
+ const reasons = [];
426
+ if (profile.flagCount > 1) reasons.push('多个绿旗脚本');
427
+ if (profile.keyCount > 0) reasons.push('按键帽');
428
+ if (profile.cloneStartCount > 0 || profile.cloneMakeCount > 0) reasons.push('克隆');
429
+ if (profile.broadcastCount > 0) reasons.push('广播');
430
+ if (profile.allAtOnceCount > 0) reasons.push('all_at_once');
431
+ if (profile.thisSpriteClickedCount > 0) reasons.push('角色点击帽');
432
+ if (profile.rcHatCount > 0) reasons.push('自制积木起动帽');
433
+ if (profile.hasStage) reasons.push('舞台(渲染线程独立)');
434
+ profile.forcedMultiReasons = reasons;
435
+ profile.concurrency = reasons.length > 0 ? 'multi' : 'multi_unknown_check';
436
+ if (reasons.length === 0) profile.concurrency = 'single';
437
+
438
+ // ============ 帧模型 ============
439
+ const frameSetting = tri(extProj.FrameRate != null ? extProj.FrameRate : opts.frameRate);
440
+ const interpSetting = tri(extProj.Interpolation != null ? extProj.Interpolation : opts.interpolation);
441
+ const cli = opts.frame || {};
442
+
443
+ // TW framerate:1..250,0=跟随屏幕;负数按 1
444
+ let framerate = pickNum(tw.framerate, cli.fps);
445
+ if (framerate != null) {
446
+ if (framerate < 0) framerate = 1;
447
+ if (framerate > 250) framerate = 250;
448
+ }
449
+ const turbo = tw.turbo === true || cli.turbo === true;
450
+
451
+ let gate = false, tps = 0;
452
+ if (stageSetting === 'off') {
453
+ // 禁用舞台:不启用帧
454
+ if (framerate != null || cli.fps != null) {
455
+ console.warn('\x1b[33m已禁用舞台:帧率设置不生效(帧门控随舞台一并关闭)\x1b[m');
456
+ }
457
+ gate = false; tps = 0;
458
+ } else if (frameSetting === 'off') {
459
+ gate = false; tps = 0;
460
+ } else if (turbo) {
461
+ // turbo:无帧门控(wait 仍按墙钟)
462
+ gate = false; tps = 0;
463
+ } else if (frameSetting === 'on') {
464
+ gate = true; tps = framerate != null ? framerate : 30;
465
+ } else if (profile.hasStage) {
466
+ // 舞台默认锁帧(TW framerate 优先,其次 CLI,否则 30)
467
+ gate = true; tps = framerate != null ? framerate : 30;
468
+ } else if (framerate != null && framerate > 0) {
469
+ // 无舞台默认不锁帧;显式给出帧率才启用
470
+ gate = true; tps = framerate;
471
+ }
472
+
473
+ // 插值:需 舞台 + 帧门控 + 非turbo + 非0帧率
474
+ let interpolation = false;
475
+ if (gate && profile.hasStage && !turbo && tps !== 0) {
476
+ if (interpSetting === 'on') interpolation = true;
477
+ else if (interpSetting === 'default') interpolation = tw.interpolation === true;
478
+ } else if (interpSetting === 'on') {
479
+ console.warn('\x1b[33m视觉插值需满足 舞台+帧门控+非turbo+非0帧率,当前配置已忽略\x1b[m');
480
+ }
481
+
482
+ const renderFpsRaw = pickNum(cli.renderFps);
483
+ const renderFps = renderFpsRaw != null ? clamp(renderFpsRaw, 0, 1000) : 0;
484
+
485
+ profile.frame = { gate, tps, renderFps, interpolation, turbo };
486
+
487
+ // ============ 舞台尺寸(跟随 TurboWarp width/height;打包 StageWidth/Height 显式覆盖) ============
488
+ profile.stageSize = {
489
+ width: Math.round(clamp(pickNum(tw.width, 480), 20, 1920)),
490
+ height: Math.round(clamp(pickNum(tw.height, 360), 20, 1600))
491
+ };
492
+
493
+ // ============ 抗逆向("编译器配置→安全",extensionStorage.rcompiler.config) ============
494
+ // normal(默认,当前行为)| obf(资产/文本加密 + 去符号)| debug(原名/块号/错误定位)
495
+ const extCfg = (profile.extensionStorage && profile.extensionStorage.config) || {};
496
+ const arcRaw = (extCfg.AntiReverse !== undefined && extCfg.AntiReverse !== null && extCfg.AntiReverse !== '')
497
+ ? extCfg.AntiReverse
498
+ : opts.antiReverse;
499
+ profile.antiReverse = normAntiReverse(arcRaw);
500
+
501
+ // ============ 打包配置("项目配置→打包",extensionStorage.rcompiler.project.App) ============
502
+ // 优先级:面板显式 > CLI > 默认;默认值一律保持现状行为
503
+ const appStored = (extProj.App && typeof extProj.App === 'object') ? extProj.App : {};
504
+ const appCli = (opts.app && typeof opts.app === 'object') ? opts.app : {};
505
+ const has = (o, k) => o[k] !== undefined && o[k] !== null && o[k] !== '';
506
+ const pickStr = (k, dflt) => (has(appStored, k) ? String(appStored[k]) : (has(appCli, k) ? String(appCli[k]) : dflt));
507
+ const pickTri = (k, dflt) => {
508
+ const raw = has(appStored, k) ? appStored[k] : (has(appCli, k) ? appCli[k] : undefined);
509
+ if (raw === undefined) return dflt;
510
+ const v = tri(raw);
511
+ return v === 'default' ? dflt : v === 'on';
512
+ };
513
+ const cloneLimitRaw = pickStr('CloneLimit', APP_DEFAULTS.CloneLimit);
514
+ const cloneLimit = Math.round(clamp(Number(cloneLimitRaw) || APP_DEFAULTS.CloneLimit, 1, 9999));
515
+ const exitKeyRaw = String(pickStr('ExitKey', APP_DEFAULTS.ExitKey) || 'none').toLowerCase();
516
+ // 顶栏三按钮:显式设置优先;未设置时向后兼容旧版总开关 Controls(true = 全开)
517
+ const controlsRaw = has(appStored, 'Controls') ? appStored['Controls'] : (has(appCli, 'Controls') ? appCli['Controls'] : undefined);
518
+ const btnVal = (k) => {
519
+ const raw = has(appStored, k) ? appStored[k] : (has(appCli, k) ? appCli[k] : undefined);
520
+ if (raw !== undefined) { const v = tri(raw); return v === 'default' ? false : v === 'on'; }
521
+ return controlsRaw === true || controlsRaw === 'on';
522
+ };
523
+ // 舞台尺寸:面板显式(数字)> TurboWarp width/height > 默认
524
+ const appNum = (k) => {
525
+ const raw = has(appStored, k) ? appStored[k] : (has(appCli, k) ? appCli[k] : undefined);
526
+ if (raw === undefined || raw === null || raw === '') return null;
527
+ const n = Number(raw);
528
+ return Number.isFinite(n) ? n : null;
529
+ };
530
+ profile.app = {
531
+ title: pickStr('Title', APP_DEFAULTS.Title),
532
+ icon: pickStr('Icon', APP_DEFAULTS.Icon),
533
+ resizable: pickTri('Resizable', APP_DEFAULTS.Resizable),
534
+ fullscreen: pickTri('Fullscreen', APP_DEFAULTS.Fullscreen),
535
+ decorations: pickTri('Decorations', APP_DEFAULTS.Decorations),
536
+ hideCursor: pickTri('HideCursor', APP_DEFAULTS.HideCursor),
537
+ controls: pickTri('Controls', APP_DEFAULTS.Controls),
538
+ btnFlag: btnVal('BtnFlag'),
539
+ btnPause: btnVal('BtnPause'),
540
+ btnStop: btnVal('BtnStop'),
541
+ autoplay: pickTri('Autoplay', APP_DEFAULTS.Autoplay),
542
+ exitKey: ['escape', 'ctrlq'].includes(exitKeyRaw) ? exitKeyRaw : 'none',
543
+ quitOnStop: pickTri('QuitOnStop', APP_DEFAULTS.QuitOnStop),
544
+ cloneLimit,
545
+ bg: parseHexColor(pickStr('Bg', APP_DEFAULTS.Bg), APP_DEFAULTS.Bg),
546
+ stageWidth: appNum('StageWidth'),
547
+ stageHeight: appNum('StageHeight')
548
+ };
549
+ // 仅舞台项目有窗口;打包项对无舞台项目无意义(克隆上限同样只用于舞台运行时)
550
+ if (!profile.hasStage && (Object.keys(appStored).length > 0 || Object.keys(appCli).length > 0)) {
551
+ console.warn('\x1b[33m打包选项仅对舞台项目生效,当前项目未启用舞台,窗口/顶栏设置已忽略\x1b[m');
552
+ }
553
+ if (profile.hasStage && !profile.app.autoplay && !(profile.app.btnFlag || profile.app.btnPause || profile.app.btnStop)) {
554
+ console.warn('\x1b[33m已关闭自动启动但未启用任何顶栏按钮:项目启动后将不会运行,请开启打包→顶栏按钮\x1b[m');
555
+ }
556
+ // 打包长宽显式设置覆盖 TurboWarp 注释
557
+ if (profile.app.stageWidth != null) profile.stageSize.width = Math.round(clamp(profile.app.stageWidth, 20, 1920));
558
+ if (profile.app.stageHeight != null) profile.stageSize.height = Math.round(clamp(profile.app.stageHeight, 20, 1600));
559
+
560
+ return profile;
561
+ }
562
+
563
+ module.exports = { analyze, normType, parseTwConfig, parseIgnoreExt, isIgnoredExtOp };