@playcraft/build 0.1.93-test → 0.1.95-test-a
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/dist/audio-source-files.d.ts +5 -0
- package/dist/audio-source-files.js +135 -0
- package/dist/base-builder.js +41 -2
- package/dist/delivery/agent-build-runner.d.ts +44 -0
- package/dist/delivery/agent-build-runner.js +365 -0
- package/dist/delivery/agent-build-source.d.ts +8 -0
- package/dist/delivery/agent-build-source.js +25 -0
- package/dist/delivery/artifact-descriptor.d.ts +31 -0
- package/dist/delivery/artifact-descriptor.js +237 -0
- package/dist/delivery/artifact-package.d.ts +43 -0
- package/dist/delivery/artifact-package.js +283 -0
- package/dist/delivery/build-plan.d.ts +4 -0
- package/dist/delivery/build-plan.js +189 -0
- package/dist/delivery/build-plan.types.d.ts +51 -0
- package/dist/delivery/build-plan.types.js +1 -0
- package/dist/delivery/command-isolation.d.ts +20 -0
- package/dist/delivery/command-isolation.js +324 -0
- package/dist/delivery/commands.d.ts +5 -0
- package/dist/delivery/commands.js +146 -0
- package/dist/delivery/files.d.ts +9 -0
- package/dist/delivery/files.js +144 -0
- package/dist/delivery/git-source-fingerprint.d.ts +2 -0
- package/dist/delivery/git-source-fingerprint.js +58 -0
- package/dist/delivery/isolated-source.d.ts +5 -0
- package/dist/delivery/isolated-source.js +126 -0
- package/dist/delivery/output-publication.d.ts +21 -0
- package/dist/delivery/output-publication.js +444 -0
- package/dist/delivery/project-delivery.d.ts +6 -0
- package/dist/delivery/project-delivery.js +287 -0
- package/dist/delivery/recipe-build-plan.d.ts +4 -0
- package/dist/delivery/recipe-build-plan.js +53 -0
- package/dist/delivery/recipe.d.ts +20 -0
- package/dist/delivery/recipe.js +211 -0
- package/dist/delivery/safe-path.d.ts +2 -0
- package/dist/delivery/safe-path.js +18 -0
- package/dist/delivery/types.d.ts +76 -0
- package/dist/delivery/types.js +1 -0
- package/dist/engines/engine-detector.js +4 -0
- package/dist/engines/generic-adapter.js +14 -19
- package/dist/index.d.ts +19 -4
- package/dist/index.js +11 -2
- package/dist/platforms/adikteev.js +1 -0
- package/dist/platforms/applovin.js +1 -0
- package/dist/platforms/base.js +2 -2
- package/dist/platforms/bigo.js +1 -0
- package/dist/platforms/facebook.js +1 -0
- package/dist/platforms/google.js +1 -0
- package/dist/platforms/inmobi.js +1 -0
- package/dist/platforms/ironsource.js +1 -0
- package/dist/platforms/liftoff.js +1 -0
- package/dist/platforms/mintegral.js +1 -0
- package/dist/platforms/moloco.js +1 -0
- package/dist/platforms/playcraft.js +1 -0
- package/dist/platforms/remerge.js +1 -0
- package/dist/platforms/snapchat.js +1 -0
- package/dist/platforms/tiktok.js +1 -0
- package/dist/platforms/unity.js +1 -0
- package/dist/production-animation-presence.d.ts +2 -0
- package/dist/production-animation-presence.js +146 -0
- package/dist/production-inputs.d.ts +30 -0
- package/dist/production-inputs.js +262 -0
- package/dist/production-source-paths.d.ts +5 -0
- package/dist/production-source-paths.js +27 -0
- package/dist/types.d.ts +5 -0
- package/dist/validation/artifact-qa.d.ts +44 -0
- package/dist/validation/artifact-qa.js +170 -0
- package/dist/validation/artifact-rules.d.ts +28 -0
- package/dist/validation/artifact-rules.js +440 -0
- package/dist/validation/artifact.d.ts +14 -0
- package/dist/validation/artifact.js +188 -0
- package/dist/validation/html-validator.d.ts +5 -0
- package/dist/validation/html-validator.js +19 -17
- package/dist/validation/index.d.ts +4 -0
- package/dist/validation/index.js +4 -0
- package/dist/validation/package-validator.d.ts +2 -0
- package/dist/validation/package-validator.js +25 -64
- package/dist/validation/profiles.d.ts +13 -1
- package/dist/validation/profiles.js +27 -0
- package/dist/validation/runtime-load.d.ts +89 -0
- package/dist/validation/runtime-load.js +654 -0
- package/dist/validation/source-scanner.d.ts +11 -0
- package/dist/validation/source-scanner.js +32 -2
- package/dist/validation/types.d.ts +155 -2
- package/dist/validation/types.js +1 -1
- package/dist/validation/validation-runner.d.ts +22 -2
- package/dist/validation/validation-runner.js +68 -3
- package/dist/validation/zip-reader.d.ts +7 -0
- package/dist/validation/zip-reader.js +159 -26
- package/dist/vite/config-builder-generic.d.ts +3 -1
- package/dist/vite/config-builder-generic.js +9 -7
- package/dist/vite/config-builder.js +1 -1
- package/dist/vite/plugin-platform.js +30 -54
- package/dist/vite/plugin-source-builder.d.ts +2 -14
- package/dist/vite/plugin-source-builder.js +61 -997
- package/dist/vite/source-builder-asset-paths.d.ts +25 -0
- package/dist/vite/source-builder-asset-paths.js +154 -0
- package/dist/vite/source-builder-esm.d.ts +7 -0
- package/dist/vite/source-builder-esm.js +877 -0
- package/dist/vite/source-builder-types.d.ts +14 -0
- package/dist/vite/source-builder-types.js +1 -0
- package/dist/vite/workspace.d.ts +6 -0
- package/dist/vite/workspace.js +41 -0
- package/dist/vite-builder.d.ts +4 -5
- package/dist/vite-builder.js +33 -34
- package/dist/workspace-css-imports.d.ts +2 -0
- package/dist/workspace-css-imports.js +139 -0
- package/dist/workspace-model-source.d.ts +14 -0
- package/dist/workspace-model-source.js +184 -0
- package/dist/workspace-public-imports.d.ts +11 -0
- package/dist/workspace-public-imports.js +232 -0
- package/dist/workspace-public-source.d.ts +15 -0
- package/dist/workspace-public-source.js +564 -0
- package/package.json +16 -4
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { generateESMTemplate } from './source-builder-esm.js';
|
|
2
|
+
import { buildFolderFullPathMap, resolveTreePathFromPathArray, } from './source-builder-asset-paths.js';
|
|
1
3
|
import fs from 'fs/promises';
|
|
2
4
|
import path from 'path';
|
|
3
5
|
import { fileURLToPath } from 'url';
|
|
@@ -54,7 +56,11 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
54
56
|
}
|
|
55
57
|
// 通过 Import Map 解析裸模块说明符(如 gameRule、planck 等)
|
|
56
58
|
// Import Map 中的路径是相对于 assets/ 目录的(Import Map 文件本身在 assets/Import Map.json 中)
|
|
57
|
-
if (options.importMap?.content?.imports &&
|
|
59
|
+
if (options.importMap?.content?.imports &&
|
|
60
|
+
!id.startsWith('./') &&
|
|
61
|
+
!id.startsWith('../') &&
|
|
62
|
+
!id.startsWith('/') &&
|
|
63
|
+
!id.startsWith('\0')) {
|
|
58
64
|
const imports = options.importMap.content.imports;
|
|
59
65
|
const assetsDir = path.join(options.projectDir, 'assets');
|
|
60
66
|
// 精确匹配(如 "gameRule" -> "./Generated/GameRule/BreakshotPoolRule.mjs")
|
|
@@ -105,14 +111,16 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
105
111
|
if (id === '\0virtual:game-scripts') {
|
|
106
112
|
// 生成入口文件,直接导入所有真实的脚本文件
|
|
107
113
|
// 让 Vite 自然地处理这些文件及其依赖关系
|
|
108
|
-
const imports = userScripts
|
|
114
|
+
const imports = userScripts
|
|
115
|
+
.map((script) => {
|
|
109
116
|
const scriptPath = path.join(options.projectDir, script.path);
|
|
110
117
|
// 将 Windows 路径中的反斜杠转换为正斜杠,避免在 import 语句中被解释为转义字符
|
|
111
118
|
// 使用 split + join 方式更可靠地处理路径分隔符
|
|
112
119
|
const normalizedPath = scriptPath.split(path.sep).join('/');
|
|
113
120
|
console.log(`[SourceBuilder] 脚本路径: ${scriptPath} -> ${normalizedPath}`);
|
|
114
121
|
return `import '${normalizedPath}';`;
|
|
115
|
-
})
|
|
122
|
+
})
|
|
123
|
+
.join('\n');
|
|
116
124
|
console.log(`[SourceBuilder] 虚拟模块内容:\n${imports}`);
|
|
117
125
|
return imports || '// No user scripts';
|
|
118
126
|
}
|
|
@@ -137,9 +145,7 @@ export function viteSourceBuilderPlugin(options) {
|
|
|
137
145
|
console.log('[SourceBuilder] 生成 config.json');
|
|
138
146
|
// 生成 __settings__.js
|
|
139
147
|
// 如果 config.scenes 中有场景,使用第一个场景的 URL
|
|
140
|
-
const firstScenePath = config.scenes && config.scenes.length > 0
|
|
141
|
-
? config.scenes[0].url
|
|
142
|
-
: undefined;
|
|
148
|
+
const firstScenePath = config.scenes && config.scenes.length > 0 ? config.scenes[0].url : undefined;
|
|
143
149
|
const settings = generateSettings(projectConfig, firstScenePath);
|
|
144
150
|
await fs.writeFile(path.join(options.outputDir, '__settings__.js'), settings, 'utf-8');
|
|
145
151
|
console.log('[SourceBuilder] 生成 __settings__.js');
|
|
@@ -175,6 +181,7 @@ async function detectFormat(projectDir) {
|
|
|
175
181
|
if (manifest.format === 'playcraft' || Array.isArray(manifest.assets)) {
|
|
176
182
|
return 'playcraft';
|
|
177
183
|
}
|
|
184
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
178
185
|
}
|
|
179
186
|
catch (error) {
|
|
180
187
|
// manifest.json 不存在或格式不对
|
|
@@ -194,6 +201,7 @@ function buildScriptPathMapping(projectConfig, userScripts, projectDir) {
|
|
|
194
201
|
// 构建文件夹 ID 到名称的映射
|
|
195
202
|
const folderMap = new Map();
|
|
196
203
|
for (const [assetId, asset] of Object.entries(assets)) {
|
|
204
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
197
205
|
const assetData = asset;
|
|
198
206
|
if (assetData.type === 'folder') {
|
|
199
207
|
folderMap.set(assetId, assetData.name);
|
|
@@ -201,6 +209,7 @@ function buildScriptPathMapping(projectConfig, userScripts, projectDir) {
|
|
|
201
209
|
}
|
|
202
210
|
// 为每个脚本构建模块路径
|
|
203
211
|
for (const script of userScripts) {
|
|
212
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
204
213
|
const asset = assets[script.id];
|
|
205
214
|
if (!asset)
|
|
206
215
|
continue;
|
|
@@ -242,6 +251,7 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
242
251
|
for (const scriptId of scriptIds) {
|
|
243
252
|
const asset = pcProject.assets[String(scriptId)];
|
|
244
253
|
if (asset && asset.type === 'script') {
|
|
254
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
245
255
|
const assetData = asset;
|
|
246
256
|
// 检查 preload 属性(默认为 true)
|
|
247
257
|
const preload = assetData.preload !== false;
|
|
@@ -258,6 +268,7 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
258
268
|
code,
|
|
259
269
|
name: assetData.name || `script_${scriptId}`,
|
|
260
270
|
});
|
|
271
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
261
272
|
}
|
|
262
273
|
catch (error) {
|
|
263
274
|
console.warn(`警告: 无法读取脚本文件: ${scriptPath}`);
|
|
@@ -273,6 +284,7 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
273
284
|
for (const scriptId of scriptIds) {
|
|
274
285
|
const asset = pcProject.assets[String(scriptId)];
|
|
275
286
|
if (asset && asset.type === 'script') {
|
|
287
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
276
288
|
const assetData = asset;
|
|
277
289
|
// 检查 preload 属性(默认为 true)
|
|
278
290
|
const preload = assetData.preload !== false;
|
|
@@ -289,6 +301,7 @@ async function collectUserScripts(projectConfig, projectDir) {
|
|
|
289
301
|
code,
|
|
290
302
|
name: assetData.name || `script_${scriptId}`,
|
|
291
303
|
});
|
|
304
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
292
305
|
}
|
|
293
306
|
catch (error) {
|
|
294
307
|
console.warn(`警告: 无法读取脚本文件: ${scriptPath}`);
|
|
@@ -331,19 +344,22 @@ async function copyTemplates(outputDir) {
|
|
|
331
344
|
/**
|
|
332
345
|
* 复制资源文件
|
|
333
346
|
*/
|
|
334
|
-
async function copyAssets(projectConfig, projectDir, outputDir,
|
|
335
|
-
|
|
347
|
+
async function copyAssets(projectConfig, projectDir, outputDir,
|
|
348
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
349
|
+
assetsOverride, skipScripts) {
|
|
336
350
|
const assetsOutputDir = path.join(outputDir, 'files');
|
|
337
351
|
await fs.mkdir(assetsOutputDir, { recursive: true });
|
|
338
|
-
const assets = assetsOverride ||
|
|
339
|
-
|
|
340
|
-
|
|
352
|
+
const assets = assetsOverride ||
|
|
353
|
+
(projectConfig.format === 'playcanvas'
|
|
354
|
+
? projectConfig.assets
|
|
355
|
+
: projectConfig.assets);
|
|
341
356
|
// 使用 Set 去重,避免重复复制同一个文件
|
|
342
357
|
const copiedUrls = new Set();
|
|
343
358
|
let copiedCount = 0;
|
|
344
359
|
let failedCount = 0;
|
|
345
360
|
// 遍历 assets
|
|
346
361
|
for (const [, asset] of Object.entries(assets)) {
|
|
362
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
347
363
|
const assetData = asset;
|
|
348
364
|
if (!assetData.file?.url || assetData.file.url.startsWith('data:')) {
|
|
349
365
|
continue;
|
|
@@ -369,6 +385,7 @@ async function copyAssets(projectConfig, projectDir, outputDir, assetsOverride,
|
|
|
369
385
|
// 标记为已复制
|
|
370
386
|
copiedUrls.add(assetData.file.url);
|
|
371
387
|
copiedCount++;
|
|
388
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
372
389
|
}
|
|
373
390
|
catch (error) {
|
|
374
391
|
// 资源文件可能不存在(可能是内联的)
|
|
@@ -381,6 +398,7 @@ async function copyAssets(projectConfig, projectDir, outputDir, assetsOverride,
|
|
|
381
398
|
* 收集项目中所有已注册的脚本名称
|
|
382
399
|
* 从脚本资产中提取 scriptName(ESM 脚本通过 static scriptName 定义)
|
|
383
400
|
*/
|
|
401
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
384
402
|
function collectRegisteredScriptNames(assets) {
|
|
385
403
|
const scriptNames = new Set();
|
|
386
404
|
for (const [, asset] of Object.entries(assets)) {
|
|
@@ -429,20 +447,27 @@ function collectRegisteredScriptNames(assets) {
|
|
|
429
447
|
* 验证并清理场景中的无效脚本引用
|
|
430
448
|
* 移除引用了不存在脚本的组件
|
|
431
449
|
*/
|
|
432
|
-
function validateAndCleanSceneScripts(
|
|
433
|
-
|
|
450
|
+
function validateAndCleanSceneScripts(
|
|
451
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
452
|
+
sceneData, registeredScripts,
|
|
453
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
454
|
+
_sceneName) {
|
|
434
455
|
const removedScripts = [];
|
|
435
456
|
if (!sceneData?.entities) {
|
|
436
457
|
return { cleaned: sceneData, removedScripts };
|
|
437
458
|
}
|
|
438
459
|
// 深拷贝场景数据以避免修改原始数据
|
|
439
460
|
const cleaned = JSON.parse(JSON.stringify(sceneData));
|
|
461
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
440
462
|
for (const [entityId, entity] of Object.entries(cleaned.entities)) {
|
|
441
463
|
const scriptComp = entity?.components?.script;
|
|
442
464
|
if (!scriptComp)
|
|
443
465
|
continue;
|
|
444
466
|
// 处理 ESM 格式:scripts 是对象 { scriptName: {...}, ... }
|
|
445
|
-
if (scriptComp.scripts &&
|
|
467
|
+
if (scriptComp.scripts &&
|
|
468
|
+
typeof scriptComp.scripts === 'object' &&
|
|
469
|
+
!Array.isArray(scriptComp.scripts)) {
|
|
470
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
446
471
|
const validScripts = {};
|
|
447
472
|
for (const [scriptName, scriptData] of Object.entries(scriptComp.scripts)) {
|
|
448
473
|
if (registeredScripts.has(scriptName)) {
|
|
@@ -463,6 +488,7 @@ function validateAndCleanSceneScripts(sceneData, registeredScripts, _sceneName /
|
|
|
463
488
|
}
|
|
464
489
|
// 处理 Classic 格式:scripts 是数组 [{ name: 'xxx' }, ...]
|
|
465
490
|
if (scriptComp.scripts && Array.isArray(scriptComp.scripts)) {
|
|
491
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
466
492
|
const validScripts = scriptComp.scripts.filter((s) => {
|
|
467
493
|
if (!s?.name)
|
|
468
494
|
return false;
|
|
@@ -498,11 +524,13 @@ outputDir, selectedScenes) {
|
|
|
498
524
|
? pcProject.scenes
|
|
499
525
|
: Object.entries(pcProject.scenes).map(([keyId, scene]) => {
|
|
500
526
|
// keyId 是场景文件名使用的 ID(如 "2388047")
|
|
527
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
501
528
|
return { ...scene, sceneFileId: keyId };
|
|
502
529
|
});
|
|
503
530
|
// 如果提供了 selectedScenes,只生成这些场景
|
|
504
531
|
if (selectedScenes && selectedScenes.length > 0) {
|
|
505
|
-
const selectedUrls = new Set(selectedScenes.map(s => s.url));
|
|
532
|
+
const selectedUrls = new Set(selectedScenes.map((s) => s.url));
|
|
533
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
506
534
|
scenes = scenes.filter((scene) => {
|
|
507
535
|
// 优先使用 sceneFileId(来自 scenes.json 的 key)
|
|
508
536
|
const sceneId = scene.sceneFileId || scene.id || scene.name || 'scene';
|
|
@@ -512,6 +540,7 @@ outputDir, selectedScenes) {
|
|
|
512
540
|
}
|
|
513
541
|
let totalRemoved = 0;
|
|
514
542
|
for (const scene of scenes) {
|
|
543
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
515
544
|
const sceneData = scene;
|
|
516
545
|
// 优先使用 sceneFileId(来自 scenes.json 的 key)
|
|
517
546
|
const sceneId = sceneData.sceneFileId || sceneData.id || sceneData.name || 'scene';
|
|
@@ -521,7 +550,7 @@ outputDir, selectedScenes) {
|
|
|
521
550
|
if (removedScripts.length > 0) {
|
|
522
551
|
totalRemoved += removedScripts.length;
|
|
523
552
|
console.warn(`\n⚠️ 场景 "${sceneData.name || sceneId}" 中发现 ${removedScripts.length} 个无效脚本引用,已移除:`);
|
|
524
|
-
removedScripts.slice(0, 10).forEach(s => console.warn(` - ${s}`));
|
|
553
|
+
removedScripts.slice(0, 10).forEach((s) => console.warn(` - ${s}`));
|
|
525
554
|
if (removedScripts.length > 10) {
|
|
526
555
|
console.warn(` ... 还有 ${removedScripts.length - 10} 个`);
|
|
527
556
|
}
|
|
@@ -540,7 +569,8 @@ outputDir, selectedScenes) {
|
|
|
540
569
|
let scenes = pcProject.scenes;
|
|
541
570
|
// 如果提供了 selectedScenes,只生成这些场景
|
|
542
571
|
if (selectedScenes && selectedScenes.length > 0) {
|
|
543
|
-
const selectedNames = new Set(selectedScenes.map(s => s.name));
|
|
572
|
+
const selectedNames = new Set(selectedScenes.map((s) => s.name));
|
|
573
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
544
574
|
scenes = scenes.filter((scene) => {
|
|
545
575
|
const sceneName = scene.name || scene.id || 'scene';
|
|
546
576
|
return selectedNames.has(sceneName);
|
|
@@ -548,6 +578,7 @@ outputDir, selectedScenes) {
|
|
|
548
578
|
}
|
|
549
579
|
let totalRemoved = 0;
|
|
550
580
|
for (const scene of scenes) {
|
|
581
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
551
582
|
const sceneData = scene;
|
|
552
583
|
const sceneId = sceneData.id || sceneData.name || 'scene';
|
|
553
584
|
const scenePath = path.join(outputDir, `${sceneId}.json`);
|
|
@@ -556,7 +587,7 @@ outputDir, selectedScenes) {
|
|
|
556
587
|
if (removedScripts.length > 0) {
|
|
557
588
|
totalRemoved += removedScripts.length;
|
|
558
589
|
console.warn(`\n⚠️ 场景 "${sceneData.name || sceneId}" 中发现 ${removedScripts.length} 个无效脚本引用,已移除:`);
|
|
559
|
-
removedScripts.slice(0, 10).forEach(s => console.warn(` - ${s}`));
|
|
590
|
+
removedScripts.slice(0, 10).forEach((s) => console.warn(` - ${s}`));
|
|
560
591
|
if (removedScripts.length > 10) {
|
|
561
592
|
console.warn(` ... 还有 ${removedScripts.length - 10} 个`);
|
|
562
593
|
}
|
|
@@ -569,52 +600,6 @@ outputDir, selectedScenes) {
|
|
|
569
600
|
}
|
|
570
601
|
}
|
|
571
602
|
}
|
|
572
|
-
/**
|
|
573
|
-
* 构建文件夹 ID -> 完整目录路径的映射
|
|
574
|
-
* PlayCraft Git 项目的 assets.json 中,资产的 path 字段是文件夹 ID 数组(如 [30097022, 30097024]),
|
|
575
|
-
* 需要通过递归遍历构建每个 folder ID 对应的完整路径(如 "LiteCreator/System")
|
|
576
|
-
*/
|
|
577
|
-
function buildFolderFullPathMap(assets) {
|
|
578
|
-
const folderMap = new Map();
|
|
579
|
-
const buildPath = (folderId, visited = new Set()) => {
|
|
580
|
-
if (visited.has(folderId))
|
|
581
|
-
return '';
|
|
582
|
-
if (folderMap.has(folderId))
|
|
583
|
-
return folderMap.get(folderId);
|
|
584
|
-
visited.add(folderId);
|
|
585
|
-
const folder = assets[folderId];
|
|
586
|
-
if (!folder || folder.type !== 'folder')
|
|
587
|
-
return '';
|
|
588
|
-
const pathIds = folder.path || [];
|
|
589
|
-
if (pathIds.length === 0) {
|
|
590
|
-
folderMap.set(folderId, folder.name);
|
|
591
|
-
return folder.name;
|
|
592
|
-
}
|
|
593
|
-
// 最后一个 ID 是直接父文件夹
|
|
594
|
-
const parentId = String(pathIds[pathIds.length - 1]);
|
|
595
|
-
const parentPath = buildPath(parentId, visited);
|
|
596
|
-
const fullPath = parentPath ? `${parentPath}/${folder.name}` : folder.name;
|
|
597
|
-
folderMap.set(folderId, fullPath);
|
|
598
|
-
return fullPath;
|
|
599
|
-
};
|
|
600
|
-
for (const [id, asset] of Object.entries(assets)) {
|
|
601
|
-
if (asset.type === 'folder') {
|
|
602
|
-
buildPath(id);
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
return folderMap;
|
|
606
|
-
}
|
|
607
|
-
/**
|
|
608
|
-
* 从资产的 path 数组(文件夹 ID 列表)重建 treePath
|
|
609
|
-
* path 数组中最后一个 ID 是直接父文件夹
|
|
610
|
-
*/
|
|
611
|
-
function resolveTreePathFromPathArray(pathIds, folderFullPathMap) {
|
|
612
|
-
if (!pathIds || !Array.isArray(pathIds) || pathIds.length === 0) {
|
|
613
|
-
return '';
|
|
614
|
-
}
|
|
615
|
-
const parentFolderId = String(pathIds[pathIds.length - 1]);
|
|
616
|
-
return folderFullPathMap.get(parentFolderId) || '';
|
|
617
|
-
}
|
|
618
603
|
/**
|
|
619
604
|
* 规范化资源 URL(补齐 file.url)
|
|
620
605
|
* 源码导出中的资源只有 file.filename,没有 file.url
|
|
@@ -629,13 +614,16 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
629
614
|
let normalizedCount = 0;
|
|
630
615
|
let notFoundCount = 0;
|
|
631
616
|
for (const [assetId, asset] of Object.entries(assets)) {
|
|
617
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
632
618
|
const assetData = asset;
|
|
633
619
|
// 跳过没有 file 的资源
|
|
634
620
|
if (!assetData.file) {
|
|
635
621
|
continue;
|
|
636
622
|
}
|
|
637
623
|
// 如果已有有效的本地 url(非 API URL),验证文件是否存在
|
|
638
|
-
if (assetData.file.url &&
|
|
624
|
+
if (assetData.file.url &&
|
|
625
|
+
!assetData.file.url.startsWith('/api/') &&
|
|
626
|
+
!assetData.file.url.startsWith('http')) {
|
|
639
627
|
// 已有有效的本地 url,验证文件存在性
|
|
640
628
|
try {
|
|
641
629
|
await fs.access(path.join(projectDir, assetData.file.url));
|
|
@@ -647,7 +635,8 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
647
635
|
}
|
|
648
636
|
}
|
|
649
637
|
// 如果 url 是 API URL(PlayCraft 格式残留),清除它
|
|
650
|
-
if (assetData.file.url &&
|
|
638
|
+
if (assetData.file.url &&
|
|
639
|
+
(assetData.file.url.startsWith('/api/') || assetData.file.url.startsWith('http'))) {
|
|
651
640
|
delete assetData.file.url;
|
|
652
641
|
}
|
|
653
642
|
// 如果已经有有效 url 了(由之前的 loader 设置的),跳过
|
|
@@ -690,6 +679,7 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
690
679
|
normalizedCount++;
|
|
691
680
|
found = true;
|
|
692
681
|
break;
|
|
682
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
693
683
|
}
|
|
694
684
|
catch (error) {
|
|
695
685
|
// 继续尝试下一个
|
|
@@ -704,12 +694,14 @@ async function normalizeAssetUrls(projectConfig, projectDir) {
|
|
|
704
694
|
/**
|
|
705
695
|
* 为脚本资产补齐 __game-scripts.js 信息
|
|
706
696
|
*/
|
|
697
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
707
698
|
async function patchScriptAssets(config, outputDir) {
|
|
708
699
|
if (!config?.assets) {
|
|
709
700
|
return;
|
|
710
701
|
}
|
|
711
702
|
const scriptIds = Array.isArray(config?.application_properties?.scripts)
|
|
712
|
-
?
|
|
703
|
+
? // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
704
|
+
config.application_properties.scripts.map((id) => String(id))
|
|
713
705
|
: [];
|
|
714
706
|
if (scriptIds.length === 0) {
|
|
715
707
|
return;
|
|
@@ -721,11 +713,13 @@ async function patchScriptAssets(config, outputDir) {
|
|
|
721
713
|
const buffer = await fs.readFile(gameScriptsPath);
|
|
722
714
|
stat = { size: buffer.byteLength };
|
|
723
715
|
hash = crypto.createHash('md5').update(buffer).digest('hex');
|
|
716
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
724
717
|
}
|
|
725
718
|
catch (error) {
|
|
726
719
|
// __game-scripts.js 可能不存在
|
|
727
720
|
}
|
|
728
721
|
for (const [assetId, asset] of Object.entries(config.assets)) {
|
|
722
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Preserve the existing dynamic project schema and bindings during extraction.
|
|
729
723
|
const assetData = asset;
|
|
730
724
|
if (!scriptIds.includes(String(assetId))) {
|
|
731
725
|
continue;
|
|
@@ -741,933 +735,3 @@ async function patchScriptAssets(config, outputDir) {
|
|
|
741
735
|
}
|
|
742
736
|
}
|
|
743
737
|
}
|
|
744
|
-
/**
|
|
745
|
-
* Analyze script file import dependencies and add missing dependency scripts to config.assets.
|
|
746
|
-
* This handles cases like: BoardRandomFiller.mjs imports ./BoardShapeGenerator.mjs,
|
|
747
|
-
* which is not directly referenced in the scene or templates.
|
|
748
|
-
*/
|
|
749
|
-
async function collectScriptImportDependencies(projectConfig, projectDir, importMap, configAssets) {
|
|
750
|
-
const assets = projectConfig.format === 'playcanvas'
|
|
751
|
-
? projectConfig.assets
|
|
752
|
-
: projectConfig.assets;
|
|
753
|
-
// Build folder ID -> name mapping
|
|
754
|
-
const folderMap = new Map();
|
|
755
|
-
for (const [assetId, asset] of Object.entries(assets)) {
|
|
756
|
-
if (asset.type === 'folder') {
|
|
757
|
-
folderMap.set(assetId, asset.name);
|
|
758
|
-
}
|
|
759
|
-
}
|
|
760
|
-
// Build reverse mapping: targetPath -> assetId (for ALL script assets, not just configAssets)
|
|
761
|
-
const targetPathToAssetId = new Map();
|
|
762
|
-
for (const [assetId, asset] of Object.entries(assets)) {
|
|
763
|
-
const assetData = asset;
|
|
764
|
-
if (assetData.type !== 'script')
|
|
765
|
-
continue;
|
|
766
|
-
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
767
|
-
const pathIds = assetData.path || [];
|
|
768
|
-
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
769
|
-
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
770
|
-
if (targetPath) {
|
|
771
|
-
targetPathToAssetId.set(targetPath.replace(/\\/g, '/'), assetId);
|
|
772
|
-
}
|
|
773
|
-
}
|
|
774
|
-
// Regex to extract import specifiers from script content
|
|
775
|
-
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
776
|
-
const importsMap = importMap.content.imports || {};
|
|
777
|
-
// Iteratively discover new script dependencies
|
|
778
|
-
const processedScripts = new Set();
|
|
779
|
-
let newDepsFound = true;
|
|
780
|
-
while (newDepsFound) {
|
|
781
|
-
newDepsFound = false;
|
|
782
|
-
const currentScriptIds = Object.keys(configAssets).filter(id => configAssets[id].type === 'script' && !processedScripts.has(id));
|
|
783
|
-
for (const scriptId of currentScriptIds) {
|
|
784
|
-
processedScripts.add(scriptId);
|
|
785
|
-
const assetData = assets[scriptId];
|
|
786
|
-
if (!assetData)
|
|
787
|
-
continue;
|
|
788
|
-
// Resolve source file path
|
|
789
|
-
const sourcePath = await resolveScriptSourcePath(assetData, scriptId, projectDir);
|
|
790
|
-
if (!sourcePath)
|
|
791
|
-
continue;
|
|
792
|
-
let content;
|
|
793
|
-
try {
|
|
794
|
-
content = await fs.readFile(sourcePath, 'utf-8');
|
|
795
|
-
}
|
|
796
|
-
catch {
|
|
797
|
-
continue;
|
|
798
|
-
}
|
|
799
|
-
// Get current script's target path for relative path resolution
|
|
800
|
-
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
801
|
-
const pathIds = assetData.path || [];
|
|
802
|
-
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
803
|
-
const scriptTargetPath = resolveTargetPathFromImportMap(folderPath, filename, importMap);
|
|
804
|
-
if (!scriptTargetPath)
|
|
805
|
-
continue;
|
|
806
|
-
const scriptDir = path.dirname(scriptTargetPath).replace(/\\/g, '/');
|
|
807
|
-
// Parse all import statements
|
|
808
|
-
let match;
|
|
809
|
-
importRegex.lastIndex = 0;
|
|
810
|
-
while ((match = importRegex.exec(content)) !== null) {
|
|
811
|
-
const modulePath = match[2] || match[5];
|
|
812
|
-
if (!modulePath)
|
|
813
|
-
continue;
|
|
814
|
-
let resolvedTargetPath = null;
|
|
815
|
-
if (modulePath.startsWith('./') || modulePath.startsWith('../')) {
|
|
816
|
-
// Relative import: resolve against script's directory
|
|
817
|
-
const joined = path.posix.join(scriptDir, modulePath);
|
|
818
|
-
resolvedTargetPath = path.posix.normalize(joined);
|
|
819
|
-
}
|
|
820
|
-
else if (!modulePath.startsWith('/') && !modulePath.startsWith('http')) {
|
|
821
|
-
// Import Map alias: resolve via import map
|
|
822
|
-
resolvedTargetPath = resolveModulePathViaImportMap(modulePath, importsMap);
|
|
823
|
-
}
|
|
824
|
-
if (!resolvedTargetPath)
|
|
825
|
-
continue;
|
|
826
|
-
resolvedTargetPath = resolvedTargetPath.replace(/\\/g, '/');
|
|
827
|
-
// Look up the asset by target path
|
|
828
|
-
const depAssetId = targetPathToAssetId.get(resolvedTargetPath);
|
|
829
|
-
if (depAssetId === undefined) {
|
|
830
|
-
console.warn(`Warning: resolvedTargetPath '${resolvedTargetPath}' not found in targetPathToAssetId`);
|
|
831
|
-
}
|
|
832
|
-
else if (!configAssets[depAssetId]) {
|
|
833
|
-
// Found a missing dependency — add it to configAssets
|
|
834
|
-
configAssets[depAssetId] = assets[depAssetId];
|
|
835
|
-
newDepsFound = true;
|
|
836
|
-
console.log(`📜 [ScriptDeps] ${assetData.name} imports ${assets[depAssetId].name} (${depAssetId}) — added to configAssets`);
|
|
837
|
-
}
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
/**
|
|
843
|
-
* Resolve the source file path for a script asset.
|
|
844
|
-
* @param assets - 可选,所有资产的 map,用于从 path 数组重建 treePath(PlayCraft Git 仓库场景)
|
|
845
|
-
*/
|
|
846
|
-
async function resolveScriptSourcePath(assetData, scriptId, projectDir, assets) {
|
|
847
|
-
if (assetData.file?.url) {
|
|
848
|
-
const fullPath = path.join(projectDir, assetData.file.url);
|
|
849
|
-
try {
|
|
850
|
-
await fs.access(fullPath);
|
|
851
|
-
return fullPath;
|
|
852
|
-
}
|
|
853
|
-
catch {
|
|
854
|
-
// file.url 指向的文件不存在,继续搜索
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
if (assetData.file?.filename) {
|
|
858
|
-
const filename = assetData.file.filename;
|
|
859
|
-
const revision = assetData.revision ?? 1;
|
|
860
|
-
const candidates = [
|
|
861
|
-
// PlayCanvas 标准结构
|
|
862
|
-
path.join(projectDir, 'files', 'assets', String(scriptId), String(revision), filename),
|
|
863
|
-
path.join(projectDir, 'files', 'assets', String(scriptId), '1', filename),
|
|
864
|
-
path.join(projectDir, 'files', 'assets', String(scriptId), filename),
|
|
865
|
-
];
|
|
866
|
-
// PlayCraft 结构:使用 treePath
|
|
867
|
-
if (assetData.treePath) {
|
|
868
|
-
candidates.push(path.join(projectDir, 'assets', assetData.treePath, filename));
|
|
869
|
-
candidates.push(path.join(projectDir, assetData.treePath, filename));
|
|
870
|
-
}
|
|
871
|
-
// PlayCraft Git 仓库:从 path 数组重建 treePath
|
|
872
|
-
if (assets && assetData.path && Array.isArray(assetData.path) && assetData.path.length > 0) {
|
|
873
|
-
const folderFullPathMap = buildFolderFullPathMap(assets);
|
|
874
|
-
const computedTreePath = resolveTreePathFromPathArray(assetData.path, folderFullPathMap);
|
|
875
|
-
if (computedTreePath) {
|
|
876
|
-
candidates.push(path.join(projectDir, 'assets', computedTreePath, filename));
|
|
877
|
-
candidates.push(path.join(projectDir, computedTreePath, filename));
|
|
878
|
-
}
|
|
879
|
-
}
|
|
880
|
-
// 最后尝试直接在 assets/ 根目录下查找
|
|
881
|
-
candidates.push(path.join(projectDir, 'assets', filename));
|
|
882
|
-
for (const candidate of candidates) {
|
|
883
|
-
try {
|
|
884
|
-
await fs.access(candidate);
|
|
885
|
-
return candidate;
|
|
886
|
-
}
|
|
887
|
-
catch {
|
|
888
|
-
// try next
|
|
889
|
-
}
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
return null;
|
|
893
|
-
}
|
|
894
|
-
/**
|
|
895
|
-
* 生成 ESM 模板文件
|
|
896
|
-
*/
|
|
897
|
-
async function generateESMTemplate(projectConfig, options, config) {
|
|
898
|
-
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
899
|
-
const outputDir = options.outputDir;
|
|
900
|
-
// 1. 生成 index.html (修复 Import Map 路径)
|
|
901
|
-
const htmlTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.html'), 'utf-8');
|
|
902
|
-
const projectName = projectConfig.format === 'playcanvas'
|
|
903
|
-
? projectConfig.project.name || 'PlayCanvas Project'
|
|
904
|
-
: projectConfig.manifest.name || 'PlayCanvas Project';
|
|
905
|
-
// 修复 Import Map 中的路径(将 ./Lib/ 改为 ./)
|
|
906
|
-
const fixedImportMap = fixImportMapPaths(options.importMap?.content || { imports: {} });
|
|
907
|
-
const importMapJson = JSON.stringify(fixedImportMap, null, 2);
|
|
908
|
-
const html = htmlTemplate
|
|
909
|
-
.replace(/\{\{PROJECT_NAME\}\}/g, projectName)
|
|
910
|
-
.replace(/\{\{IMPORT_MAP\}\}/g, importMapJson);
|
|
911
|
-
await fs.writeFile(path.join(outputDir, 'index.html'), html, 'utf-8');
|
|
912
|
-
// 2. 复制 PlayCanvas Engine(UMD 格式)和 ESM 包装器
|
|
913
|
-
const jsDir = path.join(outputDir, 'js');
|
|
914
|
-
await fs.mkdir(jsDir, { recursive: true });
|
|
915
|
-
// 复制 UMD 引擎
|
|
916
|
-
const engineSourcePath = path.join(templatesDir, 'playcanvas-stable.min.js');
|
|
917
|
-
const engineTargetPath = path.join(jsDir, 'playcanvas-engine-umd.js');
|
|
918
|
-
try {
|
|
919
|
-
await fs.copyFile(engineSourcePath, engineTargetPath);
|
|
920
|
-
console.log('[SourceBuilder] PlayCanvas Engine (UMD) 已复制');
|
|
921
|
-
}
|
|
922
|
-
catch (error) {
|
|
923
|
-
console.warn('[SourceBuilder] 警告: 无法复制 PlayCanvas Engine:', error);
|
|
924
|
-
}
|
|
925
|
-
// 复制 ESM 包装器
|
|
926
|
-
const wrapperSourcePath = path.join(templatesDir, 'playcanvas-esm-wrapper.mjs');
|
|
927
|
-
const wrapperTargetPath = path.join(jsDir, 'playcanvas-engine.mjs');
|
|
928
|
-
try {
|
|
929
|
-
await fs.copyFile(wrapperSourcePath, wrapperTargetPath);
|
|
930
|
-
console.log('[SourceBuilder] PlayCanvas ESM 包装器已复制');
|
|
931
|
-
}
|
|
932
|
-
catch (error) {
|
|
933
|
-
console.warn('[SourceBuilder] 警告: 无法复制 ESM 包装器:', error);
|
|
934
|
-
}
|
|
935
|
-
// 3. 分析脚本文件的 import 依赖,将缺失的依赖脚本添加到 config.assets
|
|
936
|
-
if (options.importMap) {
|
|
937
|
-
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
938
|
-
}
|
|
939
|
-
// 4. 收集用户脚本的导入路径(传入 config.assets 以包含 template 依赖 + import 依赖的脚本)
|
|
940
|
-
const scriptImportPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
941
|
-
// 5. 从 Import Map 中提取 gameRule 路径
|
|
942
|
-
let gameRulePath = '';
|
|
943
|
-
if (options.importMap?.content?.imports) {
|
|
944
|
-
const imports = options.importMap.content.imports;
|
|
945
|
-
if (imports['gameRule']) {
|
|
946
|
-
// 将 "./Generated/..." 格式转换为相对于 js/ 目录的路径 "../Generated/..."
|
|
947
|
-
gameRulePath = imports['gameRule'];
|
|
948
|
-
if (gameRulePath.startsWith('./')) {
|
|
949
|
-
gameRulePath = '..' + gameRulePath.slice(1); // "./" -> "../"
|
|
950
|
-
}
|
|
951
|
-
console.log(`[SourceBuilder] GameRule 路径: ${gameRulePath}`);
|
|
952
|
-
}
|
|
953
|
-
}
|
|
954
|
-
// 5.1 从场景 SystemManager 的 GameConfig.json 中收集 Rule 脚本
|
|
955
|
-
if (options.importMap && projectConfig.format === 'playcanvas') {
|
|
956
|
-
const allAssets = projectConfig.assets || {};
|
|
957
|
-
const pcScenes = projectConfig.scenes;
|
|
958
|
-
// Iterate over selected scenes (from config.scenes) and find the scene data
|
|
959
|
-
for (const sceneRef of (config.scenes || [])) {
|
|
960
|
-
// Extract scene file ID from url (e.g. "4577025.json" -> "4577025")
|
|
961
|
-
const sceneFileId = (sceneRef.url || '').replace(/\.json$/, '');
|
|
962
|
-
const sceneData = pcScenes?.[sceneFileId];
|
|
963
|
-
if (!sceneData?.entities)
|
|
964
|
-
continue;
|
|
965
|
-
// Find SystemManager entity
|
|
966
|
-
for (const [, entity] of Object.entries(sceneData.entities)) {
|
|
967
|
-
if (entity?.name !== 'SystemManager')
|
|
968
|
-
continue;
|
|
969
|
-
const smScript = entity.components?.script?.scripts?.systemManager;
|
|
970
|
-
if (!smScript?.attributes?.gameConfigAsset)
|
|
971
|
-
continue;
|
|
972
|
-
const jsonAssetId = String(smScript.attributes.gameConfigAsset);
|
|
973
|
-
const jsonAsset = allAssets[jsonAssetId];
|
|
974
|
-
if (!jsonAsset || jsonAsset.type !== 'json')
|
|
975
|
-
continue;
|
|
976
|
-
// Read the GameConfig JSON file
|
|
977
|
-
const jsonFilePath = await resolveScriptSourcePath(jsonAsset, jsonAssetId, options.projectDir, allAssets);
|
|
978
|
-
if (!jsonFilePath)
|
|
979
|
-
continue;
|
|
980
|
-
let gameConfig;
|
|
981
|
-
try {
|
|
982
|
-
const content = await fs.readFile(jsonFilePath, 'utf-8');
|
|
983
|
-
gameConfig = JSON.parse(content);
|
|
984
|
-
}
|
|
985
|
-
catch {
|
|
986
|
-
console.warn(`[SourceBuilder] 无法读取 GameConfig.json (${jsonAssetId})`);
|
|
987
|
-
continue;
|
|
988
|
-
}
|
|
989
|
-
const ruleName = gameConfig?.Gameplay?.Rule;
|
|
990
|
-
if (!ruleName)
|
|
991
|
-
continue;
|
|
992
|
-
// Resolve Rule script: look for a script asset named "{ruleName}.mjs"
|
|
993
|
-
const ruleFileName = `${ruleName}.mjs`;
|
|
994
|
-
let ruleAssetId = null;
|
|
995
|
-
for (const [assetId, asset] of Object.entries(allAssets)) {
|
|
996
|
-
if (asset.type === 'script' && (asset.file?.filename === ruleFileName || asset.name === ruleFileName)) {
|
|
997
|
-
ruleAssetId = assetId;
|
|
998
|
-
break;
|
|
999
|
-
}
|
|
1000
|
-
}
|
|
1001
|
-
if (ruleAssetId && !config.assets[ruleAssetId]) {
|
|
1002
|
-
config.assets[ruleAssetId] = allAssets[ruleAssetId];
|
|
1003
|
-
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — added to configAssets`);
|
|
1004
|
-
// Also collect its import dependencies
|
|
1005
|
-
if (options.importMap) {
|
|
1006
|
-
await collectScriptImportDependencies(projectConfig, options.projectDir, options.importMap, config.assets);
|
|
1007
|
-
}
|
|
1008
|
-
// Rebuild script import paths to include the new Rule script
|
|
1009
|
-
const newPaths = await collectESMScriptImports(projectConfig, options, config.assets);
|
|
1010
|
-
for (const p of newPaths) {
|
|
1011
|
-
if (!scriptImportPaths.includes(p)) {
|
|
1012
|
-
scriptImportPaths.push(p);
|
|
1013
|
-
}
|
|
1014
|
-
}
|
|
1015
|
-
}
|
|
1016
|
-
else if (ruleAssetId) {
|
|
1017
|
-
console.log(`📜 [GameConfig] Rule "${ruleName}" → 资源 ${ruleAssetId} — already in configAssets`);
|
|
1018
|
-
}
|
|
1019
|
-
else {
|
|
1020
|
-
console.warn(`⚠️ [GameConfig] Rule "${ruleName}" 对应的脚本 ${ruleFileName} 未找到`);
|
|
1021
|
-
}
|
|
1022
|
-
// Use the rule path from 5.1 if Import Map didn't provide a gameRule mapping (step 5)
|
|
1023
|
-
if (ruleAssetId && !gameRulePath) {
|
|
1024
|
-
const ruleAsset = allAssets[ruleAssetId];
|
|
1025
|
-
// Build folder map for path resolution
|
|
1026
|
-
const folderMap = new Map();
|
|
1027
|
-
for (const [aid, a] of Object.entries(allAssets)) {
|
|
1028
|
-
if (a.type === 'folder')
|
|
1029
|
-
folderMap.set(aid, a.name);
|
|
1030
|
-
}
|
|
1031
|
-
const ruleFilename = ruleAsset.file?.filename || ruleAsset.name + '.mjs';
|
|
1032
|
-
const ruleFolderPath = buildScriptFolderPath(ruleAsset.path || [], folderMap);
|
|
1033
|
-
const targetPath = resolveTargetPathFromImportMap(ruleFolderPath, ruleFilename, options.importMap);
|
|
1034
|
-
if (targetPath) {
|
|
1035
|
-
gameRulePath = '../' + targetPath;
|
|
1036
|
-
console.log(`📜 [GameConfig] 使用 5.1 收集的 Rule 路径: ${gameRulePath}`);
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
}
|
|
1042
|
-
// 6. 生成 js/index.mjs(包含脚本导入),使用过滤后的 config.scenes
|
|
1043
|
-
await generateESMEntry(projectConfig, outputDir, scriptImportPaths, config.scenes, gameRulePath);
|
|
1044
|
-
// 7. 在 ESM 模式下,复制用户脚本为独立文件,并更新 config.assets 中的 URL
|
|
1045
|
-
if (options.importMap) {
|
|
1046
|
-
const scriptUrlMap = await copyUserScriptsForESM(projectConfig, options.projectDir, outputDir, options.importMap, config.assets);
|
|
1047
|
-
console.log('[SourceBuilder] 用户脚本已复制为独立 ESM 模块');
|
|
1048
|
-
// 更新 config.assets 中脚本的 URL
|
|
1049
|
-
if (scriptUrlMap.size > 0 && config.assets) {
|
|
1050
|
-
for (const [scriptId, newUrl] of scriptUrlMap) {
|
|
1051
|
-
if (config.assets[scriptId] && config.assets[scriptId].file) {
|
|
1052
|
-
config.assets[scriptId].file.url = newUrl;
|
|
1053
|
-
}
|
|
1054
|
-
}
|
|
1055
|
-
// 重新写入 config.json
|
|
1056
|
-
await fs.writeFile(path.join(outputDir, 'config.json'), JSON.stringify(config, null, 2), 'utf-8');
|
|
1057
|
-
console.log(`[SourceBuilder] 更新了 ${scriptUrlMap.size} 个脚本的 URL`);
|
|
1058
|
-
}
|
|
1059
|
-
// 8. 复制 Import Map 中引用的第三方库文件
|
|
1060
|
-
await copyImportMapLibraries(projectConfig, options.projectDir, outputDir, options.importMap);
|
|
1061
|
-
}
|
|
1062
|
-
// 9. 复制其他必要的模板文件
|
|
1063
|
-
const templateFiles = [
|
|
1064
|
-
'__start__.js', // 可能不需要了,但先保留
|
|
1065
|
-
'__modules__.js',
|
|
1066
|
-
'__loading__.js',
|
|
1067
|
-
'styles.css',
|
|
1068
|
-
'manifest.json',
|
|
1069
|
-
];
|
|
1070
|
-
for (const file of templateFiles) {
|
|
1071
|
-
const sourcePath = path.join(templatesDir, file);
|
|
1072
|
-
const targetPath = path.join(outputDir, file);
|
|
1073
|
-
try {
|
|
1074
|
-
await fs.copyFile(sourcePath, targetPath);
|
|
1075
|
-
}
|
|
1076
|
-
catch (error) {
|
|
1077
|
-
// 某些文件可能不存在,忽略
|
|
1078
|
-
}
|
|
1079
|
-
}
|
|
1080
|
-
}
|
|
1081
|
-
/**
|
|
1082
|
-
* 修复 Import Map 中的路径
|
|
1083
|
-
* 将 ./Lib/xxx.mjs 等错误路径修复为正确的相对路径
|
|
1084
|
-
* 并添加必要的模块映射(如 playcanvas)
|
|
1085
|
-
*/
|
|
1086
|
-
function fixImportMapPaths(importMap) {
|
|
1087
|
-
const fixedImports = {};
|
|
1088
|
-
// 添加 playcanvas 引擎映射(脚本中使用 import from 'playcanvas')
|
|
1089
|
-
fixedImports['playcanvas'] = './js/playcanvas-engine.mjs';
|
|
1090
|
-
for (const [key, value] of Object.entries(importMap.imports || {})) {
|
|
1091
|
-
// 修复 ./Lib/ 路径(通常第三方库文件会被复制到根目录)
|
|
1092
|
-
let fixedValue = value;
|
|
1093
|
-
if (value.startsWith('./Lib/')) {
|
|
1094
|
-
// 将 ./Lib/xxx.mjs 改为 ./xxx.mjs
|
|
1095
|
-
fixedValue = './' + value.slice(6);
|
|
1096
|
-
}
|
|
1097
|
-
fixedImports[key] = fixedValue;
|
|
1098
|
-
}
|
|
1099
|
-
return { imports: fixedImports };
|
|
1100
|
-
}
|
|
1101
|
-
/**
|
|
1102
|
-
* 收集 ESM 脚本的导入路径
|
|
1103
|
-
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
1104
|
-
*/
|
|
1105
|
-
async function collectESMScriptImports(projectConfig, options, configAssets) {
|
|
1106
|
-
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
1107
|
-
let assets;
|
|
1108
|
-
if (projectConfig.format === 'playcanvas') {
|
|
1109
|
-
assets = projectConfig.assets;
|
|
1110
|
-
}
|
|
1111
|
-
else {
|
|
1112
|
-
assets = projectConfig.assets;
|
|
1113
|
-
}
|
|
1114
|
-
// 收集所有需要导入的脚本 ID:
|
|
1115
|
-
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
1116
|
-
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
1117
|
-
const scriptIdsToImport = new Set();
|
|
1118
|
-
if (configAssets) {
|
|
1119
|
-
console.log(`📜 [DEBUG-ESMImports] 使用 configAssets 收集脚本, configAssets 总数: ${Object.keys(configAssets).length}`);
|
|
1120
|
-
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
1121
|
-
if (asset.type === 'script') {
|
|
1122
|
-
scriptIdsToImport.add(assetId);
|
|
1123
|
-
}
|
|
1124
|
-
}
|
|
1125
|
-
console.log(`[ESMImports] 从 configAssets 收集到 ${scriptIdsToImport.size} 个脚本`);
|
|
1126
|
-
}
|
|
1127
|
-
else {
|
|
1128
|
-
console.log(`[ESMImports] configAssets 未传入, 回退到 settings.scripts`);
|
|
1129
|
-
// Fallback: use settings.scripts
|
|
1130
|
-
let scriptIds;
|
|
1131
|
-
if (projectConfig.format === 'playcanvas') {
|
|
1132
|
-
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
1133
|
-
}
|
|
1134
|
-
else {
|
|
1135
|
-
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
1136
|
-
}
|
|
1137
|
-
for (const id of scriptIds) {
|
|
1138
|
-
scriptIdsToImport.add(String(id));
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
const importPaths = [];
|
|
1142
|
-
// 构建文件夹 ID 到名称的映射
|
|
1143
|
-
const folderMap = new Map();
|
|
1144
|
-
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1145
|
-
const assetData = asset;
|
|
1146
|
-
if (assetData.type === 'folder') {
|
|
1147
|
-
folderMap.set(assetId, assetData.name);
|
|
1148
|
-
}
|
|
1149
|
-
}
|
|
1150
|
-
// 遍历每个脚本,构建导入路径
|
|
1151
|
-
for (const scriptId of scriptIdsToImport) {
|
|
1152
|
-
const asset = assets[String(scriptId)];
|
|
1153
|
-
if (!asset || asset.type !== 'script')
|
|
1154
|
-
continue;
|
|
1155
|
-
const assetData = asset;
|
|
1156
|
-
// 获取正确的文件名(带扩展名)
|
|
1157
|
-
const filename = assetData.file?.filename || assetData.name + '.mjs';
|
|
1158
|
-
// 获取脚本的文件夹路径
|
|
1159
|
-
const pathIds = assetData.path || [];
|
|
1160
|
-
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
1161
|
-
// 根据 import map 确定目标路径
|
|
1162
|
-
if (options.importMap) {
|
|
1163
|
-
const targetPath = resolveTargetPathFromImportMap(folderPath, filename, options.importMap);
|
|
1164
|
-
console.log(`[ESM Imports] ${assetData.name}: folderPath=${folderPath}, filename=${filename}, targetPath=${targetPath}`);
|
|
1165
|
-
if (targetPath) {
|
|
1166
|
-
// 生成相对于 js/ 目录的导入路径
|
|
1167
|
-
// 入口文件在 js/index.mjs,脚本在根目录,所以需要 ../
|
|
1168
|
-
importPaths.push('../' + targetPath);
|
|
1169
|
-
}
|
|
1170
|
-
}
|
|
1171
|
-
}
|
|
1172
|
-
return importPaths;
|
|
1173
|
-
}
|
|
1174
|
-
/**
|
|
1175
|
-
* 生成 ESM 入口文件 js/index.mjs
|
|
1176
|
-
*/
|
|
1177
|
-
async function generateESMEntry(projectConfig, outputDir, scriptImportPaths = [], configScenes, gameRulePath = '') {
|
|
1178
|
-
const templatesDir = path.resolve(__dirname, '../../templates');
|
|
1179
|
-
const esmTemplate = await fs.readFile(path.join(templatesDir, 'index.esm.mjs'), 'utf-8');
|
|
1180
|
-
// 获取项目设置
|
|
1181
|
-
let settings;
|
|
1182
|
-
let scripts = [];
|
|
1183
|
-
if (projectConfig.format === 'playcanvas') {
|
|
1184
|
-
const pcProject = projectConfig;
|
|
1185
|
-
settings = pcProject.project.settings || {};
|
|
1186
|
-
scripts = settings.scripts || [];
|
|
1187
|
-
}
|
|
1188
|
-
else {
|
|
1189
|
-
const pcProject = projectConfig;
|
|
1190
|
-
settings = pcProject.manifest.settings || {};
|
|
1191
|
-
scripts = settings.scripts || [];
|
|
1192
|
-
}
|
|
1193
|
-
// 确定场景路径(优先使用传入的 configScenes,否则从原始 projectConfig 获取)
|
|
1194
|
-
let scenePath = '';
|
|
1195
|
-
if (configScenes && configScenes.length > 0) {
|
|
1196
|
-
// 使用过滤后的配置场景
|
|
1197
|
-
scenePath = configScenes[0].url;
|
|
1198
|
-
}
|
|
1199
|
-
else if (projectConfig.format === 'playcanvas') {
|
|
1200
|
-
const pcProject = projectConfig;
|
|
1201
|
-
if (pcProject.scenes) {
|
|
1202
|
-
const scenes = Array.isArray(pcProject.scenes)
|
|
1203
|
-
? pcProject.scenes
|
|
1204
|
-
: Object.values(pcProject.scenes);
|
|
1205
|
-
if (scenes.length > 0) {
|
|
1206
|
-
const firstScene = scenes[0];
|
|
1207
|
-
scenePath = firstScene.url || firstScene.file || `${firstScene.id || 'scene'}.json`;
|
|
1208
|
-
}
|
|
1209
|
-
}
|
|
1210
|
-
}
|
|
1211
|
-
else {
|
|
1212
|
-
const pcProject = projectConfig;
|
|
1213
|
-
if (pcProject.scenes && pcProject.scenes.length > 0) {
|
|
1214
|
-
const firstScene = pcProject.scenes[0];
|
|
1215
|
-
scenePath = firstScene.url || `${firstScene.id || 'scene'}.json`;
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
// 构建 CONTEXT_OPTIONS
|
|
1219
|
-
const contextOptions = {
|
|
1220
|
-
antialias: settings.antiAlias ?? true,
|
|
1221
|
-
alpha: false,
|
|
1222
|
-
preserveDrawingBuffer: settings.preserveDrawingBuffer ?? false,
|
|
1223
|
-
deviceTypes: ['webgl2', 'webgl1'],
|
|
1224
|
-
powerPreference: settings.powerPreference || 'high-performance'
|
|
1225
|
-
};
|
|
1226
|
-
// 构建 INPUT_SETTINGS
|
|
1227
|
-
const inputSettings = {
|
|
1228
|
-
useKeyboard: settings.useKeyboard ?? true,
|
|
1229
|
-
useMouse: settings.useMouse ?? true,
|
|
1230
|
-
useGamepads: settings.useGamepads ?? false,
|
|
1231
|
-
useTouch: settings.useTouch ?? true
|
|
1232
|
-
};
|
|
1233
|
-
// 提取预加载模块(WASM 等)
|
|
1234
|
-
const preloadModules = [];
|
|
1235
|
-
// TODO: 从 assets 中提取 WASM 模块
|
|
1236
|
-
// 生成脚本导入路径数组(延迟加载)
|
|
1237
|
-
console.log(`[ESMEntry] 生成 ${scriptImportPaths.length} 个脚本导入路径`);
|
|
1238
|
-
// 替换模板占位符
|
|
1239
|
-
const entry = esmTemplate
|
|
1240
|
-
.replace(/\{\{SCRIPT_IMPORT_PATHS\}\}/g, JSON.stringify(scriptImportPaths))
|
|
1241
|
-
.replace(/\{\{GAME_RULE_PATH\}\}/g, gameRulePath)
|
|
1242
|
-
.replace(/\{\{ASSET_PREFIX\}\}/g, '')
|
|
1243
|
-
.replace(/\{\{SCRIPT_PREFIX\}\}/g, '')
|
|
1244
|
-
.replace(/\{\{SCENE_PATH\}\}/g, scenePath)
|
|
1245
|
-
.replace(/\{\{CONTEXT_OPTIONS\}\}/g, JSON.stringify(contextOptions))
|
|
1246
|
-
.replace(/\{\{SCRIPTS\}\}/g, JSON.stringify(scripts))
|
|
1247
|
-
.replace(/\{\{INPUT_SETTINGS\}\}/g, JSON.stringify(inputSettings))
|
|
1248
|
-
.replace(/\{\{PRELOAD_MODULES\}\}/g, JSON.stringify(preloadModules))
|
|
1249
|
-
.replace(/\{\{LEGACY_SCRIPTS\}\}/g, String(settings.useLegacyScripts ?? false));
|
|
1250
|
-
// 写入 js/index.mjs
|
|
1251
|
-
const jsDir = path.join(outputDir, 'js');
|
|
1252
|
-
await fs.mkdir(jsDir, { recursive: true });
|
|
1253
|
-
await fs.writeFile(path.join(jsDir, 'index.mjs'), entry, 'utf-8');
|
|
1254
|
-
}
|
|
1255
|
-
/**
|
|
1256
|
-
* 在 ESM 模式下复制用户脚本为独立文件
|
|
1257
|
-
* @param configAssets - generateConfig 过滤后的 config.assets,包含 template 依赖的脚本
|
|
1258
|
-
* @returns 脚本ID到新URL的映射
|
|
1259
|
-
*/
|
|
1260
|
-
async function copyUserScriptsForESM(projectConfig, projectDir, outputDir, importMap, configAssets) {
|
|
1261
|
-
const scriptUrlMap = new Map();
|
|
1262
|
-
// 获取资产(支持 PlayCanvas 和 PlayCraft 两种格式)
|
|
1263
|
-
let assets;
|
|
1264
|
-
if (projectConfig.format === 'playcanvas') {
|
|
1265
|
-
assets = projectConfig.assets;
|
|
1266
|
-
}
|
|
1267
|
-
else {
|
|
1268
|
-
assets = projectConfig.assets;
|
|
1269
|
-
}
|
|
1270
|
-
// 收集所有需要复制的脚本 ID:
|
|
1271
|
-
// 1. config.assets 中的 script 类型资产(已包含场景依赖 + template 依赖的脚本)
|
|
1272
|
-
// 2. 回退到 settings.scripts(当没有 configAssets 时)
|
|
1273
|
-
const scriptIdsToProcess = new Set();
|
|
1274
|
-
if (configAssets) {
|
|
1275
|
-
for (const [assetId, asset] of Object.entries(configAssets)) {
|
|
1276
|
-
if (asset.type === 'script') {
|
|
1277
|
-
scriptIdsToProcess.add(assetId);
|
|
1278
|
-
}
|
|
1279
|
-
}
|
|
1280
|
-
}
|
|
1281
|
-
else {
|
|
1282
|
-
let scriptIds;
|
|
1283
|
-
if (projectConfig.format === 'playcanvas') {
|
|
1284
|
-
scriptIds = projectConfig.project.settings?.scripts || [];
|
|
1285
|
-
}
|
|
1286
|
-
else {
|
|
1287
|
-
scriptIds = projectConfig.manifest.settings?.scripts || [];
|
|
1288
|
-
}
|
|
1289
|
-
for (const id of scriptIds) {
|
|
1290
|
-
scriptIdsToProcess.add(String(id));
|
|
1291
|
-
}
|
|
1292
|
-
}
|
|
1293
|
-
console.log(`[copyUserScriptsForESM] 复制 ${scriptIdsToProcess.size} 个脚本`);
|
|
1294
|
-
// 构建文件夹 ID 到名称的映射
|
|
1295
|
-
const folderMap = new Map();
|
|
1296
|
-
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1297
|
-
const assetData = asset;
|
|
1298
|
-
if (assetData.type === 'folder') {
|
|
1299
|
-
folderMap.set(assetId, assetData.name);
|
|
1300
|
-
}
|
|
1301
|
-
}
|
|
1302
|
-
// 遍历每个脚本
|
|
1303
|
-
for (const scriptId of scriptIdsToProcess) {
|
|
1304
|
-
const asset = assets[String(scriptId)];
|
|
1305
|
-
if (!asset || asset.type !== 'script')
|
|
1306
|
-
continue;
|
|
1307
|
-
const assetData = asset;
|
|
1308
|
-
// 获取脚本源文件路径(使用统一的解析函数,支持 PlayCraft Git 仓库结构)
|
|
1309
|
-
const sourcePath = await resolveScriptSourcePath(assetData, String(scriptId), projectDir, assets);
|
|
1310
|
-
if (!sourcePath) {
|
|
1311
|
-
console.warn(`[ESM] 无法找到脚本 ${assetData.name} 的源文件,跳过`);
|
|
1312
|
-
continue;
|
|
1313
|
-
}
|
|
1314
|
-
// 获取脚本的文件夹路径
|
|
1315
|
-
const pathIds = assetData.path || [];
|
|
1316
|
-
const folderPath = buildScriptFolderPath(pathIds, folderMap);
|
|
1317
|
-
// 获取正确的文件名(带扩展名)
|
|
1318
|
-
const scriptFilename = assetData.file?.filename || assetData.name + '.mjs';
|
|
1319
|
-
// 根据 import map 确定目标路径
|
|
1320
|
-
const targetPath = resolveTargetPathFromImportMap(folderPath, scriptFilename, importMap);
|
|
1321
|
-
if (!targetPath) {
|
|
1322
|
-
console.warn(`[ESM] 无法为脚本 ${assetData.name} 确定目标路径,跳过`);
|
|
1323
|
-
continue;
|
|
1324
|
-
}
|
|
1325
|
-
console.log(`[ESM] 脚本 ${assetData.name}: folderPath=${folderPath}, targetPath=${targetPath}`);
|
|
1326
|
-
// 复制文件(并重写 import 语句中的 Import Map 别名)
|
|
1327
|
-
const outputPath = path.join(outputDir, targetPath);
|
|
1328
|
-
try {
|
|
1329
|
-
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1330
|
-
// 读取源文件
|
|
1331
|
-
let content = await fs.readFile(sourcePath, 'utf-8');
|
|
1332
|
-
// 修复已知的代码问题(如未定义变量的错误日志)
|
|
1333
|
-
console.log(`[copyUserScriptsForESM] 处理脚本: ${assetData.name}`);
|
|
1334
|
-
content = fixKnownCodeIssues(content, assetData.name);
|
|
1335
|
-
// 重写 import 语句,将 Import Map 别名转换为相对路径
|
|
1336
|
-
content = rewriteImportsWithImportMap(content, targetPath, importMap);
|
|
1337
|
-
// 重写 pc.app 访问,确保在 ESM 模式下能正确获取 app 实例
|
|
1338
|
-
content = rewritePcAppAccess(content);
|
|
1339
|
-
// 写入目标文件
|
|
1340
|
-
await fs.writeFile(outputPath, content, 'utf-8');
|
|
1341
|
-
// 记录脚本ID到新URL的映射
|
|
1342
|
-
scriptUrlMap.set(String(scriptId), targetPath);
|
|
1343
|
-
}
|
|
1344
|
-
catch (error) {
|
|
1345
|
-
console.warn(`[ESM] 无法复制脚本 ${assetData.name}:`, error);
|
|
1346
|
-
}
|
|
1347
|
-
}
|
|
1348
|
-
return scriptUrlMap;
|
|
1349
|
-
}
|
|
1350
|
-
/**
|
|
1351
|
-
* 重写脚本内容中的 import 语句
|
|
1352
|
-
* 将 Import Map 别名转换为相对于脚本位置的相对路径
|
|
1353
|
-
*/
|
|
1354
|
-
function rewriteImportsWithImportMap(content, scriptTargetPath, importMap) {
|
|
1355
|
-
const imports = importMap.content.imports || {};
|
|
1356
|
-
// 获取脚本所在目录(相对于输出根目录)
|
|
1357
|
-
const scriptDir = path.dirname(scriptTargetPath);
|
|
1358
|
-
// 正则匹配 import 语句中的模块说明符
|
|
1359
|
-
// 匹配: import ... from 'xxx' 或 import ... from "xxx" 或 import('xxx') 等
|
|
1360
|
-
const importRegex = /(from\s+['"])([^'"]+)(['"])|(\bimport\s*\(\s*['"])([^'"]+)(['"]\s*\))/g;
|
|
1361
|
-
return content.replace(importRegex, (match, p1, p2, p3, p4, p5, p6) => {
|
|
1362
|
-
const prefix = p1 || p4;
|
|
1363
|
-
const modulePath = p2 || p5;
|
|
1364
|
-
const suffix = p3 || p6;
|
|
1365
|
-
// 如果已经是相对路径(./ 或 ../)或绝对路径(/ 或 http),不处理
|
|
1366
|
-
if (modulePath.startsWith('./') || modulePath.startsWith('../') ||
|
|
1367
|
-
modulePath.startsWith('/') || modulePath.startsWith('http://') ||
|
|
1368
|
-
modulePath.startsWith('https://')) {
|
|
1369
|
-
return match;
|
|
1370
|
-
}
|
|
1371
|
-
// 尝试通过 Import Map 解析模块路径
|
|
1372
|
-
const resolvedPath = resolveModulePathViaImportMap(modulePath, imports);
|
|
1373
|
-
if (resolvedPath) {
|
|
1374
|
-
// 计算从脚本位置到解析后路径的相对路径
|
|
1375
|
-
const relativePath = calculateRelativePath(scriptDir, resolvedPath);
|
|
1376
|
-
return prefix + relativePath + suffix;
|
|
1377
|
-
}
|
|
1378
|
-
// 如果无法解析,保持原样
|
|
1379
|
-
return match;
|
|
1380
|
-
});
|
|
1381
|
-
}
|
|
1382
|
-
/**
|
|
1383
|
-
* 通过 Import Map 解析模块路径
|
|
1384
|
-
* 注意:需要应用与 fixImportMapPaths 相同的路径修复逻辑
|
|
1385
|
-
*/
|
|
1386
|
-
function resolveModulePathViaImportMap(modulePath, imports) {
|
|
1387
|
-
// 1. 精确匹配
|
|
1388
|
-
if (imports[modulePath]) {
|
|
1389
|
-
let resolved = imports[modulePath];
|
|
1390
|
-
// 去掉开头的 ./
|
|
1391
|
-
if (resolved.startsWith('./')) {
|
|
1392
|
-
resolved = resolved.slice(2);
|
|
1393
|
-
}
|
|
1394
|
-
// 修复 Lib/ 路径(与 fixImportMapPaths 保持一致)
|
|
1395
|
-
// 将 Lib/xxx.mjs 改为 xxx.mjs(因为这些文件会被复制到根目录)
|
|
1396
|
-
if (resolved.startsWith('Lib/')) {
|
|
1397
|
-
resolved = resolved.slice(4);
|
|
1398
|
-
}
|
|
1399
|
-
return resolved;
|
|
1400
|
-
}
|
|
1401
|
-
// 2. 前缀匹配(目录别名)
|
|
1402
|
-
for (const [prefix, target] of Object.entries(imports)) {
|
|
1403
|
-
if (prefix.endsWith('/') && modulePath.startsWith(prefix)) {
|
|
1404
|
-
const remainder = modulePath.slice(prefix.length);
|
|
1405
|
-
let targetBase = target;
|
|
1406
|
-
// 去掉开头的 ./
|
|
1407
|
-
if (targetBase.startsWith('./')) {
|
|
1408
|
-
targetBase = targetBase.slice(2);
|
|
1409
|
-
}
|
|
1410
|
-
// 修复 Lib/ 路径
|
|
1411
|
-
if (targetBase.startsWith('Lib/')) {
|
|
1412
|
-
targetBase = targetBase.slice(4);
|
|
1413
|
-
}
|
|
1414
|
-
// 去掉结尾的 /
|
|
1415
|
-
if (targetBase.endsWith('/')) {
|
|
1416
|
-
targetBase = targetBase.slice(0, -1);
|
|
1417
|
-
}
|
|
1418
|
-
return targetBase + '/' + remainder;
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
return null;
|
|
1422
|
-
}
|
|
1423
|
-
/**
|
|
1424
|
-
* 计算从源目录到目标路径的相对路径
|
|
1425
|
-
*/
|
|
1426
|
-
function calculateRelativePath(fromDir, toPath) {
|
|
1427
|
-
// 将路径统一使用正斜杠
|
|
1428
|
-
fromDir = fromDir.replace(/\\/g, '/');
|
|
1429
|
-
toPath = toPath.replace(/\\/g, '/');
|
|
1430
|
-
// 分割路径
|
|
1431
|
-
const fromParts = fromDir ? fromDir.split('/').filter(p => p) : [];
|
|
1432
|
-
const toParts = toPath.split('/').filter(p => p);
|
|
1433
|
-
// 找到共同前缀
|
|
1434
|
-
let commonLength = 0;
|
|
1435
|
-
for (let i = 0; i < Math.min(fromParts.length, toParts.length); i++) {
|
|
1436
|
-
if (fromParts[i] === toParts[i]) {
|
|
1437
|
-
commonLength++;
|
|
1438
|
-
}
|
|
1439
|
-
else {
|
|
1440
|
-
break;
|
|
1441
|
-
}
|
|
1442
|
-
}
|
|
1443
|
-
// 计算需要向上走多少级
|
|
1444
|
-
const upCount = fromParts.length - commonLength;
|
|
1445
|
-
// 构建相对路径
|
|
1446
|
-
const upPath = '../'.repeat(upCount);
|
|
1447
|
-
const downPath = toParts.slice(commonLength).join('/');
|
|
1448
|
-
const result = upPath + downPath;
|
|
1449
|
-
// 如果结果为空或不以 ./ 或 ../ 开头,添加 ./
|
|
1450
|
-
if (!result || (!result.startsWith('./') && !result.startsWith('../'))) {
|
|
1451
|
-
return './' + result;
|
|
1452
|
-
}
|
|
1453
|
-
return result;
|
|
1454
|
-
}
|
|
1455
|
-
/**
|
|
1456
|
-
* 修复已知的代码问题
|
|
1457
|
-
* 这些是项目源代码中的 bug,需要在打包时自动修复
|
|
1458
|
-
*/
|
|
1459
|
-
function fixKnownCodeIssues(content, scriptName) {
|
|
1460
|
-
let modified = content;
|
|
1461
|
-
let fixCount = 0;
|
|
1462
|
-
// 修复 1: GameplaySystem.mjs 中 ruleName 未定义的问题
|
|
1463
|
-
// 原代码: console.error(`[LC] Load game rule '${ruleName}' failed`);
|
|
1464
|
-
// 问题: ruleName 变量在上面被注释掉了,但错误日志仍然引用它
|
|
1465
|
-
if (content.includes("console.error(`[LC] Load game rule '${ruleName}' failed`)")) {
|
|
1466
|
-
modified = modified.replace("console.error(`[LC] Load game rule '${ruleName}' failed`)", "console.error(`[LC] Load game rule failed - GameplaySystem.gameRule is null`)");
|
|
1467
|
-
fixCount++;
|
|
1468
|
-
console.log(`[SourceBuilder] 修复 ${scriptName}: ruleName 未定义问题`);
|
|
1469
|
-
}
|
|
1470
|
-
// 修复 2: AimAdjustmentBar.mjs 中 sprite 可能为 null 的问题
|
|
1471
|
-
// 原代码: const frameKey = this.wheel.element.sprite.frameKeys[frameNum];
|
|
1472
|
-
// 问题: sprite 资源可能还没加载完成或引用丢失
|
|
1473
|
-
if (content.includes('this.wheel.element.sprite.frameKeys[frameNum]')) {
|
|
1474
|
-
// 直接替换整行
|
|
1475
|
-
const oldLine = 'const frameKey = this.wheel.element.sprite.frameKeys[frameNum];';
|
|
1476
|
-
const newLines = `const sprite = this.wheel.element.sprite;
|
|
1477
|
-
if (!sprite || !sprite.frameKeys || !sprite.atlas) {
|
|
1478
|
-
console.warn('[AimAdjustmentBar] Sprite not ready, skipping wheel initialization');
|
|
1479
|
-
return;
|
|
1480
|
-
}
|
|
1481
|
-
const frameKey = sprite.frameKeys[frameNum];`;
|
|
1482
|
-
if (content.includes(oldLine)) {
|
|
1483
|
-
modified = modified.replace(oldLine, newLines);
|
|
1484
|
-
// 同时替换 atlas 的访问
|
|
1485
|
-
const oldAtlas = 'const atlas = this.wheel.element.sprite.atlas;';
|
|
1486
|
-
const newAtlas = 'const atlas = sprite.atlas;';
|
|
1487
|
-
modified = modified.replace(oldAtlas, newAtlas);
|
|
1488
|
-
// 添加对 atlas.frames 的空值检查
|
|
1489
|
-
const oldRect = 'const rect = atlas.frames[frameKey].rect;';
|
|
1490
|
-
const newRect = `if (!atlas.frames || !atlas.frames[frameKey]) {
|
|
1491
|
-
console.warn('[AimAdjustmentBar] Atlas frame not found:', frameKey);
|
|
1492
|
-
return;
|
|
1493
|
-
}
|
|
1494
|
-
const rect = atlas.frames[frameKey].rect;`;
|
|
1495
|
-
modified = modified.replace(oldRect, newRect);
|
|
1496
|
-
fixCount++;
|
|
1497
|
-
console.log(`[SourceBuilder] 修复 ${scriptName}: sprite 空值检查`);
|
|
1498
|
-
}
|
|
1499
|
-
}
|
|
1500
|
-
// 可以在这里添加更多已知问题的修复...
|
|
1501
|
-
if (fixCount > 0) {
|
|
1502
|
-
console.log(`[SourceBuilder] 共修复 ${scriptName} 中的 ${fixCount} 个已知问题`);
|
|
1503
|
-
}
|
|
1504
|
-
return modified;
|
|
1505
|
-
}
|
|
1506
|
-
/**
|
|
1507
|
-
* 重写 pc.app 访问为 window.pc.app
|
|
1508
|
-
*
|
|
1509
|
-
* 问题背景:
|
|
1510
|
-
* 在 ESM 模式下,用户脚本通过 `import * as pc from 'playcanvas'` 导入。
|
|
1511
|
-
* ESM 命名空间对象是静态的、冻结的,无法在运行时添加 `app` 属性。
|
|
1512
|
-
* 但 PlayCanvas 脚本习惯使用 `pc.app.root`、`pc.app.assets` 等方式访问应用实例。
|
|
1513
|
-
*
|
|
1514
|
-
* 解决方案:
|
|
1515
|
-
* 将代码中的 `pc.app` 重写为 `window.pc.app`,因为 `window.pc` 是可变的,
|
|
1516
|
-
* 在 index.esm.mjs 中会设置 `window.pc.app = app`。
|
|
1517
|
-
*/
|
|
1518
|
-
function rewritePcAppAccess(content) {
|
|
1519
|
-
// 匹配 pc.app 的访问模式
|
|
1520
|
-
// 不匹配已经是 window.pc.app 的情况
|
|
1521
|
-
// 使用负向后瞻确保前面不是 window. 或其他字母
|
|
1522
|
-
// 使用两个步骤:
|
|
1523
|
-
// 1. 先统计需要替换的数量
|
|
1524
|
-
// 2. 再执行替换
|
|
1525
|
-
const pcAppRegex = /(?<!window\.)(?<!\w)pc\.app\b/g;
|
|
1526
|
-
// 统计匹配数量(在替换前)
|
|
1527
|
-
const matches = content.match(pcAppRegex);
|
|
1528
|
-
const matchCount = matches ? matches.length : 0;
|
|
1529
|
-
// 如果没有需要替换的内容,直接返回
|
|
1530
|
-
if (matchCount === 0) {
|
|
1531
|
-
return content;
|
|
1532
|
-
}
|
|
1533
|
-
// 执行替换
|
|
1534
|
-
const modified = content.replace(pcAppRegex, 'window.pc.app');
|
|
1535
|
-
console.log(`[SourceBuilder] 重写了 ${matchCount} 处 pc.app -> window.pc.app`);
|
|
1536
|
-
return modified;
|
|
1537
|
-
}
|
|
1538
|
-
/**
|
|
1539
|
-
* 构建脚本的文件夹路径(从 asset.path 数组)
|
|
1540
|
-
*/
|
|
1541
|
-
function buildScriptFolderPath(pathIds, folderMap) {
|
|
1542
|
-
const pathNames = [];
|
|
1543
|
-
// 跳过根文件夹(第一个元素),构建路径
|
|
1544
|
-
for (let i = 1; i < pathIds.length; i++) {
|
|
1545
|
-
const folderId = String(pathIds[i]);
|
|
1546
|
-
const folderName = folderMap.get(folderId);
|
|
1547
|
-
if (folderName) {
|
|
1548
|
-
pathNames.push(folderName);
|
|
1549
|
-
}
|
|
1550
|
-
}
|
|
1551
|
-
return pathNames.join('/');
|
|
1552
|
-
}
|
|
1553
|
-
/**
|
|
1554
|
-
* 根据 import map 确定目标路径
|
|
1555
|
-
*/
|
|
1556
|
-
function resolveTargetPathFromImportMap(folderPath, filename, importMap) {
|
|
1557
|
-
const imports = importMap.content.imports || {};
|
|
1558
|
-
// 尝试匹配 import map 中的前缀
|
|
1559
|
-
for (const [prefix, target] of Object.entries(imports)) {
|
|
1560
|
-
// prefix 可能是 "Gameplay/" 这样的目录前缀
|
|
1561
|
-
if (prefix.endsWith('/')) {
|
|
1562
|
-
const prefixName = prefix.slice(0, -1); // 移除末尾的 '/'
|
|
1563
|
-
// 检查文件夹路径是否以该前缀开始
|
|
1564
|
-
if (folderPath === prefixName || folderPath.startsWith(prefixName + '/')) {
|
|
1565
|
-
// 计算相对于前缀的剩余路径
|
|
1566
|
-
const relativePath = folderPath === prefixName
|
|
1567
|
-
? ''
|
|
1568
|
-
: folderPath.slice(prefixName.length + 1);
|
|
1569
|
-
// 构建目标路径(使用正斜杠,因为 ESM import 需要 URL 风格路径)
|
|
1570
|
-
const targetBase = target.startsWith('./') ? target.slice(2) : target;
|
|
1571
|
-
const resultPath = relativePath
|
|
1572
|
-
? path.join(targetBase, relativePath, filename)
|
|
1573
|
-
: path.join(targetBase, filename);
|
|
1574
|
-
// 确保使用正斜杠(Windows 兼容)
|
|
1575
|
-
return resultPath.replace(/\\/g, '/');
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
}
|
|
1579
|
-
// 如果没有匹配的前缀,使用原始路径
|
|
1580
|
-
const defaultPath = folderPath ? path.join(folderPath, filename) : filename;
|
|
1581
|
-
// 确保使用正斜杠(Windows 兼容)
|
|
1582
|
-
return defaultPath.replace(/\\/g, '/');
|
|
1583
|
-
}
|
|
1584
|
-
/**
|
|
1585
|
-
* 复制 Import Map 中引用的第三方库文件
|
|
1586
|
-
* 例如 planck.mjs 等
|
|
1587
|
-
*/
|
|
1588
|
-
async function copyImportMapLibraries(projectConfig, projectDir, outputDir, importMap) {
|
|
1589
|
-
const imports = importMap.content.imports || {};
|
|
1590
|
-
const assets = projectConfig.format === 'playcanvas'
|
|
1591
|
-
? projectConfig.assets
|
|
1592
|
-
: projectConfig.assets;
|
|
1593
|
-
for (const [key, value] of Object.entries(imports)) {
|
|
1594
|
-
// 跳过目录前缀(以 / 结尾的)
|
|
1595
|
-
if (key.endsWith('/'))
|
|
1596
|
-
continue;
|
|
1597
|
-
// 跳过 playcanvas 引擎(由模板处理)
|
|
1598
|
-
if (key === 'playcanvas')
|
|
1599
|
-
continue;
|
|
1600
|
-
// 处理单个文件的导入(如 "planck": "./Lib/planck.mjs")
|
|
1601
|
-
let targetPath = value;
|
|
1602
|
-
// 修复路径(./Lib/ -> ./)
|
|
1603
|
-
if (targetPath.startsWith('./Lib/')) {
|
|
1604
|
-
targetPath = './' + targetPath.slice(6);
|
|
1605
|
-
}
|
|
1606
|
-
// 移除 ./ 前缀
|
|
1607
|
-
const outputRelPath = targetPath.startsWith('./') ? targetPath.slice(2) : targetPath;
|
|
1608
|
-
const outputPath = path.join(outputDir, outputRelPath);
|
|
1609
|
-
// 检查目标文件是否已存在(可能已被 copyUserScriptsForESM 复制)
|
|
1610
|
-
try {
|
|
1611
|
-
await fs.access(outputPath);
|
|
1612
|
-
console.log(`[ESM] 第三方库已存在,跳过: ${key} -> ${outputRelPath}`);
|
|
1613
|
-
continue;
|
|
1614
|
-
}
|
|
1615
|
-
catch {
|
|
1616
|
-
// 文件不存在,需要复制
|
|
1617
|
-
}
|
|
1618
|
-
// 查找源文件
|
|
1619
|
-
// 1. 首先检查是否是 asset 引用(通过 name 查找),使用统一的解析函数
|
|
1620
|
-
let sourceFound = false;
|
|
1621
|
-
const filename = path.basename(outputRelPath);
|
|
1622
|
-
for (const [assetId, asset] of Object.entries(assets)) {
|
|
1623
|
-
const assetData = asset;
|
|
1624
|
-
if (assetData.type !== 'script')
|
|
1625
|
-
continue;
|
|
1626
|
-
if (assetData.name !== key && assetData.file?.filename !== filename)
|
|
1627
|
-
continue;
|
|
1628
|
-
// 使用统一的解析函数查找源文件(支持 PlayCraft Git 仓库结构)
|
|
1629
|
-
const sourcePath = await resolveScriptSourcePath(assetData, assetId, projectDir, assets);
|
|
1630
|
-
if (sourcePath) {
|
|
1631
|
-
try {
|
|
1632
|
-
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1633
|
-
await fs.copyFile(sourcePath, outputPath);
|
|
1634
|
-
console.log(`[ESM] 复制第三方库: ${key} -> ${outputRelPath}`);
|
|
1635
|
-
sourceFound = true;
|
|
1636
|
-
}
|
|
1637
|
-
catch (error) {
|
|
1638
|
-
console.warn(`[ESM] 无法复制第三方库 ${key}:`, error);
|
|
1639
|
-
}
|
|
1640
|
-
break;
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
// 2. 如果没有在 assets 中找到,尝试在项目目录中直接查找
|
|
1644
|
-
if (!sourceFound) {
|
|
1645
|
-
// 尝试原始路径(例如 ./Lib/planck.mjs)
|
|
1646
|
-
const originalPath = value.startsWith('./') ? value.slice(2) : value;
|
|
1647
|
-
const candidates = [
|
|
1648
|
-
path.join(projectDir, originalPath),
|
|
1649
|
-
path.join(projectDir, filename),
|
|
1650
|
-
path.join(projectDir, 'Lib', filename),
|
|
1651
|
-
// PlayCraft Git 仓库结构
|
|
1652
|
-
path.join(projectDir, 'assets', filename),
|
|
1653
|
-
path.join(projectDir, 'assets', originalPath),
|
|
1654
|
-
];
|
|
1655
|
-
for (const candidate of candidates) {
|
|
1656
|
-
try {
|
|
1657
|
-
await fs.access(candidate);
|
|
1658
|
-
await fs.mkdir(path.dirname(outputPath), { recursive: true });
|
|
1659
|
-
await fs.copyFile(candidate, outputPath);
|
|
1660
|
-
console.log(`[ESM] 复制第三方库(从目录): ${key} -> ${outputRelPath}`);
|
|
1661
|
-
sourceFound = true;
|
|
1662
|
-
break;
|
|
1663
|
-
}
|
|
1664
|
-
catch {
|
|
1665
|
-
// 继续尝试
|
|
1666
|
-
}
|
|
1667
|
-
}
|
|
1668
|
-
}
|
|
1669
|
-
if (!sourceFound) {
|
|
1670
|
-
console.warn(`[ESM] 未找到第三方库 ${key} 的源文件`);
|
|
1671
|
-
}
|
|
1672
|
-
}
|
|
1673
|
-
}
|